Repository: rust-lang/rust-analyzer
Pull request #16938 (2024-03-24 14:41:17)

Implement `BeginPanic` handling in const eval
for #16935, needs some figuring out of how to write these tests correctly

Veykril: I pushed a fix to the minicore fixture which changes the failure of one of the tests
Veykril: There were some more issues in the minicore definition (it was written with signatures in mind only so some functions were just lacking bodies etc), now both tests are running into execution limits (probably executing `loop {}`s but I am not sure why, I don't know hwo the current formatting infra works wrt to const eval)

Patch:
diff --git a/.github/workflows/metrics.yaml b/.github/workflows/metrics.yaml
index b6cd4a795a..de61b2389a 100644
--- a/.github/workflows/metrics.yaml
+++ b/.github/workflows/metrics.yaml
@@ -58,7 +58,7 @@ jobs:
           key: ${{ runner.os }}-target-${{ github.sha }}
 
       - name: Upload build metrics
-        uses: actions/upload-artifact@v4
+        uses: actions/upload-artifact@v3
         with:
           name: build-${{ github.sha }}
           path: target/build.json
@@ -95,7 +95,7 @@ jobs:
         run: cargo xtask metrics "${{ matrix.names }}"
 
       - name: Upload metrics
-        uses: actions/upload-artifact@v4
+        uses: actions/upload-artifact@v3
         with:
           name: ${{ matrix.names }}-${{ github.sha }}
           path: target/${{ matrix.names }}.json
@@ -109,32 +109,32 @@ jobs:
         uses: actions/checkout@v4
 
       - name: Download build metrics
-        uses: actions/download-artifact@v4
+        uses: actions/download-artifact@v3
         with:
           name: build-${{ github.sha }}
 
       - name: Download self metrics
-        uses: actions/download-artifact@v4
+        uses: actions/download-artifact@v3
         with:
           name: self-${{ github.sha }}
 
       - name: Download ripgrep-13.0.0 metrics
-        uses: actions/download-artifact@v4
+        uses: actions/download-artifact@v3
         with:
           name: ripgrep-13.0.0-${{ github.sha }}
 
       - name: Download webrender-2022 metrics
-        uses: actions/download-artifact@v4
+        uses: actions/download-artifact@v3
         with:
           name: webrender-2022-${{ github.sha }}
 
       - name: Download diesel-1.4.8 metrics
-        uses: actions/download-artifact@v4
+        uses: actions/download-artifact@v3
         with:
           name: diesel-1.4.8-${{ github.sha }}
 
       - name: Download hyper-0.14.18 metrics
-        uses: actions/download-artifact@v4
+        uses: actions/download-artifact@v3
         with:
           name: hyper-0.14.18-${{ github.sha }}
 
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
deleted file mode 100644
index da65b034be..0000000000
--- a/CONTRIBUTING.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# Contributing to rust-analyzer
-
-Thank you for your interest in contributing to rust-analyzer! There are many ways to contribute
-and we appreciate all of them.
-
-To get a quick overview of the crates and structure of the project take a look at the
-[./docs/dev](./docs/dev) folder.
-
-If you have any questions please ask them in the [rust-analyzer zulip stream](
-https://rust-lang.zulipchat.com/#narrow/stream/185405-t-compiler.2Frust-analyzer) or if unsure where
-to start out when working on a concrete issue drop a comment on the related issue for mentoring
-instructions (general discussions are recommended to happen on zulip though).
-
-## Fixing a bug or improving a feature
-
-Generally it's fine to just work on these kinds of things and put a pull-request out for it. If there
-is an issue accompanying it make sure to link it in the pull request description so it can be closed
-afterwards or linked for context.
-
-If you want to find something to fix or work on keep a look out for the `C-bug` and `C-enhancement`
-labels.
-
-## Implementing a new feature
-
-It's advised to first open an issue for any kind of new feature so the team can tell upfront whether
-the feature is desirable or not before any implementation work happens. We want to minimize the
-possibility of someone putting a lot of work into a feature that is then going to waste as we deem
-it out of scope (be it due to generally not fitting in with rust-analyzer, or just not having the
-maintenance capacity). If there already is a feature issue open but it is not clear whether it is
-considered accepted feel free to just drop a comment and ask!
diff --git a/README.md b/README.md
index 552f71f151..8c3f6f8468 100644
--- a/README.md
+++ b/README.md
@@ -13,9 +13,8 @@ https://rust-analyzer.github.io/manual.html#installation
 
 ## Documentation
 
-If you want to **contribute** to rust-analyzer check out the [CONTRIBUTING.md](./CONTRIBUTING.md) or
-if you are just curious about how things work under the hood, check the [./docs/dev](./docs/dev)
-folder.
+If you want to **contribute** to rust-analyzer or are just curious about how
+things work under the hood, check the [./docs/dev](./docs/dev) folder.
 
 If you want to **use** rust-analyzer's language server with your editor of
 choice, check [the manual](https://rust-analyzer.github.io/manual.html) folder.
diff --git a/crates/base-db/src/input.rs b/crates/base-db/src/input.rs
index 240af7925c..6a8ab71624 100644
--- a/crates/base-db/src/input.rs
+++ b/crates/base-db/src/input.rs
@@ -295,30 +295,11 @@ pub struct CrateData {
     pub is_proc_macro: bool,
 }
 
-#[derive(Default, Clone, PartialEq, Eq)]
+#[derive(Default, Debug, Clone, PartialEq, Eq)]
 pub struct Env {
     entries: FxHashMap<String, String>,
 }
 
-impl fmt::Debug for Env {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        struct EnvDebug<'s>(Vec<(&'s String, &'s String)>);
-
-        impl fmt::Debug for EnvDebug<'_> {
-            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-                f.debug_map().entries(self.0.iter().copied()).finish()
-            }
-        }
-        f.debug_struct("Env")
-            .field("entries", &{
-                let mut entries: Vec<_> = self.entries.iter().collect();
-                entries.sort();
-                EnvDebug(entries)
-            })
-            .finish()
-    }
-}
-
 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
 pub struct Dependency {
     pub crate_id: CrateId,
@@ -350,11 +331,10 @@ impl CrateGraph {
         version: Option<String>,
         cfg_options: Arc<CfgOptions>,
         potential_cfg_options: Option<Arc<CfgOptions>>,
-        mut env: Env,
+        env: Env,
         is_proc_macro: bool,
         origin: CrateOrigin,
     ) -> CrateId {
-        env.entries.shrink_to_fit();
         let data = CrateData {
             root_file_id,
             edition,
@@ -671,24 +651,16 @@ impl FromIterator<(String, String)> for Env {
 }
 
 impl Env {
-    pub fn set(&mut self, env: &str, value: impl Into<String>) {
-        self.entries.insert(env.to_owned(), value.into());
+    pub fn set(&mut self, env: &str, value: String) {
+        self.entries.insert(env.to_owned(), value);
     }
 
     pub fn get(&self, env: &str) -> Option<String> {
         self.entries.get(env).cloned()
     }
 
-    pub fn extend_from_other(&mut self, other: &Env) {
-        self.entries.extend(other.entries.iter().map(|(x, y)| (x.to_owned(), y.to_owned())));
-    }
-}
-
-impl From<Env> for Vec<(String, String)> {
-    fn from(env: Env) -> Vec<(String, String)> {
-        let mut entries: Vec<_> = env.entries.into_iter().collect();
-        entries.sort();
-        entries
+    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
+        self.entries.iter().map(|(k, v)| (k.as_str(), v.as_str()))
     }
 }
 
diff --git a/crates/cfg/src/lib.rs b/crates/cfg/src/lib.rs
index 9a365889e6..454d6fc538 100644
--- a/crates/cfg/src/lib.rs
+++ b/crates/cfg/src/lib.rs
@@ -58,6 +58,13 @@ impl CfgOptions {
         self.enabled.insert(CfgAtom::KeyValue { key, value });
     }
 
+    pub fn difference<'a>(
+        &'a self,
+        other: &'a CfgOptions,
+    ) -> impl Iterator<Item = &'a CfgAtom> + 'a {
+        self.enabled.difference(&other.enabled)
+    }
+
     pub fn apply_diff(&mut self, diff: CfgDiff) {
         for atom in diff.enable {
             self.enabled.insert(atom);
diff --git a/crates/hir-def/Cargo.toml b/crates/hir-def/Cargo.toml
index 41c59ea0d9..523ff6fc40 100644
--- a/crates/hir-def/Cargo.toml
+++ b/crates/hir-def/Cargo.toml
@@ -54,7 +54,7 @@ test-utils.workspace = true
 test-fixture.workspace = true
 
 [features]
-in-rust-tree = ["hir-expand/in-rust-tree"]
+in-rust-tree = []
 
 [lints]
 workspace = true
diff --git a/crates/hir-def/src/attr.rs b/crates/hir-def/src/attr.rs
index d9eeffd798..f4f78ce6a4 100644
--- a/crates/hir-def/src/attr.rs
+++ b/crates/hir-def/src/attr.rs
@@ -5,7 +5,7 @@ pub mod builtin;
 #[cfg(test)]
 mod tests;
 
-use std::{borrow::Cow, hash::Hash, ops, slice::Iter as SliceIter};
+use std::{hash::Hash, ops, slice::Iter as SliceIter};
 
 use base_db::CrateId;
 use cfg::{CfgExpr, CfgOptions};
@@ -573,10 +573,6 @@ impl<'attr> AttrQuery<'attr> {
         self.attrs().find_map(|attr| attr.string_value())
     }
 
-    pub fn string_value_unescape(self) -> Option<Cow<'attr, str>> {
-        self.attrs().find_map(|attr| attr.string_value_unescape())
-    }
-
     pub fn exists(self) -> bool {
         self.attrs().next().is_some()
     }
diff --git a/crates/hir-def/src/body/lower.rs b/crates/hir-def/src/body/lower.rs
index 340e95dbc2..f58228c45f 100644
--- a/crates/hir-def/src/body/lower.rs
+++ b/crates/hir-def/src/body/lower.rs
@@ -1869,42 +1869,45 @@ impl ExprCollector<'_> {
     ) -> ExprId {
         match count {
             Some(FormatCount::Literal(n)) => {
-                match LangItem::FormatCount.ty_rel_path(self.db, self.krate, name![Is]) {
-                    Some(count_is) => {
-                        let count_is = self.alloc_expr_desugared(Expr::Path(count_is));
-                        let args = self.alloc_expr_desugared(Expr::Literal(Literal::Uint(
-                            *n as u128,
-                            Some(BuiltinUint::Usize),
-                        )));
-                        self.alloc_expr_desugared(Expr::Call {
-                            callee: count_is,
-                            args: Box::new([args]),
-                            is_assignee_expr: false,
-                        })
-                    }
-                    None => self.missing_expr(),
-                }
+                let args = self.alloc_expr_desugared(Expr::Literal(Literal::Uint(
+                    *n as u128,
+                    Some(BuiltinUint::Usize),
+                )));
+                let count_is =
+                    match LangItem::FormatCount.ty_rel_path(self.db, self.krate, name![Is]) {
+                        Some(count_is) => self.alloc_expr_desugared(Expr::Path(count_is)),
+                        None => self.missing_expr(),
+                    };
+                self.alloc_expr_desugared(Expr::Call {
+                    callee: count_is,
+                    args: Box::new([args]),
+                    is_assignee_expr: false,
+                })
             }
             Some(FormatCount::Argument(arg)) => {
                 if let Ok(arg_index) = arg.index {
                     let (i, _) = argmap.insert_full((arg_index, ArgumentType::Usize));
 
-                    match LangItem::FormatCount.ty_rel_path(self.db, self.krate, name![Param]) {
-                        Some(count_param) => {
-                            let count_param = self.alloc_expr_desugared(Expr::Path(count_param));
-                            let args = self.alloc_expr_desugared(Expr::Literal(Literal::Uint(
-                                i as u128,
-                                Some(BuiltinUint::Usize),
-                            )));
-                            self.alloc_expr_desugared(Expr::Call {
-                                callee: count_param,
-                                args: Box::new([args]),
-                                is_assignee_expr: false,
-                            })
-                        }
+                    let args = self.alloc_expr_desugared(Expr::Literal(Literal::Uint(
+                        i as u128,
+                        Some(BuiltinUint::Usize),
+                    )));
+                    let count_param = match LangItem::FormatCount.ty_rel_path(
+                        self.db,
+                        self.krate,
+                        name![Param],
+                    ) {
+                        Some(count_param) => self.alloc_expr_desugared(Expr::Path(count_param)),
                         None => self.missing_expr(),
-                    }
+                    };
+                    self.alloc_expr_desugared(Expr::Call {
+                        callee: count_param,
+                        args: Box::new([args]),
+                        is_assignee_expr: false,
+                    })
                 } else {
+                    // FIXME: This drops arg causing it to potentially not be resolved/type checked
+                    // when typing?
                     self.missing_expr()
                 }
             }
@@ -1925,7 +1928,8 @@ impl ExprCollector<'_> {
     fn make_argument(&mut self, arg: ExprId, ty: ArgumentType) -> ExprId {
         use ArgumentType::*;
         use FormatTrait::*;
-        match LangItem::FormatArgument.ty_rel_path(
+
+        let new_fn = match LangItem::FormatArgument.ty_rel_path(
             self.db,
             self.krate,
             match ty {
@@ -1941,16 +1945,14 @@ impl ExprCollector<'_> {
                 Usize => name![from_usize],
             },
         ) {
-            Some(new_fn) => {
-                let new_fn = self.alloc_expr_desugared(Expr::Path(new_fn));
-                self.alloc_expr_desugared(Expr::Call {
-                    callee: new_fn,
-                    args: Box::new([arg]),
-                    is_assignee_expr: false,
-                })
-            }
+            Some(new_fn) => self.alloc_expr_desugared(Expr::Path(new_fn)),
             None => self.missing_expr(),
-        }
+        };
+        self.alloc_expr_desugared(Expr::Call {
+            callee: new_fn,
+            args: Box::new([arg]),
+            is_assignee_expr: false,
+        })
     }
     // endregion: format
 }
diff --git a/crates/hir-def/src/nameres/collector.rs b/crates/hir-def/src/nameres/collector.rs
index 0a6cd0fe9e..0a74123abb 100644
--- a/crates/hir-def/src/nameres/collector.rs
+++ b/crates/hir-def/src/nameres/collector.rs
@@ -1917,7 +1917,7 @@ impl ModCollector<'_, '_> {
     }
 
     fn collect_module(&mut self, module_id: FileItemTreeId<Mod>, attrs: &Attrs) {
-        let path_attr = attrs.by_key("path").string_value_unescape();
+        let path_attr = attrs.by_key("path").string_value();
         let is_macro_use = attrs.by_key("macro_use").exists();
         let module = &self.item_tree[module_id];
         match &module.kind {
@@ -1931,8 +1931,7 @@ impl ModCollector<'_, '_> {
                     module_id,
                 );
 
-                let Some(mod_dir) =
-                    self.mod_dir.descend_into_definition(&module.name, path_attr.as_deref())
+                let Some(mod_dir) = self.mod_dir.descend_into_definition(&module.name, path_attr)
                 else {
                     return;
                 };
@@ -1953,12 +1952,8 @@ impl ModCollector<'_, '_> {
             ModKind::Outline => {
                 let ast_id = AstId::new(self.file_id(), module.ast_id);
                 let db = self.def_collector.db;
-                match self.mod_dir.resolve_declaration(
-                    db,
-                    self.file_id(),
-                    &module.name,
-                    path_attr.as_deref(),
-                ) {
+                match self.mod_dir.resolve_declaration(db, self.file_id(), &module.name, path_attr)
+                {
                     Ok((file_id, is_mod_rs, mod_dir)) => {
                         let item_tree = db.file_item_tree(file_id.into());
                         let krate = self.def_collector.def_map.krate;
diff --git a/crates/hir-expand/Cargo.toml b/crates/hir-expand/Cargo.toml
index ca05618aec..a9eeb58b2b 100644
--- a/crates/hir-expand/Cargo.toml
+++ b/crates/hir-expand/Cargo.toml
@@ -37,8 +37,5 @@ parser.workspace = true
 [dev-dependencies]
 expect-test = "1.4.0"
 
-[features]
-in-rust-tree = ["syntax/in-rust-tree"]
-
 [lints]
 workspace = true
diff --git a/crates/hir-expand/src/attrs.rs b/crates/hir-expand/src/attrs.rs
index f8bf88d83c..f1540498f2 100644
--- a/crates/hir-expand/src/attrs.rs
+++ b/crates/hir-expand/src/attrs.rs
@@ -1,5 +1,5 @@
 //! A higher level attributes based on TokenTree, with also some shortcuts.
-use std::{borrow::Cow, fmt, ops};
+use std::{fmt, ops};
 
 use base_db::CrateId;
 use cfg::CfgExpr;
@@ -8,7 +8,6 @@ use intern::Interned;
 use mbe::{syntax_node_to_token_tree, DelimiterKind, Punct};
 use smallvec::{smallvec, SmallVec};
 use span::{Span, SyntaxContextId};
-use syntax::unescape;
 use syntax::{ast, format_smolstr, match_ast, AstNode, AstToken, SmolStr, SyntaxNode};
 use triomphe::ThinArc;
 
@@ -55,7 +54,8 @@ impl RawAttrs {
                     Attr {
                         id,
                         input: Some(Interned::new(AttrInput::Literal(tt::Literal {
-                            text: SmolStr::new(format_smolstr!("\"{}\"", Self::escape_chars(doc))),
+                            // FIXME: Escape quotes from comment content
+                            text: SmolStr::new(format_smolstr!("\"{doc}\"",)),
                             span,
                         }))),
                         path: Interned::new(ModPath::from(crate::name!(doc))),
@@ -74,10 +74,6 @@ impl RawAttrs {
         RawAttrs { entries }
     }
 
-    fn escape_chars(s: &str) -> String {
-        s.replace('\\', r#"\\"#).replace('"', r#"\""#)
-    }
-
     pub fn from_attrs_owner(
         db: &dyn ExpandDatabase,
         owner: InFile<&dyn ast::HasAttrs>,
@@ -301,18 +297,6 @@ impl Attr {
         }
     }
 
-    pub fn string_value_unescape(&self) -> Option<Cow<'_, str>> {
-        match self.input.as_deref()? {
-            AttrInput::Literal(it) => match it.text.strip_prefix('r') {
-                Some(it) => {
-                    it.trim_matches('#').strip_prefix('"')?.strip_suffix('"').map(Cow::Borrowed)
-                }
-                None => it.text.strip_prefix('"')?.strip_suffix('"').and_then(unescape),
-            },
-            _ => None,
-        }
-    }
-
     /// #[path(ident)]
     pub fn single_ident_value(&self) -> Option<&tt::Ident> {
         match self.input.as_deref()? {
@@ -362,33 +346,6 @@ impl Attr {
     }
 }
 
-fn unescape(s: &str) -> Option<Cow<'_, str>> {
-    let mut buf = String::new();
-    let mut prev_end = 0;
-    let mut has_error = false;
-    unescape::unescape_unicode(s, unescape::Mode::Str, &mut |char_range, unescaped_char| match (
-        unescaped_char,
-        buf.capacity() == 0,
-    ) {
-        (Ok(c), false) => buf.push(c),
-        (Ok(_), true) if char_range.len() == 1 && char_range.start == prev_end => {
-            prev_end = char_range.end
-        }
-        (Ok(c), true) => {
-            buf.reserve_exact(s.len());
-            buf.push_str(&s[..prev_end]);
-            buf.push(c);
-        }
-        (Err(_), _) => has_error = true,
-    });
-
-    match (has_error, buf.capacity() == 0) {
-        (true, _) => None,
-        (false, false) => Some(Cow::Owned(buf)),
-        (false, true) => Some(Cow::Borrowed(s)),
-    }
-}
-
 pub fn collect_attrs(
     owner: &dyn ast::HasAttrs,
 ) -> impl Iterator<Item = (AttrId, Either<ast::Attr, ast::Comment>)> {
diff --git a/crates/hir-expand/src/db.rs b/crates/hir-expand/src/db.rs
index d7233a8923..97fa9cf2cc 100644
--- a/crates/hir-expand/src/db.rs
+++ b/crates/hir-expand/src/db.rs
@@ -3,7 +3,7 @@
 use base_db::{salsa, CrateId, FileId, SourceDatabase};
 use either::Either;
 use limit::Limit;
-use mbe::{syntax_node_to_token_tree, MatchedArmIndex};
+use mbe::syntax_node_to_token_tree;
 use rustc_hash::FxHashSet;
 use span::{AstIdMap, Span, SyntaxContextData, SyntaxContextId};
 use syntax::{ast, AstNode, Parse, SyntaxElement, SyntaxError, SyntaxNode, SyntaxToken, T};
@@ -313,10 +313,9 @@ fn parse_macro_expansion(
     let loc = db.lookup_intern_macro_call(macro_file.macro_call_id);
     let edition = loc.def.edition;
     let expand_to = loc.expand_to();
-    let mbe::ValueResult { value: (tt, matched_arm), err } =
-        macro_expand(db, macro_file.macro_call_id, loc);
+    let mbe::ValueResult { value: tt, err } = macro_expand(db, macro_file.macro_call_id, loc);
 
-    let (parse, mut rev_token_map) = token_tree_to_syntax_node(
+    let (parse, rev_token_map) = token_tree_to_syntax_node(
         match &tt {
             CowArc::Arc(it) => it,
             CowArc::Owned(it) => it,
@@ -324,7 +323,6 @@ fn parse_macro_expansion(
         expand_to,
         edition,
     );
-    rev_token_map.matched_arm = matched_arm;
 
     ExpandResult { value: (parse, Arc::new(rev_token_map)), err }
 }
@@ -546,13 +544,11 @@ fn macro_expand(
     db: &dyn ExpandDatabase,
     macro_call_id: MacroCallId,
     loc: MacroCallLoc,
-) -> ExpandResult<(CowArc<tt::Subtree>, MatchedArmIndex)> {
+) -> ExpandResult<CowArc<tt::Subtree>> {
     let _p = tracing::span!(tracing::Level::INFO, "macro_expand").entered();
 
-    let (ExpandResult { value: (tt, matched_arm), err }, span) = match loc.def.kind {
-        MacroDefKind::ProcMacro(..) => {
-            return db.expand_proc_macro(macro_call_id).map(CowArc::Arc).zip_val(None)
-        }
+    let (ExpandResult { value: tt, err }, span) = match loc.def.kind {
+        MacroDefKind::ProcMacro(..) => return db.expand_proc_macro(macro_call_id).map(CowArc::Arc),
         _ => {
             let (macro_arg, undo_info, span) =
                 db.macro_arg_considering_derives(macro_call_id, &loc.kind);
@@ -564,10 +560,10 @@ fn macro_expand(
                         .decl_macro_expander(loc.def.krate, id)
                         .expand(db, arg.clone(), macro_call_id, span),
                     MacroDefKind::BuiltIn(it, _) => {
-                        it.expand(db, macro_call_id, arg, span).map_err(Into::into).zip_val(None)
+                        it.expand(db, macro_call_id, arg, span).map_err(Into::into)
                     }
                     MacroDefKind::BuiltInDerive(it, _) => {
-                        it.expand(db, macro_call_id, arg, span).map_err(Into::into).zip_val(None)
+                        it.expand(db, macro_call_id, arg, span).map_err(Into::into)
                     }
                     MacroDefKind::BuiltInEager(it, _) => {
                         // This might look a bit odd, but we do not expand the inputs to eager macros here.
@@ -578,8 +574,7 @@ fn macro_expand(
                         // As such we just return the input subtree here.
                         let eager = match &loc.kind {
                             MacroCallKind::FnLike { eager: None, .. } => {
-                                return ExpandResult::ok(CowArc::Arc(macro_arg.clone()))
-                                    .zip_val(None);
+                                return ExpandResult::ok(CowArc::Arc(macro_arg.clone()));
                             }
                             MacroCallKind::FnLike { eager: Some(eager), .. } => Some(&**eager),
                             _ => None,
@@ -591,12 +586,12 @@ fn macro_expand(
                             // FIXME: We should report both errors!
                             res.err = error.clone().or(res.err);
                         }
-                        res.zip_val(None)
+                        res
                     }
                     MacroDefKind::BuiltInAttr(it, _) => {
                         let mut res = it.expand(db, macro_call_id, arg, span);
                         fixup::reverse_fixups(&mut res.value, &undo_info);
-                        res.zip_val(None)
+                        res
                     }
                     _ => unreachable!(),
                 };
@@ -608,18 +603,16 @@ fn macro_expand(
     if !loc.def.is_include() {
         // Set a hard limit for the expanded tt
         if let Err(value) = check_tt_count(&tt) {
-            return value
-                .map(|()| {
-                    CowArc::Owned(tt::Subtree {
-                        delimiter: tt::Delimiter::invisible_spanned(span),
-                        token_trees: Box::new([]),
-                    })
+            return value.map(|()| {
+                CowArc::Owned(tt::Subtree {
+                    delimiter: tt::Delimiter::invisible_spanned(span),
+                    token_trees: Box::new([]),
                 })
-                .zip_val(matched_arm);
+            });
         }
     }
 
-    ExpandResult { value: (CowArc::Owned(tt), matched_arm), err }
+    ExpandResult { value: CowArc::Owned(tt), err }
 }
 
 fn proc_macro_span(db: &dyn ExpandDatabase, ast: AstId<ast::Fn>) -> Span {
diff --git a/crates/hir-expand/src/declarative.rs b/crates/hir-expand/src/declarative.rs
index 66465ce600..f9ea8e2ea5 100644
--- a/crates/hir-expand/src/declarative.rs
+++ b/crates/hir-expand/src/declarative.rs
@@ -3,7 +3,6 @@ use std::sync::OnceLock;
 
 use base_db::{CrateId, VersionReq};
 use span::{Edition, MacroCallId, Span, SyntaxContextId};
-use stdx::TupleExt;
 use syntax::{ast, AstNode};
 use triomphe::Arc;
 
@@ -31,7 +30,7 @@ impl DeclarativeMacroExpander {
         tt: tt::Subtree,
         call_id: MacroCallId,
         span: Span,
-    ) -> ExpandResult<(tt::Subtree, Option<u32>)> {
+    ) -> ExpandResult<tt::Subtree> {
         let loc = db.lookup_intern_macro_call(call_id);
         let toolchain = db.toolchain(loc.def.krate);
         let new_meta_vars = toolchain.as_ref().map_or(false, |version| {
@@ -47,7 +46,7 @@ impl DeclarativeMacroExpander {
         });
         match self.mac.err() {
             Some(_) => ExpandResult::new(
-                (tt::Subtree::empty(tt::DelimSpan { open: span, close: span }), None),
+                tt::Subtree::empty(tt::DelimSpan { open: span, close: span }),
                 ExpandError::MacroDefinition,
             ),
             None => self
@@ -91,7 +90,6 @@ impl DeclarativeMacroExpander {
             None => self
                 .mac
                 .expand(&tt, |_| (), new_meta_vars, call_site, def_site_edition)
-                .map(TupleExt::head)
                 .map_err(Into::into),
         }
     }
diff --git a/crates/hir-expand/src/lib.rs b/crates/hir-expand/src/lib.rs
index 338bd25ede..db8bbeccef 100644
--- a/crates/hir-expand/src/lib.rs
+++ b/crates/hir-expand/src/lib.rs
@@ -3,7 +3,7 @@
 //! Specifically, it implements a concept of `MacroFile` -- a file whose syntax
 //! tree originates not from the text of some `FileId`, but from some macro
 //! expansion.
-#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
+
 #![warn(rust_2018_idioms, unused_lifetimes)]
 
 pub mod attrs;
diff --git a/crates/hir-ty/Cargo.toml b/crates/hir-ty/Cargo.toml
index a83ee9824e..bf47374016 100644
--- a/crates/hir-ty/Cargo.toml
+++ b/crates/hir-ty/Cargo.toml
@@ -61,7 +61,7 @@ test-utils.workspace = true
 test-fixture.workspace = true
 
 [features]
-in-rust-tree = ["hir-expand/in-rust-tree"]
+in-rust-tree = []
 
 [lints]
 workspace = true
diff --git a/crates/hir-ty/src/chalk_ext.rs b/crates/hir-ty/src/chalk_ext.rs
index 0bf01b0bc6..d99ef6679e 100644
--- a/crates/hir-ty/src/chalk_ext.rs
+++ b/crates/hir-ty/src/chalk_ext.rs
@@ -27,6 +27,7 @@ pub trait TyExt {
     fn is_scalar(&self) -> bool;
     fn is_floating_point(&self) -> bool;
     fn is_never(&self) -> bool;
+    fn is_str(&self) -> bool;
     fn is_unknown(&self) -> bool;
     fn contains_unknown(&self) -> bool;
     fn is_ty_var(&self) -> bool;
@@ -87,6 +88,10 @@ impl TyExt for Ty {
         matches!(self.kind(Interner), TyKind::Never)
     }
 
+    fn is_str(&self) -> bool {
+        matches!(self.kind(Interner), TyKind::Str)
+    }
+
     fn is_unknown(&self) -> bool {
         matches!(self.kind(Interner), TyKind::Error)
     }
diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs
index 045ffb418c..2de1aa30c9 100644
--- a/crates/hir-ty/src/mir/eval.rs
+++ b/crates/hir-ty/src/mir/eval.rs
@@ -428,6 +428,17 @@ impl MirEvalError {
         }
         Ok(())
     }
+
+    pub fn is_panic(&self) -> Option<&str> {
+        let mut err = self;
+        while let MirEvalError::InFunction(e, _) = err {
+            err = e;
+        }
+        match err {
+            MirEvalError::Panic(msg) => Some(msg),
+            _ => None,
+        }
+    }
 }
 
 impl std::fmt::Debug for MirEvalError {
@@ -1138,7 +1149,7 @@ impl Evaluator<'_> {
                 let mut ty = self.operand_ty(lhs, locals)?;
                 while let TyKind::Ref(_, _, z) = ty.kind(Interner) {
                     ty = z.clone();
-                    let size = if ty.kind(Interner) == &TyKind::Str {
+                    let size = if ty.is_str() {
                         if *op != BinOp::Eq {
                             never!("Only eq is builtin for `str`");
                         }
diff --git a/crates/hir-ty/src/mir/eval/shim.rs b/crates/hir-ty/src/mir/eval/shim.rs
index fee3dd3ada..3438712049 100644
--- a/crates/hir-ty/src/mir/eval/shim.rs
+++ b/crates/hir-ty/src/mir/eval/shim.rs
@@ -49,6 +49,7 @@ impl Evaluator<'_> {
         if self.not_special_fn_cache.borrow().contains(&def) {
             return Ok(false);
         }
+
         let function_data = self.db.function_data(def);
         let is_intrinsic = match &function_data.abi {
             Some(abi) => *abi == Interned::new_str("rust-intrinsic"),
@@ -131,9 +132,7 @@ impl Evaluator<'_> {
             return Ok(true);
         }
         if let Some(it) = self.detect_lang_function(def) {
-            let arg_bytes =
-                args.iter().map(|it| Ok(it.get(self)?.to_owned())).collect::<Result<Vec<_>>>()?;
-            let result = self.exec_lang_item(it, generic_args, &arg_bytes, locals, span)?;
+            let result = self.exec_lang_item(it, generic_args, args, locals, span)?;
             destination.write_from_bytes(self, &result)?;
             return Ok(true);
         }
@@ -311,16 +310,20 @@ impl Evaluator<'_> {
 
     fn detect_lang_function(&self, def: FunctionId) -> Option<LangItem> {
         use LangItem::*;
-        let candidate = self.db.lang_attr(def.into())?;
+        let attrs = self.db.attrs(def.into());
+
+        if attrs.by_key("rustc_const_panic_str").exists() {
+            // `#[rustc_const_panic_str]` is treated like `lang = "begin_panic"` by rustc CTFE.
+            return Some(LangItem::BeginPanic);
+        }
+
+        let candidate = attrs.by_key("lang").string_value().and_then(LangItem::from_str)?;
         // We want to execute these functions with special logic
         // `PanicFmt` is not detected here as it's redirected later.
         if [BeginPanic, SliceLen, DropInPlace].contains(&candidate) {
             return Some(candidate);
         }
-        if self.db.attrs(def.into()).by_key("rustc_const_panic_str").exists() {
-            // `#[rustc_const_panic_str]` is treated like `lang = "begin_panic"` by rustc CTFE.
-            return Some(LangItem::BeginPanic);
-        }
+
         None
     }
 
@@ -328,18 +331,52 @@ impl Evaluator<'_> {
         &mut self,
         it: LangItem,
         generic_args: &Substitution,
-        args: &[Vec<u8>],
+        args: &[IntervalAndTy],
         locals: &Locals,
         span: MirSpan,
     ) -> Result<Vec<u8>> {
         use LangItem::*;
         let mut args = args.iter();
         match it {
-            BeginPanic => Err(MirEvalError::Panic("<unknown-panic-payload>".to_owned())),
+            BeginPanic => {
+                let mut arg = args
+                    .next()
+                    .ok_or(MirEvalError::InternalError(
+                        "argument of BeginPanic is not provided".into(),
+                    ))?
+                    .clone();
+                while let TyKind::Ref(_, _, ty) = arg.ty.kind(Interner) {
+                    if ty.is_str() {
+                        let (pointee, metadata) = arg.interval.get(self)?.split_at(self.ptr_size());
+                        let len = from_bytes!(usize, metadata);
+
+                        return {
+                            Err(MirEvalError::Panic(
+                                std::str::from_utf8(
+                                    self.read_memory(Address::from_bytes(pointee)?, len)?,
+                                )
+                                .unwrap()
+                                .to_owned(),
+                            ))
+                        };
+                    }
+                    let size = self.size_of_sized(ty, locals, "begin panic arg")?;
+                    let pointee = arg.interval.get(self)?;
+                    arg = IntervalAndTy {
+                        interval: Interval::new(Address::from_bytes(pointee)?, size),
+                        ty: ty.clone(),
+                    };
+                }
+                Err(MirEvalError::Panic(format!(
+                    "unknown-panic-payload: {:?}",
+                    arg.ty.kind(Interner)
+                )))
+            }
             SliceLen => {
                 let arg = args.next().ok_or(MirEvalError::InternalError(
                     "argument of <[T]>::len() is not provided".into(),
                 ))?;
+                let arg = arg.get(self)?;
                 let ptr_size = arg.len() / 2;
                 Ok(arg[ptr_size..].into())
             }
@@ -353,6 +390,7 @@ impl Evaluator<'_> {
                 let arg = args.next().ok_or(MirEvalError::InternalError(
                     "argument of drop_in_place is not provided".into(),
                 ))?;
+                let arg = arg.interval.get(self)?.to_owned();
                 self.run_drop_glue_deep(
                     ty.clone(),
                     locals,
diff --git a/crates/hir/Cargo.toml b/crates/hir/Cargo.toml
index 6d7ecd1e50..190722075a 100644
--- a/crates/hir/Cargo.toml
+++ b/crates/hir/Cargo.toml
@@ -33,7 +33,7 @@ tt.workspace = true
 span.workspace = true
 
 [features]
-in-rust-tree = ["hir-expand/in-rust-tree"]
+in-rust-tree = []
 
 [lints]
 workspace = true
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs
index e792e159ac..e1516fcdcb 100644
--- a/crates/hir/src/semantics.rs
+++ b/crates/hir/src/semantics.rs
@@ -1246,17 +1246,6 @@ impl<'db> SemanticsImpl<'db> {
             .map_or(false, |m| matches!(m.id, MacroId::ProcMacroId(..)))
     }
 
-    pub fn resolve_macro_call_arm(&self, macro_call: &ast::MacroCall) -> Option<u32> {
-        let sa = self.analyze(macro_call.syntax())?;
-        self.db
-            .parse_macro_expansion(
-                sa.expand(self.db, self.wrap_node_infile(macro_call.clone()).as_ref())?,
-            )
-            .value
-            .1
-            .matched_arm
-    }
-
     pub fn is_unsafe_macro_call(&self, macro_call: &ast::MacroCall) -> bool {
         let sa = match self.analyze(macro_call.syntax()) {
             Some(it) => it,
diff --git a/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs b/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs
deleted file mode 100644
index 5459bd334c..0000000000
--- a/crates/ide-assists/src/handlers/convert_from_to_tryfrom.rs
+++ /dev/null
@@ -1,250 +0,0 @@
-use ide_db::{famous_defs::FamousDefs, traits::resolve_target_trait};
-use itertools::Itertools;
-use syntax::{
-    ast::{self, make, AstNode, HasName},
-    ted,
-};
-
-use crate::{AssistContext, AssistId, AssistKind, Assists};
-
-// Assist: convert_from_to_tryfrom
-//
-// Converts a From impl to a TryFrom impl, wrapping returns in `Ok`.
-//
-// ```
-// # //- minicore: from
-// impl $0From<usize> for Thing {
-//     fn from(val: usize) -> Self {
-//         Thing {
-//             b: val.to_string(),
-//             a: val
-//         }
-//     }
-// }
-// ```
-// ->
-// ```
-// impl TryFrom<usize> for Thing {
-//     type Error = ${0:()};
-//
-//     fn try_from(val: usize) -> Result<Self, Self::Error> {
-//         Ok(Thing {
-//             b: val.to_string(),
-//             a: val
-//         })
-//     }
-// }
-// ```
-pub(crate) fn convert_from_to_tryfrom(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
-    let impl_ = ctx.find_node_at_offset::<ast::Impl>()?;
-    let trait_ty = impl_.trait_()?;
-
-    let module = ctx.sema.scope(impl_.syntax())?.module();
-
-    let from_type = match &trait_ty {
-        ast::Type::PathType(path) => {
-            path.path()?.segment()?.generic_arg_list()?.generic_args().next()?
-        }
-        _ => return None,
-    };
-
-    let associated_items = impl_.assoc_item_list()?;
-    let from_fn = associated_items.assoc_items().find_map(|item| {
-        if let ast::AssocItem::Fn(f) = item {
-            if f.name()?.text() == "from" {
-                return Some(f);
-            }
-        };
-        None
-    })?;
-
-    let from_fn_name = from_fn.name()?;
-    let from_fn_return_type = from_fn.ret_type()?.ty()?;
-
-    let return_exprs = from_fn.body()?.syntax().descendants().filter_map(ast::ReturnExpr::cast);
-    let tail_expr = from_fn.body()?.tail_expr()?;
-
-    if resolve_target_trait(&ctx.sema, &impl_)?
-        != FamousDefs(&ctx.sema, module.krate()).core_convert_From()?
-    {
-        return None;
-    }
-
-    acc.add(
-        AssistId("convert_from_to_tryfrom", AssistKind::RefactorRewrite),
-        "Convert From to TryFrom",
-        impl_.syntax().text_range(),
-        |builder| {
-            let trait_ty = builder.make_mut(trait_ty);
-            let from_fn_return_type = builder.make_mut(from_fn_return_type);
-            let from_fn_name = builder.make_mut(from_fn_name);
-            let tail_expr = builder.make_mut(tail_expr);
-            let return_exprs = return_exprs.map(|r| builder.make_mut(r)).collect_vec();
-            let associated_items = builder.make_mut(associated_items).clone();
-
-            ted::replace(
-                trait_ty.syntax(),
-                make::ty(&format!("TryFrom<{from_type}>")).syntax().clone_for_update(),
-            );
-            ted::replace(
-                from_fn_return_type.syntax(),
-                make::ty("Result<Self, Self::Error>").syntax().clone_for_update(),
-            );
-            ted::replace(from_fn_name.syntax(), make::name("try_from").syntax().clone_for_update());
-            ted::replace(
-                tail_expr.syntax(),
-                wrap_ok(tail_expr.clone()).syntax().clone_for_update(),
-            );
-
-            for r in return_exprs {
-                let t = r.expr().unwrap_or_else(make::expr_unit);
-                ted::replace(t.syntax(), wrap_ok(t.clone()).syntax().clone_for_update());
-            }
-
-            let error_type = ast::AssocItem::TypeAlias(make::ty_alias(
-                "Error",
-                None,
-                None,
-                None,
-                Some((make::ty_unit(), None)),
-            ))
-            .clone_for_update();
-
-            if let Some(cap) = ctx.config.snippet_cap {
-                if let ast::AssocItem::TypeAlias(type_alias) = &error_type {
-                    if let Some(ty) = type_alias.ty() {
-                        builder.add_placeholder_snippet(cap, ty);
-                    }
-                }
-            }
-
-            associated_items.add_item_at_start(error_type);
-        },
-    )
-}
-
-fn wrap_ok(expr: ast::Expr) -> ast::Expr {
-    make::expr_call(
-        make::expr_path(make::ext::ident_path("Ok")),
-        make::arg_list(std::iter::once(expr)),
-    )
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-
-    use crate::tests::{check_assist, check_assist_not_applicable};
-
-    #[test]
-    fn converts_from_to_tryfrom() {
-        check_assist(
-            convert_from_to_tryfrom,
-            r#"
-//- minicore: from
-struct Foo(String);
-
-impl $0From<String> for Foo {
-    fn from(val: String) -> Self {
-        if val == "bar" {
-            return Foo(val);
-        }
-        Self(val)
-    }
-}
-            "#,
-            r#"
-struct Foo(String);
-
-impl TryFrom<String> for Foo {
-    type Error = ${0:()};
-
-    fn try_from(val: String) -> Result<Self, Self::Error> {
-        if val == "bar" {
-            return Ok(Foo(val));
-        }
-        Ok(Self(val))
-    }
-}
-            "#,
-        );
-    }
-
-    #[test]
-    fn converts_from_to_tryfrom_nested_type() {
-        check_assist(
-            convert_from_to_tryfrom,
-            r#"
-//- minicore: from
-struct Foo(String);
-
-impl $0From<Option<String>> for Foo {
-    fn from(val: Option<String>) -> Self {
-        match val {
-            Some(val) => Foo(val),
-            None => Foo("".to_string())
-        }
-    }
-}
-            "#,
-            r#"
-struct Foo(String);
-
-impl TryFrom<Option<String>> for Foo {
-    type Error = ${0:()};
-
-    fn try_from(val: Option<String>) -> Result<Self, Self::Error> {
-        Ok(match val {
-            Some(val) => Foo(val),
-            None => Foo("".to_string())
-        })
-    }
-}
-            "#,
-        );
-    }
-
-    #[test]
-    fn converts_from_to_tryfrom_preserves_lifetimes() {
-        check_assist(
-            convert_from_to_tryfrom,
-            r#"
-//- minicore: from
-struct Foo<'a>(&'a str);
-
-impl<'a> $0From<&'a str> for Foo<'a> {
-    fn from(val: &'a str) -> Self {
-        Self(val)
-    }
-}
-            "#,
-            r#"
-struct Foo<'a>(&'a str);
-
-impl<'a> TryFrom<&'a str> for Foo<'a> {
-    type Error = ${0:()};
-
-    fn try_from(val: &'a str) -> Result<Self, Self::Error> {
-        Ok(Self(val))
-    }
-}
-            "#,
-        );
-    }
-
-    #[test]
-    fn other_trait_not_applicable() {
-        check_assist_not_applicable(
-            convert_from_to_tryfrom,
-            r#"
-struct Foo(String);
-
-impl $0TryFrom<String> for Foo {
-    fn try_from(val: String) -> Result<Self, Self::Error> {
-        Ok(Self(val))
-    }
-}
-            "#,
-        );
-    }
-}
diff --git a/crates/ide-assists/src/lib.rs b/crates/ide-assists/src/lib.rs
index 0df5e913a5..024448ef1e 100644
--- a/crates/ide-assists/src/lib.rs
+++ b/crates/ide-assists/src/lib.rs
@@ -116,7 +116,6 @@ mod handlers {
     mod change_visibility;
     mod convert_bool_then;
     mod convert_comment_block;
-    mod convert_from_to_tryfrom;
     mod convert_integer_literal;
     mod convert_into_to_from;
     mod convert_iter_for_each_to_for;
@@ -239,7 +238,6 @@ mod handlers {
             convert_bool_then::convert_bool_then_to_if,
             convert_bool_then::convert_if_to_bool_then,
             convert_comment_block::convert_comment_block,
-            convert_from_to_tryfrom::convert_from_to_tryfrom,
             convert_integer_literal::convert_integer_literal,
             convert_into_to_from::convert_into_to_from,
             convert_iter_for_each_to_for::convert_iter_for_each_to_for,
diff --git a/crates/ide-db/src/documentation.rs b/crates/ide-db/src/documentation.rs
index 58e77b95c3..72ca354365 100644
--- a/crates/ide-db/src/documentation.rs
+++ b/crates/ide-db/src/documentation.rs
@@ -91,10 +91,8 @@ pub fn docs_with_rangemap(
     db: &dyn DefDatabase,
     attrs: &AttrsWithOwner,
 ) -> Option<(Documentation, DocsRangeMap)> {
-    let docs = attrs
-        .by_key("doc")
-        .attrs()
-        .filter_map(|attr| attr.string_value_unescape().map(|s| (s, attr.id)));
+    let docs =
+        attrs.by_key("doc").attrs().filter_map(|attr| attr.string_value().map(|s| (s, attr.id)));
     let indent = doc_indent(attrs);
     let mut buf = String::new();
     let mut mapping = Vec::new();
@@ -134,7 +132,7 @@ pub fn docs_with_rangemap(
 }
 
 pub fn docs_from_attrs(attrs: &hir::Attrs) -> Option<String> {
-    let docs = attrs.by_key("doc").attrs().filter_map(|attr| attr.string_value_unescape());
+    let docs = attrs.by_key("doc").attrs().filter_map(|attr| attr.string_value());
     let indent = doc_indent(attrs);
     let mut buf = String::new();
     for doc in docs {
@@ -272,9 +270,10 @@ fn doc_indent(attrs: &hir::Attrs) -> usize {
     attrs
         .by_key("doc")
         .attrs()
-        .filter_map(|attr| attr.string_value()) // no need to use unescape version here
+        .filter_map(|attr| attr.string_value())
         .flat_map(|s| s.lines())
-        .filter_map(|line| line.chars().position(|c| !c.is_whitespace()))
+        .filter(|line| !line.chars().all(|c| c.is_whitespace()))
+        .map(|line| line.chars().take_while(|c| c.is_whitespace()).count())
         .min()
         .unwrap_or(0)
 }
diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs
index 95de3c88c8..822751c0e4 100644
--- a/crates/ide/src/hover.rs
+++ b/crates/ide/src/hover.rs
@@ -14,7 +14,7 @@ use ide_db::{
     helpers::pick_best_token,
     FxIndexSet, RootDatabase,
 };
-use itertools::{multizip, Itertools};
+use itertools::Itertools;
 use syntax::{ast, match_ast, AstNode, AstToken, SyntaxKind::*, SyntaxNode, T};
 
 use crate::{
@@ -149,7 +149,7 @@ fn hover_simple(
     if let Some(doc_comment) = token_as_doc_comment(&original_token) {
         cov_mark::hit!(no_highlight_on_comment_hover);
         return doc_comment.get_definition_with_descend_at(sema, offset, |def, node, range| {
-            let res = hover_for_definition(sema, file_id, def, &node, None, config);
+            let res = hover_for_definition(sema, file_id, def, &node, config);
             Some(RangeInfo::new(range, res))
         });
     }
@@ -162,7 +162,6 @@ fn hover_simple(
             file_id,
             Definition::from(resolution?),
             &original_token.parent()?,
-            None,
             config,
         );
         return Some(RangeInfo::new(range, res));
@@ -197,29 +196,6 @@ fn hover_simple(
             descended()
                 .filter_map(|token| {
                     let node = token.parent()?;
-
-                    // special case macro calls, we wanna render the invoked arm index
-                    if let Some(name) = ast::NameRef::cast(node.clone()) {
-                        if let Some(path_seg) =
-                            name.syntax().parent().and_then(ast::PathSegment::cast)
-                        {
-                            if let Some(macro_call) = path_seg
-                                .parent_path()
-                                .syntax()
-                                .parent()
-                                .and_then(ast::MacroCall::cast)
-                            {
-                                if let Some(macro_) = sema.resolve_macro_call(&macro_call) {
-                                    return Some(vec![(
-                                        Definition::Macro(macro_),
-                                        sema.resolve_macro_call_arm(&macro_call),
-                                        node,
-                                    )]);
-                                }
-                            }
-                        }
-                    }
-
                     match IdentClass::classify_node(sema, &node)? {
                         // It's better for us to fall back to the keyword hover here,
                         // rendering poll is very confusing
@@ -228,19 +204,20 @@ fn hover_simple(
                         IdentClass::NameRefClass(NameRefClass::ExternCrateShorthand {
                             decl,
                             ..
-                        }) => Some(vec![(Definition::ExternCrateDecl(decl), None, node)]),
+                        }) => Some(vec![(Definition::ExternCrateDecl(decl), node)]),
 
                         class => Some(
-                            multizip((class.definitions(), iter::repeat(None), iter::repeat(node)))
+                            class
+                                .definitions()
+                                .into_iter()
+                                .zip(iter::repeat(node))
                                 .collect::<Vec<_>>(),
                         ),
                     }
                 })
                 .flatten()
-                .unique_by(|&(def, _, _)| def)
-                .map(|(def, macro_arm, node)| {
-                    hover_for_definition(sema, file_id, def, &node, macro_arm, config)
-                })
+                .unique_by(|&(def, _)| def)
+                .map(|(def, node)| hover_for_definition(sema, file_id, def, &node, config))
                 .reduce(|mut acc: HoverResult, HoverResult { markup, actions }| {
                     acc.actions.extend(actions);
                     acc.markup = Markup::from(format!("{}\n---\n{markup}", acc.markup));
@@ -397,7 +374,6 @@ pub(crate) fn hover_for_definition(
     file_id: FileId,
     def: Definition,
     scope_node: &SyntaxNode,
-    macro_arm: Option<u32>,
     config: &HoverConfig,
 ) -> HoverResult {
     let famous_defs = match &def {
@@ -422,8 +398,7 @@ pub(crate) fn hover_for_definition(
     };
     let notable_traits = def_ty.map(|ty| notable_traits(db, &ty)).unwrap_or_default();
 
-    let markup =
-        render::definition(sema.db, def, famous_defs.as_ref(), &notable_traits, macro_arm, config);
+    let markup = render::definition(sema.db, def, famous_defs.as_ref(), &notable_traits, config);
     HoverResult {
         markup: render::process_markup(sema.db, def, &markup, config),
         actions: [
diff --git a/crates/ide/src/hover/render.rs b/crates/ide/src/hover/render.rs
index 3f0fc85134..7579d4d6d8 100644
--- a/crates/ide/src/hover/render.rs
+++ b/crates/ide/src/hover/render.rs
@@ -403,7 +403,6 @@ pub(super) fn definition(
     def: Definition,
     famous_defs: Option<&FamousDefs<'_, '_>>,
     notable_traits: &[(Trait, Vec<(Option<Type>, Name)>)],
-    macro_arm: Option<u32>,
     config: &HoverConfig,
 ) -> Markup {
     let mod_path = definition_mod_path(db, &def);
@@ -414,13 +413,6 @@ pub(super) fn definition(
         Definition::Adt(Adt::Struct(struct_)) => {
             struct_.display_limited(db, config.max_struct_field_count).to_string()
         }
-        Definition::Macro(it) => {
-            let mut label = it.display(db).to_string();
-            if let Some(macro_arm) = macro_arm {
-                format_to!(label, " // matched arm #{}", macro_arm);
-            }
-            label
-        }
         _ => def.label(db),
     };
     let docs = def.docs(db, famous_defs);
diff --git a/crates/ide/src/static_index.rs b/crates/ide/src/static_index.rs
index ca013da709..3fef16df25 100644
--- a/crates/ide/src/static_index.rs
+++ b/crates/ide/src/static_index.rs
@@ -188,14 +188,7 @@ impl StaticIndex<'_> {
             } else {
                 let it = self.tokens.insert(TokenStaticData {
                     documentation: documentation_for_definition(&sema, def, &node),
-                    hover: Some(hover_for_definition(
-                        &sema,
-                        file_id,
-                        def,
-                        &node,
-                        None,
-                        &hover_config,
-                    )),
+                    hover: Some(hover_for_definition(&sema, file_id, def, &node, &hover_config)),
                     definition: def.try_to_nav(self.db).map(UpmappingResult::call_site).map(|it| {
                         FileRange { file_id: it.file_id, range: it.focus_or_full_range() }
                     }),
diff --git a/crates/load-cargo/Cargo.toml b/crates/load-cargo/Cargo.toml
index b6f90ec53b..48e84a7b25 100644
--- a/crates/load-cargo/Cargo.toml
+++ b/crates/load-cargo/Cargo.toml
@@ -28,8 +28,5 @@ tt.workspace = true
 vfs-notify.workspace = true
 vfs.workspace = true
 
-[features]
-in-rust-tree = ["hir-expand/in-rust-tree"]
-
 [lints]
 workspace = true
diff --git a/crates/load-cargo/src/lib.rs b/crates/load-cargo/src/lib.rs
index 31b0c8cdec..79d6fe36b5 100644
--- a/crates/load-cargo/src/lib.rs
+++ b/crates/load-cargo/src/lib.rs
@@ -335,7 +335,7 @@ fn load_crate_graph(
 ) -> RootDatabase {
     let (ProjectWorkspace::Cargo { toolchain, target_layout, .. }
     | ProjectWorkspace::Json { toolchain, target_layout, .. }
-    | ProjectWorkspace::DetachedFile { toolchain, target_layout, .. }) = ws;
+    | ProjectWorkspace::DetachedFiles { toolchain, target_layout, .. }) = ws;
 
     let lru_cap = std::env::var("RA_LRU_CAP").ok().and_then(|it| it.parse::<usize>().ok());
     let mut db = RootDatabase::new(lru_cap);
@@ -407,7 +407,8 @@ impl ProcMacroExpander for Expander {
         call_site: Span,
         mixed_site: Span,
     ) -> Result<tt::Subtree<Span>, ProcMacroExpansionError> {
-        match self.0.expand(subtree, attrs, env.clone(), def_site, call_site, mixed_site) {
+        let env = env.iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect();
+        match self.0.expand(subtree, attrs, env, def_site, call_site, mixed_site) {
             Ok(Ok(subtree)) => Ok(subtree),
             Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err.0)),
             Err(err) => Err(ProcMacroExpansionError::System(err.to_string())),
diff --git a/crates/mbe/src/benchmark.rs b/crates/mbe/src/benchmark.rs
index f4bbaef7af..1dca288017 100644
--- a/crates/mbe/src/benchmark.rs
+++ b/crates/mbe/src/benchmark.rs
@@ -48,7 +48,7 @@ fn benchmark_expand_macro_rules() {
             .map(|(id, tt)| {
                 let res = rules[&id].expand(&tt, |_| (), true, DUMMY, Edition::CURRENT);
                 assert!(res.err.is_none());
-                res.value.0.token_trees.len()
+                res.value.token_trees.len()
             })
             .sum()
     };
diff --git a/crates/mbe/src/expander.rs b/crates/mbe/src/expander.rs
index cfad8bcc0b..2d495da0db 100644
--- a/crates/mbe/src/expander.rs
+++ b/crates/mbe/src/expander.rs
@@ -9,7 +9,7 @@ use rustc_hash::FxHashMap;
 use span::{Edition, Span};
 use syntax::SmolStr;
 
-use crate::{parser::MetaVarKind, ExpandError, ExpandResult, MatchedArmIndex};
+use crate::{parser::MetaVarKind, ExpandError, ExpandResult};
 
 pub(crate) fn expand_rules(
     rules: &[crate::Rule],
@@ -18,9 +18,9 @@ pub(crate) fn expand_rules(
     new_meta_vars: bool,
     call_site: Span,
     def_site_edition: Edition,
-) -> ExpandResult<(tt::Subtree<Span>, MatchedArmIndex)> {
-    let mut match_: Option<(matcher::Match, &crate::Rule, usize)> = None;
-    for (idx, rule) in rules.iter().enumerate() {
+) -> ExpandResult<tt::Subtree<Span>> {
+    let mut match_: Option<(matcher::Match, &crate::Rule)> = None;
+    for rule in rules {
         let new_match = matcher::match_(&rule.lhs, input, def_site_edition);
 
         if new_match.err.is_none() {
@@ -35,34 +35,31 @@ pub(crate) fn expand_rules(
                 call_site,
             );
             if transcribe_err.is_none() {
-                return ExpandResult::ok((value, Some(idx as u32)));
+                return ExpandResult::ok(value);
             }
         }
         // Use the rule if we matched more tokens, or bound variables count
-        if let Some((prev_match, _, _)) = &match_ {
+        if let Some((prev_match, _)) = &match_ {
             if (new_match.unmatched_tts, -(new_match.bound_count as i32))
                 < (prev_match.unmatched_tts, -(prev_match.bound_count as i32))
             {
-                match_ = Some((new_match, rule, idx));
+                match_ = Some((new_match, rule));
             }
         } else {
-            match_ = Some((new_match, rule, idx));
+            match_ = Some((new_match, rule));
         }
     }
-    if let Some((match_, rule, idx)) = match_ {
+    if let Some((match_, rule)) = match_ {
         // if we got here, there was no match without errors
         let ExpandResult { value, err: transcribe_err } =
             transcriber::transcribe(&rule.rhs, &match_.bindings, marker, new_meta_vars, call_site);
-        ExpandResult { value: (value, idx.try_into().ok()), err: match_.err.or(transcribe_err) }
+        ExpandResult { value, err: match_.err.or(transcribe_err) }
     } else {
         ExpandResult::new(
-            (
-                tt::Subtree {
-                    delimiter: tt::Delimiter::invisible_spanned(call_site),
-                    token_trees: Box::default(),
-                },
-                None,
-            ),
+            tt::Subtree {
+                delimiter: tt::Delimiter::invisible_spanned(call_site),
+                token_trees: Box::new([]),
+            },
             ExpandError::NoMatchingRule,
         )
     }
diff --git a/crates/mbe/src/lib.rs b/crates/mbe/src/lib.rs
index d5de56312a..5445f8790f 100644
--- a/crates/mbe/src/lib.rs
+++ b/crates/mbe/src/lib.rs
@@ -122,9 +122,6 @@ impl fmt::Display for CountError {
     }
 }
 
-/// Index of the matched macro arm on successful expansion.
-pub type MatchedArmIndex = Option<u32>;
-
 /// This struct contains AST for a single `macro_rules` definition. What might
 /// be very confusing is that AST has almost exactly the same shape as
 /// `tt::TokenTree`, but there's a crucial difference: in macro rules, `$ident`
@@ -254,7 +251,7 @@ impl DeclarativeMacro {
         new_meta_vars: bool,
         call_site: Span,
         def_site_edition: Edition,
-    ) -> ExpandResult<(tt::Subtree<Span>, MatchedArmIndex)> {
+    ) -> ExpandResult<tt::Subtree<Span>> {
         expander::expand_rules(&self.rules, tt, marker, new_meta_vars, call_site, def_site_edition)
     }
 }
@@ -333,10 +330,6 @@ impl<T, E> ValueResult<T, E> {
         Self { value: Default::default(), err: Some(err) }
     }
 
-    pub fn zip_val<U>(self, other: U) -> ValueResult<(T, U), E> {
-        ValueResult { value: (self.value, other), err: self.err }
-    }
-
     pub fn map<U>(self, f: impl FnOnce(T) -> U) -> ValueResult<U, E> {
         ValueResult { value: f(self.value), err: self.err }
     }
diff --git a/crates/proc-macro-api/src/lib.rs b/crates/proc-macro-api/src/lib.rs
index 0ab16c38c8..3c0c904bab 100644
--- a/crates/proc-macro-api/src/lib.rs
+++ b/crates/proc-macro-api/src/lib.rs
@@ -11,7 +11,6 @@ pub mod msg;
 mod process;
 mod version;
 
-use base_db::Env;
 use indexmap::IndexSet;
 use paths::AbsPathBuf;
 use rustc_hash::FxHashMap;
@@ -153,13 +152,16 @@ impl ProcMacro {
         &self,
         subtree: &tt::Subtree<Span>,
         attr: Option<&tt::Subtree<Span>>,
-        env: Env,
+        env: Vec<(String, String)>,
         def_site: Span,
         call_site: Span,
         mixed_site: Span,
     ) -> Result<Result<tt::Subtree<Span>, PanicMessage>, ServerError> {
         let version = self.process.lock().unwrap_or_else(|e| e.into_inner()).version();
-        let current_dir = env.get("CARGO_MANIFEST_DIR");
+        let current_dir = env
+            .iter()
+            .find(|(name, _)| name == "CARGO_MANIFEST_DIR")
+            .map(|(_, value)| value.clone());
 
         let mut span_data_table = IndexSet::default();
         let def_site = span_data_table.insert_full(def_site).0;
@@ -170,7 +172,7 @@ impl ProcMacro {
             macro_name: self.name.to_string(),
             attributes: attr.map(|subtree| FlatTree::new(subtree, version, &mut span_data_table)),
             lib: self.dylib_path.to_path_buf().into(),
-            env: env.into(),
+            env,
             current_dir,
             has_global_spans: ExpnGlobals {
                 serialize: version >= HAS_GLOBAL_SPANS,
diff --git a/crates/proc-macro-srv-cli/build.rs b/crates/proc-macro-srv-cli/build.rs
deleted file mode 100644
index 07f914fece..0000000000
--- a/crates/proc-macro-srv-cli/build.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-//! This teaches cargo about our cfg(rust_analyzer)
-
-fn main() {
-    println!("cargo:rustc-check-cfg=cfg(rust_analyzer)");
-}
diff --git a/crates/proc-macro-srv/build.rs b/crates/proc-macro-srv/build.rs
index 874d1c6cd3..a8c732f315 100644
--- a/crates/proc-macro-srv/build.rs
+++ b/crates/proc-macro-srv/build.rs
@@ -4,8 +4,6 @@
 use std::{env, fs::File, io::Write, path::PathBuf, process::Command};
 
 fn main() {
-    println!("cargo:rustc-check-cfg=cfg(rust_analyzer)");
-
     let mut path = PathBuf::from(env::var_os("OUT_DIR").unwrap());
     path.push("rustc_version.rs");
     let mut f = File::create(&path).unwrap();
diff --git a/crates/project-model/src/build_scripts.rs b/crates/project-model/src/build_scripts.rs
index fbd423c9ea..26f8f52bbc 100644
--- a/crates/project-model/src/build_scripts.rs
+++ b/crates/project-model/src/build_scripts.rs
@@ -23,18 +23,16 @@ use serde::Deserialize;
 use toolchain::Tool;
 
 use crate::{
-    cfg::CfgFlag, utf8_stdout, CargoConfig, CargoFeatures, CargoWorkspace, InvocationLocation,
+    cfg_flag::CfgFlag, utf8_stdout, CargoConfig, CargoFeatures, CargoWorkspace, InvocationLocation,
     InvocationStrategy, Package, Sysroot, TargetKind,
 };
 
-/// Output of the build script and proc-macro building steps for a workspace.
 #[derive(Debug, Default, Clone, PartialEq, Eq)]
 pub struct WorkspaceBuildScripts {
     outputs: ArenaMap<Package, BuildScriptOutput>,
     error: Option<String>,
 }
 
-/// Output of the build script and proc-macro building step for a concrete package.
 #[derive(Debug, Clone, Default, PartialEq, Eq)]
 pub(crate) struct BuildScriptOutput {
     /// List of config flags defined by this package's build script.
diff --git a/crates/project-model/src/cargo_workspace.rs b/crates/project-model/src/cargo_workspace.rs
index ff7cf144aa..82fee7112f 100644
--- a/crates/project-model/src/cargo_workspace.rs
+++ b/crates/project-model/src/cargo_workspace.rs
@@ -135,20 +135,6 @@ pub struct PackageData {
     pub active_features: Vec<String>,
     /// String representation of package id
     pub id: String,
-    /// Authors as given in the `Cargo.toml`
-    pub authors: Vec<String>,
-    /// Description as given in the `Cargo.toml`
-    pub description: Option<String>,
-    /// Homepage as given in the `Cargo.toml`
-    pub homepage: Option<String>,
-    /// License as given in the `Cargo.toml`
-    pub license: Option<String>,
-    /// License file as given in the `Cargo.toml`
-    pub license_file: Option<Utf8PathBuf>,
-    /// Readme file as given in the `Cargo.toml`
-    pub readme: Option<Utf8PathBuf>,
-    /// Rust version as given in the `Cargo.toml`
-    pub rust_version: Option<semver::Version>,
     /// The contents of [package.metadata.rust-analyzer]
     pub metadata: RustAnalyzerPackageMetaData,
 }
@@ -239,10 +225,6 @@ impl TargetKind {
         }
         TargetKind::Other
     }
-
-    pub fn is_executable(self) -> bool {
-        matches!(self, TargetKind::Bin | TargetKind::Example)
-    }
 }
 
 // Deserialize helper for the cargo metadata
@@ -305,12 +287,6 @@ impl CargoWorkspace {
                     .collect(),
             );
         }
-        // The manifest is a rust file, so this means its a script manifest
-        if cargo_toml.extension().is_some_and(|ext| ext == "rs") {
-            // Deliberately don't set up RUSTC_BOOTSTRAP or a nightly override here, the user should
-            // opt into it themselves.
-            other_options.push("-Zscript".to_owned());
-        }
         meta.other_options(other_options);
 
         // FIXME: Fetching metadata is a slow process, as it might require
@@ -354,13 +330,6 @@ impl CargoWorkspace {
                 repository,
                 edition,
                 metadata,
-                authors,
-                description,
-                homepage,
-                license,
-                license_file,
-                readme,
-                rust_version,
                 ..
             } = meta_pkg;
             let meta = from_value::<PackageMetadata>(metadata).unwrap_or_default();
@@ -379,24 +348,16 @@ impl CargoWorkspace {
             let is_local = source.is_none();
             let is_member = ws_members.contains(&id);
 
-            let manifest = AbsPathBuf::assert(manifest_path);
             let pkg = packages.alloc(PackageData {
                 id: id.repr.clone(),
                 name,
                 version,
-                manifest: manifest.clone().try_into().unwrap(),
+                manifest: AbsPathBuf::assert(manifest_path).try_into().unwrap(),
                 targets: Vec::new(),
                 is_local,
                 is_member,
                 edition,
                 repository,
-                authors,
-                description,
-                homepage,
-                license,
-                license_file,
-                readme,
-                rust_version,
                 dependencies: Vec::new(),
                 features: features.into_iter().collect(),
                 active_features: Vec::new(),
@@ -407,22 +368,11 @@ impl CargoWorkspace {
             for meta_tgt in meta_targets {
                 let cargo_metadata::Target { name, kind, required_features, src_path, .. } =
                     meta_tgt;
-                let kind = TargetKind::new(&kind);
                 let tgt = targets.alloc(TargetData {
                     package: pkg,
                     name,
-                    root: if kind == TargetKind::Bin
-                        && manifest.extension().is_some_and(|ext| ext == "rs")
-                    {
-                        // cargo strips the script part of a cargo script away and places the
-                        // modified manifest file into a special target dir which is then used as
-                        // the source path. We don't want that, we want the original here so map it
-                        // back
-                        manifest.clone()
-                    } else {
-                        AbsPathBuf::assert(src_path)
-                    },
-                    kind,
+                    root: AbsPathBuf::assert(src_path),
+                    kind: TargetKind::new(&kind),
                     required_features,
                 });
                 pkg_data.targets.push(tgt);
diff --git a/crates/project-model/src/cfg.rs b/crates/project-model/src/cfg_flag.rs
similarity index 72%
rename from crates/project-model/src/cfg.rs
rename to crates/project-model/src/cfg_flag.rs
index b409bc1ce7..6192e18da0 100644
--- a/crates/project-model/src/cfg.rs
+++ b/crates/project-model/src/cfg_flag.rs
@@ -3,8 +3,7 @@
 //! rustc main.rs --cfg foo --cfg 'feature="bar"'
 use std::{fmt, str::FromStr};
 
-use cfg::{CfgDiff, CfgOptions};
-use rustc_hash::FxHashMap;
+use cfg::CfgOptions;
 use serde::Serialize;
 
 #[derive(Clone, Eq, PartialEq, Debug, Serialize)]
@@ -71,27 +70,3 @@ impl fmt::Display for CfgFlag {
         }
     }
 }
-
-/// A set of cfg-overrides per crate.
-#[derive(Default, Debug, Clone, Eq, PartialEq)]
-pub struct CfgOverrides {
-    /// A global set of overrides matching all crates.
-    pub global: CfgDiff,
-    /// A set of overrides matching specific crates.
-    pub selective: FxHashMap<String, CfgDiff>,
-}
-
-impl CfgOverrides {
-    pub fn len(&self) -> usize {
-        self.global.len() + self.selective.values().map(|it| it.len()).sum::<usize>()
-    }
-
-    pub fn apply(&self, cfg_options: &mut CfgOptions, name: &str) {
-        if !self.global.is_empty() {
-            cfg_options.apply_diff(self.global.clone());
-        };
-        if let Some(diff) = self.selective.get(name) {
-            cfg_options.apply_diff(diff.clone());
-        };
-    }
-}
diff --git a/crates/project-model/src/env.rs b/crates/project-model/src/env.rs
deleted file mode 100644
index 762e01c917..0000000000
--- a/crates/project-model/src/env.rs
+++ /dev/null
@@ -1,85 +0,0 @@
-//! Cargo-like environment variables injection.
-use base_db::Env;
-use rustc_hash::FxHashMap;
-use toolchain::Tool;
-
-use crate::{utf8_stdout, ManifestPath, PackageData, Sysroot, TargetKind};
-
-/// Recreates the compile-time environment variables that Cargo sets.
-///
-/// Should be synced with
-/// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates>
-///
-/// FIXME: ask Cargo to provide this data instead of re-deriving.
-pub(crate) fn inject_cargo_package_env(env: &mut Env, package: &PackageData) {
-    // FIXME: Missing variables:
-    // CARGO_BIN_NAME, CARGO_BIN_EXE_<name>
-
-    let manifest_dir = package.manifest.parent();
-    env.set("CARGO_MANIFEST_DIR", manifest_dir.as_str());
-
-    env.set("CARGO_PKG_VERSION", package.version.to_string());
-    env.set("CARGO_PKG_VERSION_MAJOR", package.version.major.to_string());
-    env.set("CARGO_PKG_VERSION_MINOR", package.version.minor.to_string());
-    env.set("CARGO_PKG_VERSION_PATCH", package.version.patch.to_string());
-    env.set("CARGO_PKG_VERSION_PRE", package.version.pre.to_string());
-
-    env.set("CARGO_PKG_AUTHORS", package.authors.join(":").clone());
-
-    env.set("CARGO_PKG_NAME", package.name.clone());
-    env.set("CARGO_PKG_DESCRIPTION", package.description.as_deref().unwrap_or_default());
-    env.set("CARGO_PKG_HOMEPAGE", package.homepage.as_deref().unwrap_or_default());
-    env.set("CARGO_PKG_REPOSITORY", package.repository.as_deref().unwrap_or_default());
-    env.set("CARGO_PKG_LICENSE", package.license.as_deref().unwrap_or_default());
-    env.set(
-        "CARGO_PKG_LICENSE_FILE",
-        package.license_file.as_ref().map(ToString::to_string).unwrap_or_default(),
-    );
-    env.set(
-        "CARGO_PKG_README",
-        package.readme.as_ref().map(ToString::to_string).unwrap_or_default(),
-    );
-
-    env.set(
-        "CARGO_PKG_RUST_VERSION",
-        package.rust_version.as_ref().map(ToString::to_string).unwrap_or_default(),
-    );
-}
-
-pub(crate) fn inject_cargo_env(env: &mut Env) {
-    env.set("CARGO", Tool::Cargo.path().to_string());
-}
-
-pub(crate) fn inject_rustc_tool_env(env: &mut Env, cargo_name: &str, kind: TargetKind) {
-    _ = kind;
-    // FIXME
-    // if kind.is_executable() {
-    //     env.set("CARGO_BIN_NAME", cargo_name);
-    // }
-    env.set("CARGO_CRATE_NAME", cargo_name.replace('-', "_"));
-}
-
-pub(crate) fn cargo_config_env(
-    cargo_toml: &ManifestPath,
-    extra_env: &FxHashMap<String, String>,
-    sysroot: Option<&Sysroot>,
-) -> FxHashMap<String, String> {
-    let mut cargo_config = Sysroot::tool(sysroot, Tool::Cargo);
-    cargo_config.envs(extra_env);
-    cargo_config
-        .current_dir(cargo_toml.parent())
-        .args(["-Z", "unstable-options", "config", "get", "env"])
-        .env("RUSTC_BOOTSTRAP", "1");
-    // if successful we receive `env.key.value = "value" per entry
-    tracing::debug!("Discovering cargo config env by {:?}", cargo_config);
-    utf8_stdout(cargo_config).map(parse_output_cargo_config_env).unwrap_or_default()
-}
-
-fn parse_output_cargo_config_env(stdout: String) -> FxHashMap<String, String> {
-    stdout
-        .lines()
-        .filter_map(|l| l.strip_prefix("env."))
-        .filter_map(|l| l.split_once(".value = "))
-        .map(|(key, value)| (key.to_owned(), value.trim_matches('"').to_owned()))
-        .collect()
-}
diff --git a/crates/project-model/src/lib.rs b/crates/project-model/src/lib.rs
index 7f3e35ca5d..28696aa327 100644
--- a/crates/project-model/src/lib.rs
+++ b/crates/project-model/src/lib.rs
@@ -19,8 +19,7 @@
 
 mod build_scripts;
 mod cargo_workspace;
-mod cfg;
-mod env;
+mod cfg_flag;
 mod manifest_path;
 mod project_json;
 mod rustc_cfg;
@@ -48,11 +47,10 @@ pub use crate::{
         CargoConfig, CargoFeatures, CargoWorkspace, Package, PackageData, PackageDependency,
         RustLibSource, Target, TargetData, TargetKind,
     },
-    cfg::CfgOverrides,
     manifest_path::ManifestPath,
     project_json::{ProjectJson, ProjectJsonData},
     sysroot::Sysroot,
-    workspace::{FileLoader, PackageRoot, ProjectWorkspace},
+    workspace::{CfgOverrides, PackageRoot, ProjectWorkspace},
 };
 
 #[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
diff --git a/crates/project-model/src/project_json.rs b/crates/project-model/src/project_json.rs
index fac6eb8ad3..a8e30d2267 100644
--- a/crates/project-model/src/project_json.rs
+++ b/crates/project-model/src/project_json.rs
@@ -55,7 +55,7 @@ use rustc_hash::FxHashMap;
 use serde::{de, Deserialize, Serialize};
 use span::Edition;
 
-use crate::cfg::CfgFlag;
+use crate::cfg_flag::CfgFlag;
 
 /// Roots and crates that compose this Rust project.
 #[derive(Clone, Debug, Eq, PartialEq)]
diff --git a/crates/project-model/src/rustc_cfg.rs b/crates/project-model/src/rustc_cfg.rs
index 4f69b2b96f..501b1fdc8c 100644
--- a/crates/project-model/src/rustc_cfg.rs
+++ b/crates/project-model/src/rustc_cfg.rs
@@ -4,7 +4,7 @@ use anyhow::Context;
 use rustc_hash::FxHashMap;
 use toolchain::Tool;
 
-use crate::{cfg::CfgFlag, utf8_stdout, ManifestPath, Sysroot};
+use crate::{cfg_flag::CfgFlag, utf8_stdout, ManifestPath, Sysroot};
 
 /// Determines how `rustc --print cfg` is discovered and invoked.
 pub(crate) enum RustcCfgConfig<'a> {
@@ -32,6 +32,9 @@ pub(crate) fn get(
         }
     }
 
+    // Add miri cfg, which is useful for mir eval in stdlib
+    res.push(CfgFlag::Atom("miri".into()));
+
     let rustc_cfgs = get_rust_cfgs(target, extra_env, config);
 
     let rustc_cfgs = match rustc_cfgs {
diff --git a/crates/project-model/src/workspace.rs b/crates/project-model/src/workspace.rs
index 98c5a02dcd..00e9c12988 100644
--- a/crates/project-model/src/workspace.rs
+++ b/crates/project-model/src/workspace.rs
@@ -2,7 +2,7 @@
 //! metadata` or `rust-project.json`) into representation stored in the salsa
 //! database -- `CrateGraph`.
 
-use std::{collections::VecDeque, fmt, fs, iter, sync};
+use std::{collections::VecDeque, fmt, fs, iter, str::FromStr, sync};
 
 use anyhow::{format_err, Context};
 use base_db::{
@@ -21,8 +21,7 @@ use triomphe::Arc;
 use crate::{
     build_scripts::BuildScriptOutput,
     cargo_workspace::{DepKind, PackageData, RustLibSource},
-    cfg::{CfgFlag, CfgOverrides},
-    env::{cargo_config_env, inject_cargo_env, inject_cargo_package_env, inject_rustc_tool_env},
+    cfg_flag::CfgFlag,
     project_json::{Crate, CrateArrayIdx},
     rustc_cfg::{self, RustcCfgConfig},
     sysroot::{SysrootCrate, SysrootMode},
@@ -31,7 +30,20 @@ use crate::{
     ProjectJson, ProjectManifest, Sysroot, TargetData, TargetKind, WorkspaceBuildScripts,
 };
 
-pub type FileLoader<'a> = &'a mut dyn for<'b> FnMut(&'b AbsPath) -> Option<FileId>;
+/// A set of cfg-overrides per crate.
+#[derive(Default, Debug, Clone, Eq, PartialEq)]
+pub struct CfgOverrides {
+    /// A global set of overrides matching all crates.
+    pub global: CfgDiff,
+    /// A set of overrides matching specific crates.
+    pub selective: FxHashMap<String, CfgDiff>,
+}
+
+impl CfgOverrides {
+    pub fn len(&self) -> usize {
+        self.global.len() + self.selective.values().map(|it| it.len()).sum::<usize>()
+    }
+}
 
 /// `PackageRoot` describes a package root folder.
 /// Which may be an external dependency, or a member of
@@ -48,46 +60,30 @@ pub struct PackageRoot {
 pub enum ProjectWorkspace {
     /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`.
     Cargo {
-        /// The workspace as returned by `cargo metadata`.
         cargo: CargoWorkspace,
-        /// The build script results for the workspace.
         build_scripts: WorkspaceBuildScripts,
-        /// The sysroot loaded for this workspace.
         sysroot: Result<Sysroot, Option<String>>,
-        /// The rustc workspace loaded for this workspace. An `Err(None)` means loading has been
-        /// disabled or was otherwise not requested.
         rustc: Result<Box<(CargoWorkspace, WorkspaceBuildScripts)>, Option<String>>,
         /// Holds cfg flags for the current target. We get those by running
         /// `rustc --print cfg`.
-        // FIXME: make this a per-crate map, as, eg, build.rs might have a
-        // different target.
+        ///
+        /// FIXME: make this a per-crate map, as, eg, build.rs might have a
+        /// different target.
         rustc_cfg: Vec<CfgFlag>,
-        /// A set of cfg overrides for this workspace.
         cfg_overrides: CfgOverrides,
-        /// The toolchain version used by this workspace.
         toolchain: Option<Version>,
-        /// The target data layout queried for workspace.
         target_layout: TargetLayoutLoadResult,
-        /// Environment variables set in the `.cargo/config` file.
         cargo_config_extra_env: FxHashMap<String, String>,
     },
     /// Project workspace was manually specified using a `rust-project.json` file.
     Json {
-        /// The loaded project json file.
         project: ProjectJson,
-        /// The sysroot loaded for this workspace.
         sysroot: Result<Sysroot, Option<String>>,
         /// Holds cfg flags for the current target. We get those by running
         /// `rustc --print cfg`.
-        // FIXME: make this a per-crate map, as, eg, build.rs might have a
-        // different target.
         rustc_cfg: Vec<CfgFlag>,
-        /// The toolchain version used by this workspace.
         toolchain: Option<Version>,
-        /// The target data layout queried for workspace.
         target_layout: TargetLayoutLoadResult,
-        /// A set of cfg overrides for this workspace.
-        cfg_overrides: CfgOverrides,
     },
     // FIXME: The primary limitation of this approach is that the set of detached files needs to be fixed at the beginning.
     // That's not the end user experience we should strive for.
@@ -99,24 +95,14 @@ pub enum ProjectWorkspace {
     // //
     /// Project with a set of disjoint files, not belonging to any particular workspace.
     /// Backed by basic sysroot crates for basic completion and highlighting.
-    DetachedFile {
-        /// The file in question.
-        file: AbsPathBuf,
-        /// The sysroot loaded for this workspace.
+    DetachedFiles {
+        files: Vec<AbsPathBuf>,
         sysroot: Result<Sysroot, Option<String>>,
         /// Holds cfg flags for the current target. We get those by running
         /// `rustc --print cfg`.
-        // FIXME: make this a per-crate map, as, eg, build.rs might have a
-        // different target.
         rustc_cfg: Vec<CfgFlag>,
-        /// The toolchain version used by this workspace.
         toolchain: Option<Version>,
-        /// The target data layout queried for workspace.
         target_layout: TargetLayoutLoadResult,
-        /// A set of cfg overrides for the files.
-        cfg_overrides: CfgOverrides,
-        /// Is this file a cargo script file?
-        cargo_script: Option<CargoWorkspace>,
     },
 }
 
@@ -155,7 +141,6 @@ impl fmt::Debug for ProjectWorkspace {
                 rustc_cfg,
                 toolchain,
                 target_layout: data_layout,
-                cfg_overrides,
             } => {
                 let mut debug_struct = f.debug_struct("Json");
                 debug_struct.field("n_crates", &project.n_crates());
@@ -165,28 +150,22 @@ impl fmt::Debug for ProjectWorkspace {
                 debug_struct
                     .field("n_rustc_cfg", &rustc_cfg.len())
                     .field("toolchain", &toolchain)
-                    .field("data_layout", &data_layout)
-                    .field("n_cfg_overrides", &cfg_overrides.len());
+                    .field("data_layout", &data_layout);
                 debug_struct.finish()
             }
-            ProjectWorkspace::DetachedFile {
-                file,
+            ProjectWorkspace::DetachedFiles {
+                files,
                 sysroot,
                 rustc_cfg,
                 toolchain,
                 target_layout,
-                cfg_overrides,
-                cargo_script,
             } => f
                 .debug_struct("DetachedFiles")
-                .field("file", &file)
-                .field("cargo_script", &cargo_script.is_some())
+                .field("n_files", &files.len())
                 .field("sysroot", &sysroot.is_ok())
-                .field("cargo_script", &cargo_script.is_some())
                 .field("n_rustc_cfg", &rustc_cfg.len())
                 .field("toolchain", &toolchain)
                 .field("data_layout", &target_layout)
-                .field("n_cfg_overrides", &cfg_overrides.len())
                 .finish(),
         }
     }
@@ -240,7 +219,6 @@ impl ProjectWorkspace {
                     project_json,
                     config.target.as_deref(),
                     &config.extra_env,
-                    &config.cfg_overrides,
                 )
             }
             ProjectManifest::CargoToml(cargo_toml) => {
@@ -382,7 +360,6 @@ impl ProjectWorkspace {
         project_json: ProjectJson,
         target: Option<&str>,
         extra_env: &FxHashMap<String, String>,
-        cfg_overrides: &CfgOverrides,
     ) -> ProjectWorkspace {
         let sysroot = match (project_json.sysroot.clone(), project_json.sysroot_src.clone()) {
             (Some(sysroot), Some(sysroot_src)) => {
@@ -429,86 +406,57 @@ impl ProjectWorkspace {
             rustc_cfg,
             toolchain,
             target_layout: data_layout.map(Arc::from).map_err(|it| Arc::from(it.to_string())),
-            cfg_overrides: cfg_overrides.clone(),
         }
     }
 
     pub fn load_detached_files(
         detached_files: Vec<AbsPathBuf>,
         config: &CargoConfig,
-    ) -> Vec<anyhow::Result<ProjectWorkspace>> {
-        detached_files
-            .into_iter()
-            .map(|detached_file| {
-                let dir = detached_file
-                    .parent()
-                    .ok_or_else(|| format_err!("detached file has no parent"))?;
-                let sysroot = match &config.sysroot {
-                    Some(RustLibSource::Path(path)) => {
-                        Sysroot::with_sysroot_dir(path.clone(), config.sysroot_query_metadata)
-                            .map_err(|e| Some(format!("Failed to find sysroot at {path}:{e}")))
-                    }
-                    Some(RustLibSource::Discover) => {
-                        Sysroot::discover(dir, &config.extra_env, config.sysroot_query_metadata)
-                            .map_err(|e| {
-                                Some(format!(
-                                    "Failed to find sysroot for {dir}. Is rust-src installed? {e}"
-                                ))
-                            })
-                    }
-                    None => Err(None),
-                };
-
-                let sysroot_ref = sysroot.as_ref().ok();
-                let toolchain = match get_toolchain_version(
-                    dir,
-                    sysroot_ref,
-                    Tool::Rustc,
-                    &config.extra_env,
-                    "rustc ",
-                ) {
-                    Ok(it) => it,
-                    Err(e) => {
-                        tracing::error!("{e}");
-                        None
-                    }
-                };
-
-                let rustc_cfg =
-                    rustc_cfg::get(None, &config.extra_env, RustcCfgConfig::Rustc(sysroot_ref));
-                let data_layout = target_data_layout::get(
-                    RustcDataLayoutConfig::Rustc(sysroot_ref),
-                    None,
-                    &config.extra_env,
-                );
+    ) -> anyhow::Result<ProjectWorkspace> {
+        let dir = detached_files
+            .first()
+            .and_then(|it| it.parent())
+            .ok_or_else(|| format_err!("No detached files to load"))?;
+        let sysroot = match &config.sysroot {
+            Some(RustLibSource::Path(path)) => {
+                Sysroot::with_sysroot_dir(path.clone(), config.sysroot_query_metadata)
+                    .map_err(|e| Some(format!("Failed to find sysroot at {path}:{e}")))
+            }
+            Some(RustLibSource::Discover) => Sysroot::discover(
+                dir,
+                &config.extra_env,
+                config.sysroot_query_metadata,
+            )
+            .map_err(|e| {
+                Some(format!("Failed to find sysroot for {dir}. Is rust-src installed? {e}"))
+            }),
+            None => Err(None),
+        };
 
-                let cargo_script = ManifestPath::try_from(detached_file.clone())
-                    .ok()
-                    .and_then(|file| {
-                        CargoWorkspace::fetch_metadata(
-                            &file,
-                            file.parent(),
-                            config,
-                            sysroot_ref,
-                            &|_| (),
-                        )
-                        .ok()
-                    })
-                    .map(CargoWorkspace::new);
+        let sysroot_ref = sysroot.as_ref().ok();
+        let toolchain =
+            match get_toolchain_version(dir, sysroot_ref, Tool::Rustc, &config.extra_env, "rustc ")
+            {
+                Ok(it) => it,
+                Err(e) => {
+                    tracing::error!("{e}");
+                    None
+                }
+            };
 
-                Ok(ProjectWorkspace::DetachedFile {
-                    file: detached_file,
-                    sysroot,
-                    rustc_cfg,
-                    toolchain,
-                    target_layout: data_layout
-                        .map(Arc::from)
-                        .map_err(|it| Arc::from(it.to_string())),
-                    cfg_overrides: config.cfg_overrides.clone(),
-                    cargo_script,
-                })
-            })
-            .collect()
+        let rustc_cfg = rustc_cfg::get(None, &config.extra_env, RustcCfgConfig::Rustc(sysroot_ref));
+        let data_layout = target_data_layout::get(
+            RustcDataLayoutConfig::Rustc(sysroot_ref),
+            None,
+            &config.extra_env,
+        );
+        Ok(ProjectWorkspace::DetachedFiles {
+            files: detached_files,
+            sysroot,
+            rustc_cfg,
+            toolchain,
+            target_layout: data_layout.map(Arc::from).map_err(|it| Arc::from(it.to_string())),
+        })
     }
 
     /// Runs the build scripts for this [`ProjectWorkspace`].
@@ -518,13 +466,7 @@ impl ProjectWorkspace {
         progress: &dyn Fn(String),
     ) -> anyhow::Result<WorkspaceBuildScripts> {
         match self {
-            ProjectWorkspace::DetachedFile {
-                cargo_script: Some(cargo),
-                toolchain,
-                sysroot,
-                ..
-            }
-            | ProjectWorkspace::Cargo { cargo, toolchain, sysroot, .. } => {
+            ProjectWorkspace::Cargo { cargo, toolchain, sysroot, .. } => {
                 WorkspaceBuildScripts::run_for_workspace(
                     config,
                     cargo,
@@ -536,8 +478,9 @@ impl ProjectWorkspace {
                     format!("Failed to run build scripts for {}", cargo.workspace_root())
                 })
             }
-            ProjectWorkspace::DetachedFile { cargo_script: None, .. }
-            | ProjectWorkspace::Json { .. } => Ok(WorkspaceBuildScripts::default()),
+            ProjectWorkspace::Json { .. } | ProjectWorkspace::DetachedFiles { .. } => {
+                Ok(WorkspaceBuildScripts::default())
+            }
         }
     }
 
@@ -593,11 +536,11 @@ impl ProjectWorkspace {
         }
     }
 
-    pub fn workspace_definition_path(&self) -> &AbsPath {
+    pub fn workspace_definition_path(&self) -> Option<&AbsPath> {
         match self {
-            ProjectWorkspace::Cargo { cargo, .. } => cargo.workspace_root(),
-            ProjectWorkspace::Json { project, .. } => project.path(),
-            ProjectWorkspace::DetachedFile { file, .. } => file,
+            ProjectWorkspace::Cargo { cargo, .. } => Some(cargo.workspace_root()),
+            ProjectWorkspace::Json { project, .. } => Some(project.path()),
+            ProjectWorkspace::DetachedFiles { .. } => None,
         }
     }
 
@@ -605,10 +548,10 @@ impl ProjectWorkspace {
         match self {
             ProjectWorkspace::Cargo { sysroot: Ok(sysroot), .. }
             | ProjectWorkspace::Json { sysroot: Ok(sysroot), .. }
-            | ProjectWorkspace::DetachedFile { sysroot: Ok(sysroot), .. } => {
+            | ProjectWorkspace::DetachedFiles { sysroot: Ok(sysroot), .. } => {
                 sysroot.discover_proc_macro_srv()
             }
-            ProjectWorkspace::DetachedFile { .. } => {
+            ProjectWorkspace::DetachedFiles { .. } => {
                 Err(anyhow::format_err!("cannot find proc-macro server, no sysroot was found"))
             }
             ProjectWorkspace::Cargo { cargo, .. } => Err(anyhow::format_err!(
@@ -668,7 +611,6 @@ impl ProjectWorkspace {
                 rustc_cfg: _,
                 toolchain: _,
                 target_layout: _,
-                cfg_overrides: _,
             } => project
                 .crates()
                 .map(|(_, krate)| PackageRoot {
@@ -739,50 +681,15 @@ impl ProjectWorkspace {
                     }))
                     .collect()
             }
-            ProjectWorkspace::DetachedFile { file, cargo_script, sysroot, .. } => {
-                iter::once(PackageRoot {
+            ProjectWorkspace::DetachedFiles { files, sysroot, .. } => files
+                .iter()
+                .map(|detached_file| PackageRoot {
                     is_local: true,
-                    include: vec![file.clone()],
+                    include: vec![detached_file.clone()],
                     exclude: Vec::new(),
                 })
-                .chain(cargo_script.iter().flat_map(|cargo| {
-                    cargo.packages().map(|pkg| {
-                        let is_local = cargo[pkg].is_local;
-                        let pkg_root = cargo[pkg].manifest.parent().to_path_buf();
-
-                        let mut include = vec![pkg_root.clone()];
-
-                        // In case target's path is manually set in Cargo.toml to be
-                        // outside the package root, add its parent as an extra include.
-                        // An example of this situation would look like this:
-                        //
-                        // ```toml
-                        // [lib]
-                        // path = "../../src/lib.rs"
-                        // ```
-                        let extra_targets = cargo[pkg]
-                            .targets
-                            .iter()
-                            .filter(|&&tgt| matches!(cargo[tgt].kind, TargetKind::Lib { .. }))
-                            .filter_map(|&tgt| cargo[tgt].root.parent())
-                            .map(|tgt| tgt.normalize().to_path_buf())
-                            .filter(|path| !path.starts_with(&pkg_root));
-                        include.extend(extra_targets);
-
-                        let mut exclude = vec![pkg_root.join(".git")];
-                        if is_local {
-                            exclude.push(pkg_root.join("target"));
-                        } else {
-                            exclude.push(pkg_root.join("tests"));
-                            exclude.push(pkg_root.join("examples"));
-                            exclude.push(pkg_root.join("benches"));
-                        }
-                        PackageRoot { is_local, include, exclude }
-                    })
-                }))
                 .chain(mk_sysroot(sysroot.as_ref()))
-                .collect()
-            }
+                .collect(),
         }
     }
 
@@ -798,17 +705,16 @@ impl ProjectWorkspace {
                 let sysroot_package_len = sysroot.as_ref().map_or(0, |it| it.num_packages());
                 cargo.packages().len() + sysroot_package_len + rustc_package_len
             }
-            ProjectWorkspace::DetachedFile { sysroot, cargo_script, .. } => {
+            ProjectWorkspace::DetachedFiles { sysroot, files, .. } => {
                 let sysroot_package_len = sysroot.as_ref().map_or(0, |it| it.num_packages());
-                sysroot_package_len
-                    + cargo_script.as_ref().map_or(1, |cargo| cargo.packages().len())
+                sysroot_package_len + files.len()
             }
         }
     }
 
     pub fn to_crate_graph(
         &self,
-        load: FileLoader<'_>,
+        load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
         extra_env: &FxHashMap<String, String>,
     ) -> (CrateGraph, ProcMacroPaths) {
         let _p = tracing::span!(tracing::Level::INFO, "ProjectWorkspace::to_crate_graph").entered();
@@ -820,7 +726,6 @@ impl ProjectWorkspace {
                 rustc_cfg,
                 toolchain: _,
                 target_layout: _,
-                cfg_overrides,
             } => (
                 project_json_to_crate_graph(
                     rustc_cfg.clone(),
@@ -828,7 +733,6 @@ impl ProjectWorkspace {
                     project,
                     sysroot.as_ref().ok(),
                     extra_env,
-                    cfg_overrides,
                 ),
                 sysroot,
             ),
@@ -854,34 +758,19 @@ impl ProjectWorkspace {
                 ),
                 sysroot,
             ),
-            ProjectWorkspace::DetachedFile {
-                file,
+            ProjectWorkspace::DetachedFiles {
+                files,
                 sysroot,
                 rustc_cfg,
                 toolchain: _,
                 target_layout: _,
-                cfg_overrides,
-                cargo_script,
             } => (
-                if let Some(cargo) = cargo_script {
-                    cargo_to_crate_graph(
-                        &mut |path| load(path),
-                        None,
-                        cargo,
-                        sysroot.as_ref().ok(),
-                        rustc_cfg.clone(),
-                        cfg_overrides,
-                        &WorkspaceBuildScripts::default(),
-                    )
-                } else {
-                    detached_file_to_crate_graph(
-                        rustc_cfg.clone(),
-                        load,
-                        file,
-                        sysroot.as_ref().ok(),
-                        cfg_overrides,
-                    )
-                },
+                detached_files_to_crate_graph(
+                    rustc_cfg.clone(),
+                    load,
+                    files,
+                    sysroot.as_ref().ok(),
+                ),
                 sysroot,
             ),
         };
@@ -931,56 +820,35 @@ impl ProjectWorkspace {
                     && cargo_config_extra_env == o_cargo_config_extra_env
             }
             (
-                Self::Json {
-                    project,
-                    sysroot,
-                    rustc_cfg,
-                    toolchain,
-                    target_layout: _,
-                    cfg_overrides,
-                },
+                Self::Json { project, sysroot, rustc_cfg, toolchain, target_layout: _ },
                 Self::Json {
                     project: o_project,
                     sysroot: o_sysroot,
                     rustc_cfg: o_rustc_cfg,
                     toolchain: o_toolchain,
                     target_layout: _,
-                    cfg_overrides: o_cfg_overrides,
                 },
             ) => {
                 project == o_project
                     && rustc_cfg == o_rustc_cfg
                     && sysroot == o_sysroot
                     && toolchain == o_toolchain
-                    && cfg_overrides == o_cfg_overrides
             }
             (
-                Self::DetachedFile {
-                    file,
-                    sysroot,
-                    rustc_cfg,
-                    cargo_script,
-                    toolchain,
-                    target_layout,
-                    cfg_overrides,
-                },
-                Self::DetachedFile {
-                    file: o_file,
+                Self::DetachedFiles { files, sysroot, rustc_cfg, toolchain, target_layout },
+                Self::DetachedFiles {
+                    files: o_files,
                     sysroot: o_sysroot,
                     rustc_cfg: o_rustc_cfg,
-                    cargo_script: o_cargo_script,
                     toolchain: o_toolchain,
                     target_layout: o_target_layout,
-                    cfg_overrides: o_cfg_overrides,
                 },
             ) => {
-                file == o_file
+                files == o_files
                     && sysroot == o_sysroot
                     && rustc_cfg == o_rustc_cfg
                     && toolchain == o_toolchain
                     && target_layout == o_target_layout
-                    && cfg_overrides == o_cfg_overrides
-                    && cargo_script == o_cargo_script
             }
             _ => false,
         }
@@ -997,11 +865,10 @@ impl ProjectWorkspace {
 
 fn project_json_to_crate_graph(
     rustc_cfg: Vec<CfgFlag>,
-    load: FileLoader<'_>,
+    load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
     project: &ProjectJson,
     sysroot: Option<&Sysroot>,
     extra_env: &FxHashMap<String, String>,
-    override_cfg: &CfgOverrides,
 ) -> (CrateGraph, ProcMacroPaths) {
     let mut res = (CrateGraph::default(), ProcMacroPaths::default());
     let (crate_graph, proc_macros) = &mut res;
@@ -1041,22 +908,19 @@ fn project_json_to_crate_graph(
                     None => &rustc_cfg,
                 };
 
-                let mut cfg_options = target_cfgs
-                    .iter()
-                    .chain(cfg.iter())
-                    .chain(iter::once(&r_a_cfg_flag))
-                    .cloned()
-                    .collect();
-                override_cfg.apply(
-                    &mut cfg_options,
-                    display_name.as_ref().map(|it| it.canonical_name()).unwrap_or_default(),
-                );
                 let crate_graph_crate_id = crate_graph.add_crate_root(
                     file_id,
                     *edition,
                     display_name.clone(),
                     version.clone(),
-                    Arc::new(cfg_options),
+                    Arc::new(
+                        target_cfgs
+                            .iter()
+                            .chain(cfg.iter())
+                            .chain(iter::once(&r_a_cfg_flag))
+                            .cloned()
+                            .collect(),
+                    ),
                     None,
                     env,
                     *is_proc_macro,
@@ -1103,7 +967,7 @@ fn project_json_to_crate_graph(
 }
 
 fn cargo_to_crate_graph(
-    load: FileLoader<'_>,
+    load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
     rustc: Option<&(CargoWorkspace, WorkspaceBuildScripts)>,
     cargo: &CargoWorkspace,
     sysroot: Option<&Sysroot>,
@@ -1120,7 +984,7 @@ fn cargo_to_crate_graph(
         None => (SysrootPublicDeps::default(), None),
     };
 
-    let cfg_options = CfgOptions::from_iter(rustc_cfg);
+    let cfg_options = create_cfg_options(rustc_cfg);
 
     // Mapping of a package to its library target
     let mut pkg_to_lib_crate = FxHashMap::default();
@@ -1135,13 +999,25 @@ fn cargo_to_crate_graph(
         let cfg_options = {
             let mut cfg_options = cfg_options.clone();
 
+            // Add test cfg for local crates
             if cargo[pkg].is_local {
-                // Add test cfg for local crates
                 cfg_options.insert_atom("test".into());
                 cfg_options.insert_atom("rust_analyzer".into());
             }
 
-            override_cfg.apply(&mut cfg_options, &cargo[pkg].name);
+            if !override_cfg.global.is_empty() {
+                cfg_options.apply_diff(override_cfg.global.clone());
+            };
+            if let Some(diff) = override_cfg.selective.get(&cargo[pkg].name) {
+                // FIXME: this is sort of a hack to deal with #![cfg(not(test))] vanishing such as seen
+                // in ed25519_dalek (#7243), and libcore (#9203) (although you only hit that one while
+                // working on rust-lang/rust as that's the only time it appears outside sysroot).
+                //
+                // A more ideal solution might be to reanalyze crates based on where the cursor is and
+                // figure out the set of cfgs that would have to apply to make it active.
+
+                cfg_options.apply_diff(diff.clone());
+            };
             cfg_options
         };
 
@@ -1277,7 +1153,6 @@ fn cargo_to_crate_graph(
                 &pkg_crates,
                 &cfg_options,
                 override_cfg,
-                // FIXME: Remove this once rustc switched over to rust-project.json
                 if rustc_workspace.workspace_root() == cargo.workspace_root() {
                     // the rustc workspace does not use the installed toolchain's proc-macro server
                     // so we need to make sure we don't use the pre compiled proc-macros there either
@@ -1291,12 +1166,11 @@ fn cargo_to_crate_graph(
     res
 }
 
-fn detached_file_to_crate_graph(
+fn detached_files_to_crate_graph(
     rustc_cfg: Vec<CfgFlag>,
-    load: FileLoader<'_>,
-    detached_file: &AbsPathBuf,
+    load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
+    detached_files: &[AbsPathBuf],
     sysroot: Option<&Sysroot>,
-    override_cfg: &CfgOverrides,
 ) -> (CrateGraph, ProcMacroPaths) {
     let _p = tracing::span!(tracing::Level::INFO, "detached_files_to_crate_graph").entered();
     let mut crate_graph = CrateGraph::default();
@@ -1305,38 +1179,38 @@ fn detached_file_to_crate_graph(
         None => (SysrootPublicDeps::default(), None),
     };
 
-    let mut cfg_options = CfgOptions::from_iter(rustc_cfg);
-    cfg_options.insert_atom("test".into());
+    let mut cfg_options = create_cfg_options(rustc_cfg);
     cfg_options.insert_atom("rust_analyzer".into());
-    override_cfg.apply(&mut cfg_options, "");
     let cfg_options = Arc::new(cfg_options);
 
-    let file_id = match load(detached_file) {
-        Some(file_id) => file_id,
-        None => {
-            tracing::error!("Failed to load detached file {:?}", detached_file);
-            return (crate_graph, FxHashMap::default());
-        }
-    };
-    let display_name = detached_file
-        .file_stem()
-        .map(|file_stem| CrateDisplayName::from_canonical_name(file_stem.to_owned()));
-    let detached_file_crate = crate_graph.add_crate_root(
-        file_id,
-        Edition::CURRENT,
-        display_name.clone(),
-        None,
-        cfg_options.clone(),
-        None,
-        Env::default(),
-        false,
-        CrateOrigin::Local {
-            repo: None,
-            name: display_name.map(|n| n.canonical_name().to_owned()),
-        },
-    );
+    for detached_file in detached_files {
+        let file_id = match load(detached_file) {
+            Some(file_id) => file_id,
+            None => {
+                tracing::error!("Failed to load detached file {:?}", detached_file);
+                continue;
+            }
+        };
+        let display_name = detached_file
+            .file_stem()
+            .map(|file_stem| CrateDisplayName::from_canonical_name(file_stem.to_owned()));
+        let detached_file_crate = crate_graph.add_crate_root(
+            file_id,
+            Edition::CURRENT,
+            display_name.clone(),
+            None,
+            cfg_options.clone(),
+            None,
+            Env::default(),
+            false,
+            CrateOrigin::Local {
+                repo: None,
+                name: display_name.map(|n| n.canonical_name().to_owned()),
+            },
+        );
 
-    public_deps.add_to_crate_graph(&mut crate_graph, detached_file_crate);
+        public_deps.add_to_crate_graph(&mut crate_graph, detached_file_crate);
+    }
     (crate_graph, FxHashMap::default())
 }
 
@@ -1344,7 +1218,7 @@ fn handle_rustc_crates(
     crate_graph: &mut CrateGraph,
     proc_macros: &mut ProcMacroPaths,
     pkg_to_lib_crate: &mut FxHashMap<Package, CrateId>,
-    load: FileLoader<'_>,
+    load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
     rustc_workspace: &CargoWorkspace,
     cargo: &CargoWorkspace,
     public_deps: &SysrootPublicDeps,
@@ -1376,7 +1250,20 @@ fn handle_rustc_crates(
             }
 
             let mut cfg_options = cfg_options.clone();
-            override_cfg.apply(&mut cfg_options, &rustc_workspace[pkg].name);
+
+            if !override_cfg.global.is_empty() {
+                cfg_options.apply_diff(override_cfg.global.clone());
+            };
+            if let Some(diff) = override_cfg.selective.get(&rustc_workspace[pkg].name) {
+                // FIXME: this is sort of a hack to deal with #![cfg(not(test))] vanishing such as seen
+                // in ed25519_dalek (#7243), and libcore (#9203) (although you only hit that one while
+                // working on rust-lang/rust as that's the only time it appears outside sysroot).
+                //
+                // A more ideal solution might be to reanalyze crates based on where the cursor is and
+                // figure out the set of cfgs that would have to apply to make it active.
+
+                cfg_options.apply_diff(diff.clone());
+            };
 
             for &tgt in rustc_workspace[pkg].targets.iter() {
                 let kind @ TargetKind::Lib { is_proc_macro } = rustc_workspace[tgt].kind else {
@@ -1478,19 +1365,23 @@ fn add_target_crate_root(
     };
 
     let mut env = Env::default();
-    inject_cargo_package_env(&mut env, pkg);
-    inject_cargo_env(&mut env);
-    inject_rustc_tool_env(&mut env, cargo_name, kind);
+    inject_cargo_env(pkg, &mut env);
+    if let Ok(cname) = String::from_str(cargo_name) {
+        // CARGO_CRATE_NAME is the name of the Cargo target with - converted to _, such as the name of the library, binary, example, integration test, or benchmark.
+        env.set("CARGO_CRATE_NAME", cname.replace('-', "_"));
+    }
 
     if let Some(envs) = build_data.map(|it| &it.envs) {
         for (k, v) in envs {
             env.set(k, v.clone());
         }
     }
+
+    let display_name = CrateDisplayName::from_canonical_name(cargo_name.to_owned());
     let crate_id = crate_graph.add_crate_root(
         file_id,
         edition,
-        Some(CrateDisplayName::from_canonical_name(cargo_name.to_owned())),
+        Some(display_name),
         Some(pkg.version.to_string()),
         Arc::new(cfg_options),
         potential_cfg_options.map(Arc::new),
@@ -1529,7 +1420,7 @@ fn sysroot_to_crate_graph(
     crate_graph: &mut CrateGraph,
     sysroot: &Sysroot,
     rustc_cfg: Vec<CfgFlag>,
-    load: FileLoader<'_>,
+    load: &mut dyn FnMut(&AbsPath) -> Option<FileId>,
 ) -> (SysrootPublicDeps, Option<CrateId>) {
     let _p = tracing::span!(tracing::Level::INFO, "sysroot_to_crate_graph").entered();
     match sysroot.mode() {
@@ -1540,17 +1431,7 @@ fn sysroot_to_crate_graph(
                 cargo,
                 None,
                 rustc_cfg,
-                &CfgOverrides {
-                    global: CfgDiff::new(
-                        vec![
-                            CfgAtom::Flag("debug_assertions".into()),
-                            CfgAtom::Flag("miri".into()),
-                        ],
-                        vec![],
-                    )
-                    .unwrap(),
-                    ..Default::default()
-                },
+                &CfgOverrides::default(),
                 &WorkspaceBuildScripts::default(),
             );
 
@@ -1608,18 +1489,13 @@ fn sysroot_to_crate_graph(
             (SysrootPublicDeps { deps: pub_deps }, libproc_macro)
         }
         SysrootMode::Stitched(stitched) => {
-            let cfg_options = Arc::new({
-                let mut cfg_options = CfgOptions::default();
-                cfg_options.extend(rustc_cfg);
-                cfg_options.insert_atom("debug_assertions".into());
-                cfg_options.insert_atom("miri".into());
-                cfg_options
-            });
+            let cfg_options = Arc::new(create_cfg_options(rustc_cfg));
             let sysroot_crates: FxHashMap<SysrootCrate, CrateId> = stitched
                 .crates()
                 .filter_map(|krate| {
                     let file_id = load(&stitched[krate].root)?;
 
+                    let env = Env::default();
                     let display_name =
                         CrateDisplayName::from_canonical_name(stitched[krate].name.clone());
                     let crate_id = crate_graph.add_crate_root(
@@ -1629,7 +1505,7 @@ fn sysroot_to_crate_graph(
                         None,
                         cfg_options.clone(),
                         None,
-                        Env::default(),
+                        env,
                         false,
                         CrateOrigin::Lang(LangCrateOrigin::from(&*stitched[krate].name)),
                     );
@@ -1687,3 +1563,71 @@ fn add_dep_inner(graph: &mut CrateGraph, from: CrateId, dep: Dependency) {
         tracing::error!("{}", err)
     }
 }
+
+/// Recreates the compile-time environment variables that Cargo sets.
+///
+/// Should be synced with
+/// <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates>
+///
+/// FIXME: ask Cargo to provide this data instead of re-deriving.
+fn inject_cargo_env(package: &PackageData, env: &mut Env) {
+    // FIXME: Missing variables:
+    // CARGO_BIN_NAME, CARGO_BIN_EXE_<name>
+
+    let manifest_dir = package.manifest.parent();
+    env.set("CARGO_MANIFEST_DIR", manifest_dir.as_str().to_owned());
+
+    // Not always right, but works for common cases.
+    env.set("CARGO", "cargo".into());
+
+    env.set("CARGO_PKG_VERSION", package.version.to_string());
+    env.set("CARGO_PKG_VERSION_MAJOR", package.version.major.to_string());
+    env.set("CARGO_PKG_VERSION_MINOR", package.version.minor.to_string());
+    env.set("CARGO_PKG_VERSION_PATCH", package.version.patch.to_string());
+    env.set("CARGO_PKG_VERSION_PRE", package.version.pre.to_string());
+
+    env.set("CARGO_PKG_AUTHORS", String::new());
+
+    env.set("CARGO_PKG_NAME", package.name.clone());
+    // FIXME: This isn't really correct (a package can have many crates with different names), but
+    // it's better than leaving the variable unset.
+    env.set("CARGO_CRATE_NAME", CrateName::normalize_dashes(&package.name).to_string());
+    env.set("CARGO_PKG_DESCRIPTION", String::new());
+    env.set("CARGO_PKG_HOMEPAGE", String::new());
+    env.set("CARGO_PKG_REPOSITORY", String::new());
+    env.set("CARGO_PKG_LICENSE", String::new());
+
+    env.set("CARGO_PKG_LICENSE_FILE", String::new());
+}
+
+fn create_cfg_options(rustc_cfg: Vec<CfgFlag>) -> CfgOptions {
+    let mut cfg_options = CfgOptions::default();
+    cfg_options.extend(rustc_cfg);
+    cfg_options.insert_atom("debug_assertions".into());
+    cfg_options
+}
+
+fn cargo_config_env(
+    cargo_toml: &ManifestPath,
+    extra_env: &FxHashMap<String, String>,
+    sysroot: Option<&Sysroot>,
+) -> FxHashMap<String, String> {
+    let mut cargo_config = Sysroot::tool(sysroot, Tool::Cargo);
+    cargo_config.envs(extra_env);
+    cargo_config
+        .current_dir(cargo_toml.parent())
+        .args(["-Z", "unstable-options", "config", "get", "env"])
+        .env("RUSTC_BOOTSTRAP", "1");
+    // if successful we receive `env.key.value = "value" per entry
+    tracing::debug!("Discovering cargo config env by {:?}", cargo_config);
+    utf8_stdout(cargo_config).map(parse_output_cargo_config_env).unwrap_or_default()
+}
+
+fn parse_output_cargo_config_env(stdout: String) -> FxHashMap<String, String> {
+    stdout
+        .lines()
+        .filter_map(|l| l.strip_prefix("env."))
+        .filter_map(|l| l.split_once(".value = "))
+        .map(|(key, value)| (key.to_owned(), value.trim_matches('"').to_owned()))
+        .collect()
+}
diff --git a/crates/rust-analyzer/Cargo.toml b/crates/rust-analyzer/Cargo.toml
index cd3349899e..1cc3343e5f 100644
--- a/crates/rust-analyzer/Cargo.toml
+++ b/crates/rust-analyzer/Cargo.toml
@@ -94,7 +94,6 @@ in-rust-tree = [
     "hir/in-rust-tree",
     "hir-def/in-rust-tree",
     "hir-ty/in-rust-tree",
-    "load-cargo/in-rust-tree",
 ]
 
 [lints]
diff --git a/crates/rust-analyzer/src/cargo_target_spec.rs b/crates/rust-analyzer/src/cargo_target_spec.rs
index 6a5f7b0262..83dd99b36b 100644
--- a/crates/rust-analyzer/src/cargo_target_spec.rs
+++ b/crates/rust-analyzer/src/cargo_target_spec.rs
@@ -33,55 +33,53 @@ impl CargoTargetSpec {
         kind: &RunnableKind,
         cfg: &Option<CfgExpr>,
     ) -> (Vec<String>, Vec<String>) {
-        let extra_test_binary_args = snap.config.runnables().extra_test_binary_args;
-
-        let mut cargo_args = Vec::new();
-        let mut executable_args = Vec::new();
+        let mut args = Vec::new();
+        let mut extra_args = Vec::new();
 
         match kind {
             RunnableKind::Test { test_id, attr } => {
-                cargo_args.push("test".to_owned());
-                executable_args.push(test_id.to_string());
+                args.push("test".to_owned());
+                extra_args.push(test_id.to_string());
                 if let TestId::Path(_) = test_id {
-                    executable_args.push("--exact".to_owned());
+                    extra_args.push("--exact".to_owned());
                 }
-                executable_args.extend(extra_test_binary_args);
+                extra_args.push("--nocapture".to_owned());
                 if attr.ignore {
-                    executable_args.push("--ignored".to_owned());
+                    extra_args.push("--ignored".to_owned());
                 }
             }
             RunnableKind::TestMod { path } => {
-                cargo_args.push("test".to_owned());
-                executable_args.push(path.clone());
-                executable_args.extend(extra_test_binary_args);
+                args.push("test".to_owned());
+                extra_args.push(path.clone());
+                extra_args.push("--nocapture".to_owned());
             }
             RunnableKind::Bench { test_id } => {
-                cargo_args.push("bench".to_owned());
-                executable_args.push(test_id.to_string());
+                args.push("bench".to_owned());
+                extra_args.push(test_id.to_string());
                 if let TestId::Path(_) = test_id {
-                    executable_args.push("--exact".to_owned());
+                    extra_args.push("--exact".to_owned());
                 }
-                executable_args.extend(extra_test_binary_args);
+                extra_args.push("--nocapture".to_owned());
             }
             RunnableKind::DocTest { test_id } => {
-                cargo_args.push("test".to_owned());
-                cargo_args.push("--doc".to_owned());
-                executable_args.push(test_id.to_string());
-                executable_args.extend(extra_test_binary_args);
+                args.push("test".to_owned());
+                args.push("--doc".to_owned());
+                extra_args.push(test_id.to_string());
+                extra_args.push("--nocapture".to_owned());
             }
             RunnableKind::Bin => {
                 let subcommand = match spec {
                     Some(CargoTargetSpec { target_kind: TargetKind::Test, .. }) => "test",
                     _ => "run",
                 };
-                cargo_args.push(subcommand.to_owned());
+                args.push(subcommand.to_owned());
             }
         }
 
         let (allowed_features, target_required_features) = if let Some(mut spec) = spec {
             let allowed_features = mem::take(&mut spec.features);
             let required_features = mem::take(&mut spec.required_features);
-            spec.push_to(&mut cargo_args, kind);
+            spec.push_to(&mut args, kind);
             (allowed_features, required_features)
         } else {
             (Default::default(), Default::default())
@@ -91,10 +89,10 @@ impl CargoTargetSpec {
 
         match &cargo_config.features {
             CargoFeatures::All => {
-                cargo_args.push("--all-features".to_owned());
+                args.push("--all-features".to_owned());
                 for feature in target_required_features {
-                    cargo_args.push("--features".to_owned());
-                    cargo_args.push(feature);
+                    args.push("--features".to_owned());
+                    args.push(feature);
                 }
             }
             CargoFeatures::Selected { features, no_default_features } => {
@@ -110,16 +108,16 @@ impl CargoTargetSpec {
 
                 feats.dedup();
                 for feature in feats {
-                    cargo_args.push("--features".to_owned());
-                    cargo_args.push(feature);
+                    args.push("--features".to_owned());
+                    args.push(feature);
                 }
 
                 if *no_default_features {
-                    cargo_args.push("--no-default-features".to_owned());
+                    args.push("--no-default-features".to_owned());
                 }
             }
         }
-        (cargo_args, executable_args)
+        (args, extra_args)
     }
 
     pub(crate) fn for_file(
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs
index e956791d9d..14a4185654 100644
--- a/crates/rust-analyzer/src/config.rs
+++ b/crates/rust-analyzer/src/config.rs
@@ -124,12 +124,7 @@ config_data! {
         /// avoid checking unnecessary things.
         cargo_buildScripts_useRustcWrapper: bool = true,
         /// List of cfg options to enable with the given values.
-        cargo_cfgs: FxHashMap<String, Option<String>> = {
-            let mut m = FxHashMap::default();
-            m.insert("debug_assertions".to_owned(), None);
-            m.insert("miri".to_owned(), None);
-            m
-        },
+        cargo_cfgs: FxHashMap<String, String> = FxHashMap::default(),
         /// Extra arguments that are passed to every cargo invocation.
         cargo_extraArgs: Vec<String> = vec![],
         /// Extra environment variables that will be set when running cargo, rustc
@@ -171,6 +166,8 @@ config_data! {
         /// Set to `true` to use a subdirectory of the existing target directory or
         /// set to a path relative to the workspace to use that path.
         cargo_targetDir | rust_analyzerTargetDir: Option<TargetDirectory> = None,
+        /// Unsets the implicit `#[cfg(test)]` for the specified crates.
+        cargo_unsetTest: Vec<String>     = vec!["core".to_owned()],
 
         /// Run the check command for diagnostics on save.
         checkOnSave | checkOnSave_enable: bool                         = true,
@@ -395,14 +392,6 @@ config_data! {
         /// Additional arguments to be passed to cargo for runnables such as
         /// tests or binaries. For example, it may be `--release`.
         runnables_extraArgs: Vec<String>   = vec![],
-        /// Additional arguments to be passed through Cargo to launched tests, benchmarks, or
-        /// doc-tests.
-        ///
-        /// Unless the launched target uses a
-        /// [custom test harness](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-harness-field),
-        /// they will end up being interpreted as options to
-        /// [`rustc`’s built-in test harness (“libtest”)](https://doc.rust-lang.org/rustc/tests/index.html#cli-arguments).
-        runnables_extraTestBinaryArgs: Vec<String> = vec!["--show-output".to_owned()],
 
         /// Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private
         /// projects, or "discover" to try to automatically find it if the `rustc-dev` component
@@ -834,8 +823,6 @@ pub struct RunnablesConfig {
     pub override_cargo: Option<String>,
     /// Additional arguments for the `cargo`, e.g. `--release`.
     pub cargo_extra_args: Vec<String>,
-    /// Additional arguments for the binary being run, if it is a test or benchmark.
-    pub extra_test_binary_args: Vec<String>,
 }
 
 /// Configuration for workspace symbol search requests.
@@ -1606,15 +1593,27 @@ impl Config {
                 global: CfgDiff::new(
                     self.cargo_cfgs()
                         .iter()
-                        .map(|(key, val)| match val {
-                            Some(val) => CfgAtom::KeyValue { key: key.into(), value: val.into() },
-                            None => CfgAtom::Flag(key.into()),
+                        .map(|(key, val)| {
+                            if val.is_empty() {
+                                CfgAtom::Flag(key.into())
+                            } else {
+                                CfgAtom::KeyValue { key: key.into(), value: val.into() }
+                            }
                         })
                         .collect(),
                     vec![],
                 )
                 .unwrap(),
-                selective: Default::default(),
+                selective: self
+                    .cargo_unsetTest()
+                    .iter()
+                    .map(|it| {
+                        (
+                            it.clone(),
+                            CfgDiff::new(vec![], vec![CfgAtom::Flag("test".into())]).unwrap(),
+                        )
+                    })
+                    .collect(),
             },
             wrap_rustc_in_build_scripts: *self.cargo_buildScripts_useRustcWrapper(),
             invocation_strategy: match self.cargo_buildScripts_invocationStrategy() {
@@ -1750,7 +1749,6 @@ impl Config {
         RunnablesConfig {
             override_cargo: self.runnables_command().clone(),
             cargo_extra_args: self.runnables_extraArgs().clone(),
-            extra_test_binary_args: self.runnables_extraTestBinaryArgs().clone(),
         }
     }
 
@@ -2680,9 +2678,6 @@ fn field_props(field: &str, ty: &str, doc: &[&str], default: &str) -> serde_json
         "FxHashMap<Box<str>, usize>" => set! {
             "type": "object",
         },
-        "FxHashMap<String, Option<String>>" => set! {
-            "type": "object",
-        },
         "Option<usize>" => set! {
             "type": ["null", "integer"],
             "minimum": 0,
diff --git a/crates/rust-analyzer/src/global_state.rs b/crates/rust-analyzer/src/global_state.rs
index e9bca19af6..ec10bc7ccd 100644
--- a/crates/rust-analyzer/src/global_state.rs
+++ b/crates/rust-analyzer/src/global_state.rs
@@ -125,7 +125,6 @@ pub(crate) struct GlobalState {
     /// to invalidate any salsa caches.
     pub(crate) workspaces: Arc<Vec<ProjectWorkspace>>,
     pub(crate) crate_graph_file_dependencies: FxHashSet<vfs::VfsPath>,
-    pub(crate) detached_files: FxHashSet<vfs::AbsPathBuf>,
 
     // op queues
     pub(crate) fetch_workspaces_queue:
@@ -234,7 +233,6 @@ impl GlobalState {
 
             workspaces: Arc::from(Vec::new()),
             crate_graph_file_dependencies: FxHashSet::default(),
-            detached_files: FxHashSet::default(),
             fetch_workspaces_queue: OpQueue::default(),
             fetch_build_data_queue: OpQueue::default(),
             fetch_proc_macros_queue: OpQueue::default(),
@@ -521,7 +519,7 @@ impl GlobalStateSnapshot {
                 cargo.target_by_root(path).map(|it| (cargo, it))
             }
             ProjectWorkspace::Json { .. } => None,
-            ProjectWorkspace::DetachedFile { .. } => None,
+            ProjectWorkspace::DetachedFiles { .. } => None,
         })
     }
 
diff --git a/crates/rust-analyzer/src/handlers/notification.rs b/crates/rust-analyzer/src/handlers/notification.rs
index 4b8c3d06ce..68dc2cf2e2 100644
--- a/crates/rust-analyzer/src/handlers/notification.rs
+++ b/crates/rust-analyzer/src/handlers/notification.rs
@@ -154,10 +154,6 @@ pub(crate) fn handle_did_save_text_document(
                 state
                     .fetch_workspaces_queue
                     .request_op(format!("workspace vfs file change saved {abs_path}"), false);
-            } else if state.detached_files.contains(abs_path) {
-                state
-                    .fetch_workspaces_queue
-                    .request_op(format!("detached file saved {abs_path}"), false);
             }
         }
 
@@ -307,8 +303,7 @@ fn run_flycheck(state: &mut GlobalState, vfs_path: VfsPath) -> bool {
                         }
                         None
                     }
-                    // FIXME
-                    project_model::ProjectWorkspace::DetachedFile { .. } => return None,
+                    project_model::ProjectWorkspace::DetachedFiles { .. } => return None,
                 };
                 Some((idx, package))
             });
diff --git a/crates/rust-analyzer/src/handlers/request.rs b/crates/rust-analyzer/src/handlers/request.rs
index cf97d7d9d2..9c86704ba3 100644
--- a/crates/rust-analyzer/src/handlers/request.rs
+++ b/crates/rust-analyzer/src/handlers/request.rs
@@ -101,7 +101,7 @@ pub(crate) fn handle_analyzer_status(
             "Workspace root folders: {:?}",
             snap.workspaces
                 .iter()
-                .map(|ws| ws.workspace_definition_path())
+                .flat_map(|ws| ws.workspace_definition_path())
                 .collect::<Vec<&AbsPath>>()
         );
     }
@@ -1761,9 +1761,7 @@ pub(crate) fn handle_open_docs(
     let ws_and_sysroot = snap.workspaces.iter().find_map(|ws| match ws {
         ProjectWorkspace::Cargo { cargo, sysroot, .. } => Some((cargo, sysroot.as_ref().ok())),
         ProjectWorkspace::Json { .. } => None,
-        ProjectWorkspace::DetachedFile { cargo_script, sysroot, .. } => {
-            cargo_script.as_ref().zip(Some(sysroot.as_ref().ok()))
-        }
+        ProjectWorkspace::DetachedFiles { .. } => None,
     });
 
     let (cargo, sysroot) = match ws_and_sysroot {
diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs
index 5d8a66cabc..d2e495dbfc 100644
--- a/crates/rust-analyzer/src/reload.rs
+++ b/crates/rust-analyzer/src/reload.rs
@@ -153,7 +153,7 @@ impl GlobalState {
         for ws in self.workspaces.iter() {
             let (ProjectWorkspace::Cargo { sysroot, .. }
             | ProjectWorkspace::Json { sysroot, .. }
-            | ProjectWorkspace::DetachedFile { sysroot, .. }) = ws;
+            | ProjectWorkspace::DetachedFiles { sysroot, .. }) = ws;
             match sysroot {
                 Err(None) => (),
                 Err(Some(e)) => {
@@ -234,7 +234,6 @@ impl GlobalState {
                                 it.clone(),
                                 cargo_config.target.as_deref(),
                                 &cargo_config.extra_env,
-                                &cargo_config.cfg_overrides,
                             ))
                         }
                     })
@@ -255,7 +254,7 @@ impl GlobalState {
                 }
 
                 if !detached_files.is_empty() {
-                    workspaces.extend(project_model::ProjectWorkspace::load_detached_files(
+                    workspaces.push(project_model::ProjectWorkspace::load_detached_files(
                         detached_files,
                         &cargo_config,
                     ));
@@ -540,6 +539,9 @@ impl GlobalState {
     }
 
     fn recreate_crate_graph(&mut self, cause: String) {
+        // crate graph construction relies on these paths, record them so when one of them gets
+        // deleted or created we trigger a reconstruction of the crate graph
+        let mut crate_graph_file_dependencies = mem::take(&mut self.crate_graph_file_dependencies);
         self.report_progress(
             "Building CrateGraph",
             crate::lsp::utils::Progress::Begin,
@@ -548,25 +550,13 @@ impl GlobalState {
             None,
         );
 
-        // crate graph construction relies on these paths, record them so when one of them gets
-        // deleted or created we trigger a reconstruction of the crate graph
-        self.crate_graph_file_dependencies.clear();
-        self.detached_files = self
-            .workspaces
-            .iter()
-            .filter_map(|ws| match ws {
-                ProjectWorkspace::DetachedFile { file, .. } => Some(file.clone()),
-                _ => None,
-            })
-            .collect();
-
         let (crate_graph, proc_macro_paths, layouts, toolchains) = {
             // Create crate graph from all the workspaces
             let vfs = &mut self.vfs.write().0;
 
             let load = |path: &AbsPath| {
                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
-                self.crate_graph_file_dependencies.insert(vfs_path.clone());
+                crate_graph_file_dependencies.insert(vfs_path.clone());
                 vfs.file_id(&vfs_path)
             };
 
@@ -586,6 +576,7 @@ impl GlobalState {
         change.set_target_data_layouts(layouts);
         change.set_toolchains(toolchains);
         self.analysis_host.apply_change(change);
+        self.crate_graph_file_dependencies = crate_graph_file_dependencies;
         self.report_progress(
             "Building CrateGraph",
             crate::lsp::utils::Progress::End,
@@ -682,8 +673,7 @@ impl GlobalState {
                                 _ => None,
                             }
                         }
-                        // FIXME
-                        ProjectWorkspace::DetachedFile { .. } => None,
+                        ProjectWorkspace::DetachedFiles { .. } => None,
                     })
                     .map(|(id, root, sysroot_root)| {
                         let sender = sender.clone();
@@ -722,9 +712,15 @@ pub fn ws_to_crate_graph(
         let (other, mut crate_proc_macros) = ws.to_crate_graph(&mut load, extra_env);
         let num_layouts = layouts.len();
         let num_toolchains = toolchains.len();
-        let (ProjectWorkspace::Cargo { toolchain, target_layout, .. }
-        | ProjectWorkspace::Json { toolchain, target_layout, .. }
-        | ProjectWorkspace::DetachedFile { toolchain, target_layout, .. }) = ws;
+        let (toolchain, layout) = match ws {
+            ProjectWorkspace::Cargo { toolchain, target_layout, .. }
+            | ProjectWorkspace::Json { toolchain, target_layout, .. } => {
+                (toolchain.clone(), target_layout.clone())
+            }
+            ProjectWorkspace::DetachedFiles { .. } => {
+                (None, Err("detached files have no layout".into()))
+            }
+        };
 
         let mapping = crate_graph.extend(
             other,
@@ -733,7 +729,7 @@ pub fn ws_to_crate_graph(
                 // if the newly created crate graph's layout is equal to the crate of the merged graph, then
                 // we can merge the crates.
                 let id = cg_id.into_raw().into_u32() as usize;
-                layouts[id] == *target_layout && toolchains[id] == *toolchain && cg_data == o_data
+                layouts[id] == layout && toolchains[id] == toolchain && cg_data == o_data
             },
         );
         // Populate the side tables for the newly merged crates
@@ -745,13 +741,13 @@ pub fn ws_to_crate_graph(
                 if layouts.len() <= idx {
                     layouts.resize(idx + 1, e.clone());
                 }
-                layouts[idx].clone_from(target_layout);
+                layouts[idx].clone_from(&layout);
             }
             if idx >= num_toolchains {
                 if toolchains.len() <= idx {
                     toolchains.resize(idx + 1, None);
                 }
-                toolchains[idx].clone_from(toolchain);
+                toolchains[idx].clone_from(&toolchain);
             }
         });
         proc_macro_paths.push(crate_proc_macros);
diff --git a/crates/span/src/map.rs b/crates/span/src/map.rs
index 81fc56c961..6d8c9c30fb 100644
--- a/crates/span/src/map.rs
+++ b/crates/span/src/map.rs
@@ -15,9 +15,6 @@ use crate::{
 #[derive(Debug, PartialEq, Eq, Clone, Hash)]
 pub struct SpanMap<S> {
     spans: Vec<(TextSize, SpanData<S>)>,
-    /// Index of the matched macro arm on successful expansion for declarative macros.
-    // FIXME: Does it make sense to have this here?
-    pub matched_arm: Option<u32>,
 }
 
 impl<S> SpanMap<S>
@@ -26,7 +23,7 @@ where
 {
     /// Creates a new empty [`SpanMap`].
     pub fn empty() -> Self {
-        Self { spans: Vec::new(), matched_arm: None }
+        Self { spans: Vec::new() }
     }
 
     /// Finalizes the [`SpanMap`], shrinking its backing storage and validating that the offsets are
diff --git a/crates/syntax/rust.ungram b/crates/syntax/rust.ungram
index e1765b25fd..8a775dd874 100644
--- a/crates/syntax/rust.ungram
+++ b/crates/syntax/rust.ungram
@@ -391,6 +391,7 @@ FormatArgsExpr =
 FormatArgsArg =
   (Name '=')? Expr
 
+# MacroCallExpr
 MacroExpr =
   MacroCall
 
diff --git a/crates/syntax/src/lib.rs b/crates/syntax/src/lib.rs
index 3a9ebafe87..e7bbf936dc 100644
--- a/crates/syntax/src/lib.rs
+++ b/crates/syntax/src/lib.rs
@@ -65,7 +65,6 @@ pub use rowan::{
     api::Preorder, Direction, GreenNode, NodeOrToken, SyntaxText, TextRange, TextSize,
     TokenAtOffset, WalkEvent,
 };
-pub use rustc_lexer::unescape;
 pub use smol_str::{format_smolstr, SmolStr};
 
 /// `Parse` is the result of the parsing: a syntax tree and a collection of
diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc
index a03ab0031d..af4483a2cc 100644
--- a/docs/user/generated_config.adoc
+++ b/docs/user/generated_config.adoc
@@ -88,18 +88,10 @@ or build-script sources change and are saved.
 Use `RUSTC_WRAPPER=rust-analyzer` when running build scripts to
 avoid checking unnecessary things.
 --
-[[rust-analyzer.cargo.cfgs]]rust-analyzer.cargo.cfgs::
+[[rust-analyzer.cargo.cfgs]]rust-analyzer.cargo.cfgs (default: `{}`)::
 +
 --
-Default:
-----
-{
-  "debug_assertions": null,
-  "miri": null
-}
-----
 List of cfg options to enable with the given values.
-
 --
 [[rust-analyzer.cargo.extraArgs]]rust-analyzer.cargo.extraArgs (default: `[]`)::
 +
@@ -166,6 +158,18 @@ building from locking the `Cargo.lock` at the expense of duplicating build artif
 
 Set to `true` to use a subdirectory of the existing target directory or
 set to a path relative to the workspace to use that path.
+--
+[[rust-analyzer.cargo.unsetTest]]rust-analyzer.cargo.unsetTest::
++
+--
+Default:
+----
+[
+  "core"
+]
+----
+Unsets the implicit `#[cfg(test)]` for the specified crates.
+
 --
 [[rust-analyzer.checkOnSave]]rust-analyzer.checkOnSave (default: `true`)::
 +
@@ -847,24 +851,6 @@ Command to be executed instead of 'cargo' for runnables.
 --
 Additional arguments to be passed to cargo for runnables such as
 tests or binaries. For example, it may be `--release`.
---
-[[rust-analyzer.runnables.extraTestBinaryArgs]]rust-analyzer.runnables.extraTestBinaryArgs::
-+
---
-Default:
-----
-[
-  "--show-output"
-]
-----
-Additional arguments to be passed through Cargo to launched tests, benchmarks, or
-doc-tests.
-
-Unless the launched target uses a
-[custom test harness](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-harness-field),
-they will end up being interpreted as options to
-[`rustc`’s built-in test harness (“libtest”)](https://doc.rust-lang.org/rustc/tests/index.html#cli-arguments).
-
 --
 [[rust-analyzer.rustc.source]]rust-analyzer.rustc.source (default: `null`)::
 +
diff --git a/editors/code/package.json b/editors/code/package.json
index 389e1b8742..c387e72a0c 100644
--- a/editors/code/package.json
+++ b/editors/code/package.json
@@ -610,10 +610,7 @@
                 },
                 "rust-analyzer.cargo.cfgs": {
                     "markdownDescription": "List of cfg options to enable with the given values.",
-                    "default": {
-                        "debug_assertions": null,
-                        "miri": null
-                    },
+                    "default": {},
                     "type": "object"
                 },
                 "rust-analyzer.cargo.extraArgs": {
@@ -699,6 +696,16 @@
                         }
                     ]
                 },
+                "rust-analyzer.cargo.unsetTest": {
+                    "markdownDescription": "Unsets the implicit `#[cfg(test)]` for the specified crates.",
+                    "default": [
+                        "core"
+                    ],
+                    "type": "array",
+                    "items": {
+                        "type": "string"
+                    }
+                },
                 "rust-analyzer.checkOnSave": {
                     "markdownDescription": "Run the check command for diagnostics on save.",
                     "default": true,
@@ -1587,16 +1594,6 @@
                         "type": "string"
                     }
                 },
-                "rust-analyzer.runnables.extraTestBinaryArgs": {
-                    "markdownDescription": "Additional arguments to be passed through Cargo to launched tests, benchmarks, or\ndoc-tests.\n\nUnless the launched target uses a\n[custom test harness](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-harness-field),\nthey will end up being interpreted as options to\n[`rustc`’s built-in test harness (“libtest”)](https://doc.rust-lang.org/rustc/tests/index.html#cli-arguments).",
-                    "default": [
-                        "--show-output"
-                    ],
-                    "type": "array",
-                    "items": {
-                        "type": "string"
-                    }
-                },
                 "rust-analyzer.rustc.source": {
                     "markdownDescription": "Path to the Cargo.toml of the rust compiler workspace, for usage in rustc_private\nprojects, or \"discover\" to try to automatically find it if the `rustc-dev` component\nis installed.\n\nAny project which uses rust-analyzer with the rustcPrivate\ncrates must set `[package.metadata.rust-analyzer] rustc_private=true` to use it.\n\nThis option does not take effect until rust-analyzer is restarted.",
                     "default": null,


Test patch:
diff --git a/crates/hir-def/src/body/tests.rs b/crates/hir-def/src/body/tests.rs
index a27ffe2167..4c8a54f7c8 100644
--- a/crates/hir-def/src/body/tests.rs
+++ b/crates/hir-def/src/body/tests.rs
@@ -318,18 +318,20 @@ fn f() {
 
     expect![[r#"
         fn f() {
-            $crate::panicking::panic_fmt(
-                builtin#lang(Arguments::new_v1_formatted)(
-                    &[
-                        "cc",
-                    ],
-                    &[],
-                    &[],
-                    unsafe {
-                        builtin#lang(UnsafeArg::new)()
-                    },
-                ),
-            );
+            {
+                $crate::panicking::panic_fmt(
+                    builtin#lang(Arguments::new_v1_formatted)(
+                        &[
+                            "cc",
+                        ],
+                        &[],
+                        &[],
+                        unsafe {
+                            builtin#lang(UnsafeArg::new)()
+                        },
+                    ),
+                );
+            };
         }"#]]
     .assert_eq(&body.pretty_print(&db, def))
 }
diff --git a/crates/hir-ty/src/mir/eval/tests.rs b/crates/hir-ty/src/mir/eval/tests.rs
index 381522c9ab..4abbda56cb 100644
--- a/crates/hir-ty/src/mir/eval/tests.rs
+++ b/crates/hir-ty/src/mir/eval/tests.rs
@@ -31,6 +31,7 @@ fn eval_main(db: &TestDB, file_id: FileId) -> Result<(String, String), MirEvalEr
             db.trait_environment(func_id.into()),
         )
         .map_err(|e| MirEvalError::MirLowerError(func_id, e))?;
+
     let (result, output) = interpret_mir(db, body, false, None);
     result?;
     Ok((output.stdout().into_owned(), output.stderr().into_owned()))
@@ -72,6 +73,13 @@ fn check_pass_and_stdio(ra_fixture: &str, expected_stdout: &str, expected_stderr
     }
 }
 
+fn check_panic(ra_fixture: &str, expected_panic: &str) {
+    let (db, file_ids) = TestDB::with_many_files(ra_fixture);
+    let file_id = *file_ids.last().unwrap();
+    let e = eval_main(&db, file_id).unwrap_err();
+    assert_eq!(e.is_panic().unwrap_or_else(|| panic!("unexpected error: {:?}", e)), expected_panic);
+}
+
 #[test]
 fn function_with_extern_c_abi() {
     check_pass(
@@ -87,6 +95,43 @@ fn main() {
     );
 }
 
+#[test]
+fn panic_fmt() {
+    // panic!
+    // -> panic_2021 (builtin macro redirection)
+    //   -> #[lang = "panic_fmt"] core::panicking::panic_fmt (hooked by CTFE for redirection)
+    //   -> core::panicking::const_panic_fmt
+    //     -> #[rustc_const_panic_str] core::panicking::panic_display (hooked by CTFE for builtin panic)
+    //       -> Err(ConstEvalError::Panic)
+    check_panic(
+        r#"
+//- minicore: fmt, panic
+fn main() {
+    panic!("hello, world!");
+}
+    "#,
+        "hello, world!",
+    );
+}
+
+#[test]
+fn panic_display() {
+    // panic!
+    // -> panic_2021 (builtin macro redirection)
+    //   -> #[rustc_const_panic_str] core::panicking::panic_display (hooked by CTFE for builtin panic)
+    //     -> Err(ConstEvalError::Panic)
+    check_panic(
+        r#"
+//- minicore: fmt, panic
+
+fn main() {
+    panic!("{}", "hello, world!");
+}
+    "#,
+        "hello, world!",
+    );
+}
+
 #[test]
 fn drop_basic() {
     check_pass(
diff --git a/crates/ide-assists/src/tests/generated.rs b/crates/ide-assists/src/tests/generated.rs
index 937e78f8d7..d0355bd028 100644
--- a/crates/ide-assists/src/tests/generated.rs
+++ b/crates/ide-assists/src/tests/generated.rs
@@ -390,36 +390,6 @@ fn main() {
     )
 }
 
-#[test]
-fn doctest_convert_from_to_tryfrom() {
-    check_doc_test(
-        "convert_from_to_tryfrom",
-        r#####"
-//- minicore: from
-impl $0From<usize> for Thing {
-    fn from(val: usize) -> Self {
-        Thing {
-            b: val.to_string(),
-            a: val
-        }
-    }
-}
-"#####,
-        r#####"
-impl TryFrom<usize> for Thing {
-    type Error = ${0:()};
-
-    fn try_from(val: usize) -> Result<Self, Self::Error> {
-        Ok(Thing {
-            b: val.to_string(),
-            a: val
-        })
-    }
-}
-"#####,
-    )
-}
-
 #[test]
 fn doctest_convert_if_to_bool_then() {
     check_doc_test(
diff --git a/crates/ide-diagnostics/src/tests.rs b/crates/ide-diagnostics/src/tests.rs
index bb5c2b7913..cd5e95cc1e 100644
--- a/crates/ide-diagnostics/src/tests.rs
+++ b/crates/ide-diagnostics/src/tests.rs
@@ -293,6 +293,7 @@ fn minicore_smoke_test() {
         // This should be ignored since we conditionally remove code which creates single item use with braces
         config.disabled.insert("unused_braces".to_owned());
         config.disabled.insert("unused_variables".to_owned());
+        config.disabled.insert("remove-unnecessary-else".to_owned());
         check_diagnostics_with_config(config, &source);
     }
 
diff --git a/crates/ide/src/hover/tests.rs b/crates/ide/src/hover/tests.rs
index 6bbc8b380d..48a2775ce7 100644
--- a/crates/ide/src/hover/tests.rs
+++ b/crates/ide/src/hover/tests.rs
@@ -1560,21 +1560,21 @@ fn y() {
 fn test_hover_macro_invocation() {
     check(
         r#"
-macro_rules! foo { (a) => {}; () => {} }
+macro_rules! foo { () => {} }
 
 fn f() { fo$0o!(); }
 "#,
         expect![[r#"
-            *foo*
+                *foo*
 
-            ```rust
-            test
-            ```
+                ```rust
+                test
+                ```
 
-            ```rust
-            macro_rules! foo // matched arm #1
-            ```
-        "#]],
+                ```rust
+                macro_rules! foo
+                ```
+            "#]],
     )
 }
 
@@ -1590,22 +1590,22 @@ macro foo() {}
 fn f() { fo$0o!(); }
 "#,
         expect![[r#"
-            *foo*
+                *foo*
 
-            ```rust
-            test
-            ```
+                ```rust
+                test
+                ```
 
-            ```rust
-            macro foo // matched arm #0
-            ```
+                ```rust
+                macro foo
+                ```
 
-            ---
+                ---
 
-            foo bar
+                foo bar
 
-            foo bar baz
-        "#]],
+                foo bar baz
+            "#]],
     )
 }
 
@@ -7864,8 +7864,8 @@ impl Iterator for S {
                                 file_id: FileId(
                                     1,
                                 ),
-                                full_range: 6290..6498,
-                                focus_range: 6355..6361,
+                                full_range: 7791..7999,
+                                focus_range: 7856..7862,
                                 name: "Future",
                                 kind: Trait,
                                 container_name: "future",
@@ -7878,8 +7878,8 @@ impl Iterator for S {
                                 file_id: FileId(
                                     1,
                                 ),
-                                full_range: 7128..7594,
-                                focus_range: 7172..7180,
+                                full_range: 8629..9095,
+                                focus_range: 8673..8681,
                                 name: "Iterator",
                                 kind: Trait,
                                 container_name: "iterator",
diff --git a/crates/ide/src/syntax_highlighting/test_data/highlight_default_library.html b/crates/ide/src/syntax_highlighting/test_data/highlight_default_library.html
index 366895ce7e..893e3c0675 100644
--- a/crates/ide/src/syntax_highlighting/test_data/highlight_default_library.html
+++ b/crates/ide/src/syntax_highlighting/test_data/highlight_default_library.html
@@ -49,5 +49,5 @@ pre                 { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
 
 <span class="keyword">fn</span> <span class="function declaration">main</span><span class="parenthesis">(</span><span class="parenthesis">)</span> <span class="brace">{</span>
     <span class="keyword">let</span> <span class="variable declaration">foo</span> <span class="operator">=</span> <span class="enum_variant default_library library">Some</span><span class="parenthesis">(</span><span class="numeric_literal">92</span><span class="parenthesis">)</span><span class="semicolon">;</span>
-    <span class="keyword">let</span> <span class="variable declaration">nums</span> <span class="operator">=</span> <span class="module default_library library">iter</span><span class="operator">::</span><span class="function default_library library">repeat</span><span class="parenthesis">(</span><span class="variable">foo</span><span class="operator">.</span><span class="method consuming default_library library">unwrap</span><span class="parenthesis">(</span><span class="parenthesis">)</span><span class="parenthesis">)</span><span class="semicolon">;</span>
+    <span class="keyword">let</span> <span class="variable declaration">nums</span> <span class="operator">=</span> <span class="module default_library library">iter</span><span class="operator">::</span><span class="function default_library library">repeat</span><span class="parenthesis">(</span><span class="variable">foo</span><span class="operator">.</span><span class="method default_library library">unwrap</span><span class="parenthesis">(</span><span class="parenthesis">)</span><span class="parenthesis">)</span><span class="semicolon">;</span>
 <span class="brace">}</span></code></pre>
\ No newline at end of file
diff --git a/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html b/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html
index 7a07d17b27..22706dea1f 100644
--- a/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html
+++ b/crates/ide/src/syntax_highlighting/test_data/highlight_strings.html
@@ -158,9 +158,9 @@ pre                 { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
     <span class="macro">println</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"</span><span class="format_specifier">{</span><span class="variable">ничоси</span><span class="format_specifier">}</span><span class="string_literal macro">"</span><span class="comma macro">,</span> <span class="variable declaration macro">ничоси</span> <span class="operator macro">=</span> <span class="numeric_literal macro">92</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
 
     <span class="macro">println</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"</span><span class="format_specifier">{</span><span class="format_specifier">:</span><span class="variable">x</span><span class="format_specifier">?</span><span class="format_specifier">}</span><span class="string_literal macro"> </span><span class="format_specifier">{</span><span class="format_specifier">}</span><span class="string_literal macro"> "</span><span class="comma macro">,</span> <span class="unresolved_reference macro">thingy</span><span class="comma macro">,</span> <span class="unresolved_reference macro">n2</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
-    <span class="macro default_library library">panic</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"</span><span class="format_specifier">{</span><span class="format_specifier">}</span><span class="string_literal macro">"</span><span class="comma macro">,</span> <span class="numeric_literal macro">0</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
+    <span class="macro default_library library">panic</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"{}"</span><span class="comma macro">,</span> <span class="numeric_literal macro">0</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
     <span class="macro default_library library">panic</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"more </span><span class="format_specifier">{</span><span class="format_specifier">}</span><span class="string_literal macro">"</span><span class="comma macro">,</span> <span class="numeric_literal macro">1</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
-    <span class="macro default_library library">assert</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="bool_literal macro">true</span><span class="comma macro">,</span> <span class="string_literal macro">"</span><span class="format_specifier">{</span><span class="format_specifier">}</span><span class="string_literal macro">"</span><span class="comma macro">,</span> <span class="numeric_literal macro">1</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
+    <span class="macro default_library library">assert</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="bool_literal macro">true</span><span class="comma macro">,</span> <span class="string_literal macro">"{}"</span><span class="comma macro">,</span> <span class="numeric_literal macro">1</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
     <span class="macro default_library library">assert</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="bool_literal macro">true</span><span class="comma macro">,</span> <span class="string_literal macro">"</span><span class="format_specifier">{</span><span class="format_specifier">}</span><span class="string_literal macro"> asdasd"</span><span class="comma macro">,</span> <span class="numeric_literal macro">1</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
     <span class="macro">toho</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"{}fmt"</span><span class="comma macro">,</span> <span class="numeric_literal macro">0</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
     <span class="keyword">let</span> <span class="variable declaration">i</span><span class="colon">:</span> <span class="builtin_type">u64</span> <span class="operator">=</span> <span class="numeric_literal">3</span><span class="semicolon">;</span>
diff --git a/crates/proc-macro-srv/proc-macro-test/build.rs b/crates/proc-macro-srv/proc-macro-test/build.rs
index 6a0ae362d8..c76c201d69 100644
--- a/crates/proc-macro-srv/proc-macro-test/build.rs
+++ b/crates/proc-macro-srv/proc-macro-test/build.rs
@@ -53,7 +53,7 @@ fn main() {
     println!("Creating {}", src_dir.display());
     std::fs::create_dir_all(src_dir).unwrap();
 
-    for item_els in [&["Cargo.toml"][..], &["build.rs"][..], &["src", "lib.rs"]] {
+    for item_els in [&["Cargo.toml"][..], &["src", "lib.rs"]] {
         let mut src = imp_dir.clone();
         let mut dst = staging_dir.clone();
         for el in item_els {
diff --git a/crates/proc-macro-srv/proc-macro-test/imp/build.rs b/crates/proc-macro-srv/proc-macro-test/imp/build.rs
deleted file mode 100644
index 07f914fece..0000000000
--- a/crates/proc-macro-srv/proc-macro-test/imp/build.rs
+++ /dev/null
@@ -1,5 +0,0 @@
-//! This teaches cargo about our cfg(rust_analyzer)
-
-fn main() {
-    println!("cargo:rustc-check-cfg=cfg(rust_analyzer)");
-}
diff --git a/crates/project-model/src/tests.rs b/crates/project-model/src/tests.rs
index fd09dff503..fc0b507b33 100644
--- a/crates/project-model/src/tests.rs
+++ b/crates/project-model/src/tests.rs
@@ -75,7 +75,6 @@ fn load_rust_project(file: &str) -> (CrateGraph, ProcMacroPaths) {
         rustc_cfg: Vec::new(),
         toolchain: None,
         target_layout: Err(Arc::from("test has no data layout")),
-        cfg_overrides: Default::default(),
     };
     to_crate_graph(project_workspace)
 }
@@ -98,11 +97,6 @@ fn get_test_json_file<T: DeserializeOwned>(file: &str) -> T {
     }
 }
 
-fn replace_cargo(s: &mut String) {
-    let path = toolchain::Tool::Cargo.path().to_string().escape_debug().collect::<String>();
-    *s = s.replace(&path, "$CARGO$");
-}
-
 fn replace_root(s: &mut String, direction: bool) {
     if direction {
         let root = if cfg!(windows) { r#"C:\\ROOT\"# } else { "/ROOT/" };
@@ -161,9 +155,7 @@ fn to_crate_graph(project_workspace: ProjectWorkspace) -> (CrateGraph, ProcMacro
 
 fn check_crate_graph(crate_graph: CrateGraph, expect: ExpectFile) {
     let mut crate_graph = format!("{crate_graph:#?}");
-
     replace_root(&mut crate_graph, false);
-    replace_cargo(&mut crate_graph);
     replace_fake_sys_root(&mut crate_graph);
     expect.assert_eq(&crate_graph);
 }
diff --git a/crates/project-model/test_data/output/cargo_hello_world_project_model.txt b/crates/project-model/test_data/output/cargo_hello_world_project_model.txt
index c2a2d6ed91..0ad19ca9f7 100644
--- a/crates/project-model/test_data/output/cargo_hello_world_project_model.txt
+++ b/crates/project-model/test_data/output/cargo_hello_world_project_model.txt
@@ -17,6 +17,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
                 "test",
             ],
@@ -24,22 +25,20 @@
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "hello_world",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "hello_world",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -78,6 +77,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
                 "test",
             ],
@@ -85,22 +85,20 @@
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "hello_world",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "hello_world",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -146,6 +144,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
                 "test",
             ],
@@ -153,22 +152,20 @@
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "an_example",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "an_example",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -214,6 +211,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
                 "test",
             ],
@@ -221,22 +219,20 @@
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "it",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "it",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -282,6 +278,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "feature=default",
                 "feature=std",
             ],
@@ -289,6 +286,7 @@
         potential_cfg_options: Some(
             CfgOptions(
                 [
+                    "debug_assertions",
                     "feature=align",
                     "feature=const-extern-fn",
                     "feature=default",
@@ -301,22 +299,20 @@
         ),
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "libc",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$.cargo/registry/src/github.com-1ecc6299db9ec823/libc-0.2.98",
-                "CARGO_PKG_AUTHORS": "The Rust Project Developers",
-                "CARGO_PKG_DESCRIPTION": "Raw FFI bindings to platform libraries like libc.\n",
-                "CARGO_PKG_HOMEPAGE": "https://github.com/rust-lang/libc",
-                "CARGO_PKG_LICENSE": "MIT OR Apache-2.0",
+                "CARGO_PKG_VERSION": "0.2.98",
+                "CARGO_PKG_AUTHORS": "",
+                "CARGO_CRATE_NAME": "libc",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "libc",
-                "CARGO_PKG_README": "README.md",
-                "CARGO_PKG_REPOSITORY": "https://github.com/rust-lang/libc",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.2.98",
-                "CARGO_PKG_VERSION_MAJOR": "0",
-                "CARGO_PKG_VERSION_MINOR": "2",
                 "CARGO_PKG_VERSION_PATCH": "98",
+                "CARGO": "cargo",
+                "CARGO_PKG_REPOSITORY": "",
+                "CARGO_PKG_VERSION_MINOR": "2",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
diff --git a/crates/project-model/test_data/output/cargo_hello_world_project_model_with_selective_overrides.txt b/crates/project-model/test_data/output/cargo_hello_world_project_model_with_selective_overrides.txt
index c2a2d6ed91..0ad19ca9f7 100644
--- a/crates/project-model/test_data/output/cargo_hello_world_project_model_with_selective_overrides.txt
+++ b/crates/project-model/test_data/output/cargo_hello_world_project_model_with_selective_overrides.txt
@@ -17,6 +17,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
                 "test",
             ],
@@ -24,22 +25,20 @@
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "hello_world",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "hello_world",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -78,6 +77,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
                 "test",
             ],
@@ -85,22 +85,20 @@
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "hello_world",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "hello_world",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -146,6 +144,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
                 "test",
             ],
@@ -153,22 +152,20 @@
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "an_example",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "an_example",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -214,6 +211,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
                 "test",
             ],
@@ -221,22 +219,20 @@
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "it",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "it",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -282,6 +278,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "feature=default",
                 "feature=std",
             ],
@@ -289,6 +286,7 @@
         potential_cfg_options: Some(
             CfgOptions(
                 [
+                    "debug_assertions",
                     "feature=align",
                     "feature=const-extern-fn",
                     "feature=default",
@@ -301,22 +299,20 @@
         ),
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "libc",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$.cargo/registry/src/github.com-1ecc6299db9ec823/libc-0.2.98",
-                "CARGO_PKG_AUTHORS": "The Rust Project Developers",
-                "CARGO_PKG_DESCRIPTION": "Raw FFI bindings to platform libraries like libc.\n",
-                "CARGO_PKG_HOMEPAGE": "https://github.com/rust-lang/libc",
-                "CARGO_PKG_LICENSE": "MIT OR Apache-2.0",
+                "CARGO_PKG_VERSION": "0.2.98",
+                "CARGO_PKG_AUTHORS": "",
+                "CARGO_CRATE_NAME": "libc",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "libc",
-                "CARGO_PKG_README": "README.md",
-                "CARGO_PKG_REPOSITORY": "https://github.com/rust-lang/libc",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.2.98",
-                "CARGO_PKG_VERSION_MAJOR": "0",
-                "CARGO_PKG_VERSION_MINOR": "2",
                 "CARGO_PKG_VERSION_PATCH": "98",
+                "CARGO": "cargo",
+                "CARGO_PKG_REPOSITORY": "",
+                "CARGO_PKG_VERSION_MINOR": "2",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
diff --git a/crates/project-model/test_data/output/cargo_hello_world_project_model_with_wildcard_overrides.txt b/crates/project-model/test_data/output/cargo_hello_world_project_model_with_wildcard_overrides.txt
index c291ffcca7..e2334dca87 100644
--- a/crates/project-model/test_data/output/cargo_hello_world_project_model_with_wildcard_overrides.txt
+++ b/crates/project-model/test_data/output/cargo_hello_world_project_model_with_wildcard_overrides.txt
@@ -17,28 +17,27 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
             ],
         ),
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "hello_world",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "hello_world",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -77,28 +76,27 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
             ],
         ),
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "hello_world",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "hello_world",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -144,28 +142,27 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
             ],
         ),
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "an_example",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "an_example",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -211,28 +208,27 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "rust_analyzer",
             ],
         ),
         potential_cfg_options: None,
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "it",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$hello-world",
+                "CARGO_PKG_VERSION": "0.1.0",
                 "CARGO_PKG_AUTHORS": "",
-                "CARGO_PKG_DESCRIPTION": "",
-                "CARGO_PKG_HOMEPAGE": "",
-                "CARGO_PKG_LICENSE": "",
+                "CARGO_CRATE_NAME": "it",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "hello-world",
-                "CARGO_PKG_README": "",
+                "CARGO_PKG_VERSION_PATCH": "0",
+                "CARGO": "cargo",
                 "CARGO_PKG_REPOSITORY": "",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.1.0",
-                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_PKG_VERSION_MINOR": "1",
-                "CARGO_PKG_VERSION_PATCH": "0",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
@@ -278,6 +274,7 @@
         ),
         cfg_options: CfgOptions(
             [
+                "debug_assertions",
                 "feature=default",
                 "feature=std",
             ],
@@ -285,6 +282,7 @@
         potential_cfg_options: Some(
             CfgOptions(
                 [
+                    "debug_assertions",
                     "feature=align",
                     "feature=const-extern-fn",
                     "feature=default",
@@ -297,22 +295,20 @@
         ),
         env: Env {
             entries: {
-                "CARGO": "$CARGO$",
-                "CARGO_CRATE_NAME": "libc",
+                "CARGO_PKG_LICENSE": "",
+                "CARGO_PKG_VERSION_MAJOR": "0",
                 "CARGO_MANIFEST_DIR": "$ROOT$.cargo/registry/src/github.com-1ecc6299db9ec823/libc-0.2.98",
-                "CARGO_PKG_AUTHORS": "The Rust Project Developers",
-                "CARGO_PKG_DESCRIPTION": "Raw FFI bindings to platform libraries like libc.\n",
-                "CARGO_PKG_HOMEPAGE": "https://github.com/rust-lang/libc",
-                "CARGO_PKG_LICENSE": "MIT OR Apache-2.0",
+                "CARGO_PKG_VERSION": "0.2.98",
+                "CARGO_PKG_AUTHORS": "",
+                "CARGO_CRATE_NAME": "libc",
                 "CARGO_PKG_LICENSE_FILE": "",
+                "CARGO_PKG_HOMEPAGE": "",
+                "CARGO_PKG_DESCRIPTION": "",
                 "CARGO_PKG_NAME": "libc",
-                "CARGO_PKG_README": "README.md",
-                "CARGO_PKG_REPOSITORY": "https://github.com/rust-lang/libc",
-                "CARGO_PKG_RUST_VERSION": "",
-                "CARGO_PKG_VERSION": "0.2.98",
-                "CARGO_PKG_VERSION_MAJOR": "0",
-                "CARGO_PKG_VERSION_MINOR": "2",
                 "CARGO_PKG_VERSION_PATCH": "98",
+                "CARGO": "cargo",
+                "CARGO_PKG_REPOSITORY": "",
+                "CARGO_PKG_VERSION_MINOR": "2",
                 "CARGO_PKG_VERSION_PRE": "",
             },
         },
diff --git a/crates/project-model/test_data/output/rust_project_hello_world_project_model.txt b/crates/project-model/test_data/output/rust_project_hello_world_project_model.txt
index 80c9136589..ccaba963de 100644
--- a/crates/project-model/test_data/output/rust_project_hello_world_project_model.txt
+++ b/crates/project-model/test_data/output/rust_project_hello_world_project_model.txt
@@ -16,7 +16,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -54,7 +53,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -84,7 +82,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -114,7 +111,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -144,7 +140,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -189,7 +184,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -219,7 +213,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -306,7 +299,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -336,7 +328,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
@@ -366,7 +357,6 @@
         cfg_options: CfgOptions(
             [
                 "debug_assertions",
-                "miri",
             ],
         ),
         potential_cfg_options: None,
diff --git a/crates/rust-analyzer/src/cli/rustc_tests.rs b/crates/rust-analyzer/src/cli/rustc_tests.rs
index 2f9394d0ee..eeec13a14b 100644
--- a/crates/rust-analyzer/src/cli/rustc_tests.rs
+++ b/crates/rust-analyzer/src/cli/rustc_tests.rs
@@ -75,14 +75,12 @@ impl Tester {
             &cargo_config.extra_env,
         );
 
-        let workspace = ProjectWorkspace::DetachedFile {
-            file: tmp_file,
+        let workspace = ProjectWorkspace::DetachedFiles {
+            files: vec![tmp_file],
             sysroot,
             rustc_cfg: vec![],
             toolchain: None,
             target_layout: data_layout.map(Arc::from).map_err(|it| Arc::from(it.to_string())),
-            cfg_overrides: Default::default(),
-            cargo_script: None,
         };
         let load_cargo_config = LoadCargoConfig {
             load_out_dirs_from_check: false,
diff --git a/crates/rust-analyzer/tests/slow-tests/main.rs b/crates/rust-analyzer/tests/slow-tests/main.rs
index b87f02947b..8c982b4687 100644
--- a/crates/rust-analyzer/tests/slow-tests/main.rs
+++ b/crates/rust-analyzer/tests/slow-tests/main.rs
@@ -117,105 +117,6 @@ fn f() {
     );
 }
 
-#[test]
-fn completes_items_from_standard_library_in_cargo_script() {
-    // this test requires nightly so CI can't run it
-    if skip_slow_tests() || std::env::var("CI").is_ok() {
-        return;
-    }
-
-    let server = Project::with_fixture(
-        r#"
-//- /dependency/Cargo.toml
-[package]
-name = "dependency"
-version = "0.1.0"
-//- /dependency/src/lib.rs
-pub struct SpecialHashMap;
-//- /dependency2/Cargo.toml
-[package]
-name = "dependency2"
-version = "0.1.0"
-//- /dependency2/src/lib.rs
-pub struct SpecialHashMap2;
-//- /src/lib.rs
-#!/usr/bin/env -S cargo +nightly -Zscript
----
-[dependencies]
-dependency = { path = "../dependency" }
----
-use dependency::Spam;
-use dependency2::Spam;
-"#,
-    )
-    .with_config(serde_json::json!({
-        "cargo": { "sysroot": null },
-    }))
-    .server()
-    .wait_until_workspace_is_loaded();
-
-    let res = server.send_request::<Completion>(CompletionParams {
-        text_document_position: TextDocumentPositionParams::new(
-            server.doc_id("src/lib.rs"),
-            Position::new(5, 18),
-        ),
-        context: None,
-        partial_result_params: PartialResultParams::default(),
-        work_done_progress_params: WorkDoneProgressParams::default(),
-    });
-    assert!(res.to_string().contains("SpecialHashMap"), "{}", res.to_string());
-
-    let res = server.send_request::<Completion>(CompletionParams {
-        text_document_position: TextDocumentPositionParams::new(
-            server.doc_id("src/lib.rs"),
-            Position::new(6, 18),
-        ),
-        context: None,
-        partial_result_params: PartialResultParams::default(),
-        work_done_progress_params: WorkDoneProgressParams::default(),
-    });
-    assert!(!res.to_string().contains("SpecialHashMap"));
-
-    server.write_file_and_save(
-        "src/lib.rs",
-        r#"#!/usr/bin/env -S cargo +nightly -Zscript
----
-[dependencies]
-dependency2 = { path = "../dependency2" }
----
-use dependency::Spam;
-use dependency2::Spam;
-"#
-        .to_owned(),
-    );
-
-    let server = server.wait_until_workspace_is_loaded();
-
-    std::thread::sleep(std::time::Duration::from_secs(3));
-
-    let res = server.send_request::<Completion>(CompletionParams {
-        text_document_position: TextDocumentPositionParams::new(
-            server.doc_id("src/lib.rs"),
-            Position::new(5, 18),
-        ),
-        context: None,
-        partial_result_params: PartialResultParams::default(),
-        work_done_progress_params: WorkDoneProgressParams::default(),
-    });
-    assert!(!res.to_string().contains("SpecialHashMap"));
-
-    let res = server.send_request::<Completion>(CompletionParams {
-        text_document_position: TextDocumentPositionParams::new(
-            server.doc_id("src/lib.rs"),
-            Position::new(6, 18),
-        ),
-        context: None,
-        partial_result_params: PartialResultParams::default(),
-        work_done_progress_params: WorkDoneProgressParams::default(),
-    });
-    assert!(res.to_string().contains("SpecialHashMap"));
-}
-
 #[test]
 fn test_runnables_project() {
     if skip_slow_tests() {
@@ -256,7 +157,7 @@ fn main() {}
           {
             "args": {
               "cargoArgs": ["test", "--package", "foo", "--test", "spam"],
-              "executableArgs": ["test_eggs", "--exact", "--show-output"],
+              "executableArgs": ["test_eggs", "--exact", "--nocapture"],
               "cargoExtraArgs": [],
               "overrideCargo": null,
               "workspaceRoot": server.path().join("foo")
@@ -289,7 +190,7 @@ fn main() {}
               "cargoExtraArgs": [],
               "executableArgs": [
                 "",
-                "--show-output"
+                "--nocapture"
               ]
             },
             "kind": "cargo",
diff --git a/crates/rust-analyzer/tests/slow-tests/support.rs b/crates/rust-analyzer/tests/slow-tests/support.rs
index f04962a7a2..c6778bf656 100644
--- a/crates/rust-analyzer/tests/slow-tests/support.rs
+++ b/crates/rust-analyzer/tests/slow-tests/support.rs
@@ -125,7 +125,7 @@ impl Project<'_> {
         }
 
         let mut config = Config::new(
-            tmp_dir_path.clone(),
+            tmp_dir_path,
             lsp_types::ClientCapabilities {
                 workspace: Some(lsp_types::WorkspaceClientCapabilities {
                     did_change_watched_files: Some(
@@ -185,14 +185,10 @@ impl Project<'_> {
             roots,
             None,
         );
-        // TODO: don't hardcode src/lib.rs as detached file
-        let mut c = self.config;
-        let p = tmp_dir_path.join("src/lib.rs").to_string();
-        c["detachedFiles"] = serde_json::json!([p]);
-        config.update(c).expect("invalid config");
+        config.update(self.config).expect("invalid config");
         config.rediscover_workspaces();
 
-        Server::new(tmp_dir.keep(), config)
+        Server::new(tmp_dir, config)
     }
 }
 
@@ -287,7 +283,6 @@ impl Server {
         }
     }
 
-    #[track_caller]
     pub(crate) fn send_request<R>(&self, params: R::Params) -> Value
     where
         R: lsp_types::request::Request,
@@ -299,7 +294,6 @@ impl Server {
         let r = Request::new(id.into(), R::METHOD.to_owned(), params);
         self.send_request_(r)
     }
-    #[track_caller]
     fn send_request_(&self, r: Request) -> Value {
         let id = r.id.clone();
         self.client.sender.send(r.clone().into()).unwrap();
@@ -380,16 +374,6 @@ impl Server {
     pub(crate) fn path(&self) -> &Utf8Path {
         self.dir.path()
     }
-
-    pub(crate) fn write_file_and_save(&self, path: &str, text: String) {
-        fs::write(self.dir.path().join(path), &text).unwrap();
-        self.notification::<lsp_types::notification::DidSaveTextDocument>(
-            lsp_types::DidSaveTextDocumentParams {
-                text_document: self.doc_id(path),
-                text: Some(text),
-            },
-        )
-    }
 }
 
 impl Drop for Server {
diff --git a/crates/test-fixture/src/lib.rs b/crates/test-fixture/src/lib.rs
index 89ed6a6157..fdca069dc8 100644
--- a/crates/test-fixture/src/lib.rs
+++ b/crates/test-fixture/src/lib.rs
@@ -209,7 +209,7 @@ impl ChangeFixture {
                 assert!(default_crate_root.is_none());
                 default_crate_root = Some(file_id);
                 default_cfg.extend(meta.cfg.into_iter());
-                default_env.extend_from_other(&meta.env);
+                default_env.extend(meta.env.iter().map(|(x, y)| (x.to_owned(), y.to_owned())));
             }
 
             source_change.change_file(file_id, Some(text));
diff --git a/crates/test-utils/src/minicore.rs b/crates/test-utils/src/minicore.rs
index f125792d12..0257ed9ab4 100644
--- a/crates/test-utils/src/minicore.rs
+++ b/crates/test-utils/src/minicore.rs
@@ -28,7 +28,7 @@
 //!     env: option
 //!     eq: sized
 //!     error: fmt
-//!     fmt: option, result, transmute, coerce_unsized
+//!     fmt: option, result, transmute, coerce_unsized, copy, clone, derive
 //!     fn:
 //!     from: sized
 //!     future: pin
@@ -913,11 +913,13 @@ pub mod fmt {
     }
 
     mod rt {
+        use super::*;
 
         extern "C" {
             type Opaque;
         }
 
+        #[derive(Copy, Clone)]
         #[lang = "format_argument"]
         pub struct Argument<'a> {
             value: &'a Opaque,
@@ -930,8 +932,8 @@ pub mod fmt {
                 unsafe { Argument { formatter: transmute(f), value: transmute(x) } }
             }
 
-            pub fn new_display<'b, T: Display>(x: &'b T) -> Argument<'_> {
-                Self::new(x, Display::fmt)
+            pub fn new_display<'b, T: crate::fmt::Display>(x: &'b T) -> Argument<'_> {
+                Self::new(x, crate::fmt::Display::fmt)
             }
         }
 
@@ -968,7 +970,9 @@ pub mod fmt {
                 flags: u32,
                 precision: Count,
                 width: Count,
-            ) -> Self;
+            ) -> Self {
+                Placeholder { position, fill, align, flags, precision, width }
+            }
         }
 
         #[lang = "format_unsafe_arg"]
@@ -977,10 +981,13 @@ pub mod fmt {
         }
 
         impl UnsafeArg {
-            pub unsafe fn new() -> Self;
+            pub unsafe fn new() -> Self {
+                UnsafeArg { _private: () }
+            }
         }
     }
 
+    #[derive(Copy, Clone)]
     #[lang = "format_arguments"]
     pub struct Arguments<'a> {
         pieces: &'a [&'static str],
@@ -1005,6 +1012,14 @@ pub mod fmt {
         ) -> Arguments<'a> {
             Arguments { pieces, fmt: Some(fmt), args }
         }
+
+        pub const fn as_str(&self) -> Option<&'static str> {
+            match (self.pieces, self.args) {
+                ([], []) => Some(""),
+                ([s], []) => Some(s),
+                _ => None,
+            }
+        }
     }
 
     // region:derive
@@ -1154,8 +1169,8 @@ pub mod pin {
         pointer: P,
     }
     impl<P> Pin<P> {
-        pub fn new(_pointer: P) -> Pin<P> {
-            loop {}
+        pub fn new(pointer: P) -> Pin<P> {
+            Pin { pointer }
         }
     }
     // region:deref
@@ -1356,18 +1371,48 @@ pub mod iter {
 // region:panic
 mod panic {
     pub macro panic_2021 {
-        () => (
-            $crate::panicking::panic("explicit panic")
-        ),
-        ($($t:tt)+) => (
-            $crate::panicking::panic_fmt($crate::const_format_args!($($t)+))
-        ),
+        () => ({
+            const fn panic_cold_explicit() -> ! {
+                $crate::panicking::panic_explicit()
+            }
+            panic_cold_explicit();
+        }),
+        // Special-case the single-argument case for const_panic.
+        ("{}", $arg:expr $(,)?) => ({
+            #[rustc_const_panic_str] // enforce a &&str argument in const-check and hook this by const-eval
+            #[rustc_do_not_const_check] // hooked by const-eval
+            const fn panic_cold_display<T: $crate::fmt::Display>(arg: &T) -> ! {
+                $crate::panicking::panic_display(arg)
+            }
+            panic_cold_display(&$arg);
+        }),
+        ($($t:tt)+) => ({
+            // Semicolon to prevent temporaries inside the formatting machinery from
+            // being considered alive in the caller after the panic_fmt call.
+            $crate::panicking::panic_fmt($crate::const_format_args!($($t)+));
+        }),
     }
 }
 
 mod panicking {
-    #[lang = "panic_fmt"]
-    pub const fn panic_fmt(_fmt: crate::fmt::Arguments<'_>) -> ! {
+    #[rustc_const_panic_str] // enforce a &&str argument in const-check and hook this by const-eval
+    pub const fn panic_display<T: crate::fmt::Display>(x: &T) -> ! {
+        panic_fmt(crate::format_args!("{}", *x));
+    }
+
+    // This function is used instead of panic_fmt in const eval.
+    #[lang = "const_panic_fmt"]
+    pub const fn const_panic_fmt(fmt: crate::fmt::Arguments<'_>) -> ! {
+        if let Some(msg) = fmt.as_str() {
+            // The panic_display function is hooked by const eval.
+            panic_display(&msg);
+        } else {
+            loop {}
+        }
+    }
+
+    #[lang = "panic_fmt"] // needed for const-evaluated panics
+    pub const fn panic_fmt(fmt: crate::fmt::Arguments<'_>) -> ! {
         loop {}
     }
 
@@ -1378,6 +1423,7 @@ mod panicking {
 }
 // endregion:panic
 
+#[macro_use]
 mod macros {
     // region:panic
     #[macro_export]
@@ -1470,7 +1516,6 @@ mod macros {
     }
     // endregion:unimplemented
 
-
     // region:derive
     pub(crate) mod builtin {
         #[rustc_builtin_macro]