Repository: rust-lang/rust-analyzer
Pull request #17102 (2024-04-18 18:41:13)

chore: add some `tracing` to project loading
I wanted to see what's happening during project loading and if it could be parallelized. I'm thinking maybe, but it's not this PR :)


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/Cargo.lock b/Cargo.lock
index bd3894b4d4..55709f8d45 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -323,27 +323,6 @@ dependencies = [
  "syn",
 ]
 
-[[package]]
-name = "directories"
-version = "5.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a49173b84e034382284f27f1af4dcbbd231ffa358c0fe316541a7337f376a35"
-dependencies = [
- "dirs-sys",
-]
-
-[[package]]
-name = "dirs-sys"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
-dependencies = [
- "libc",
- "option-ext",
- "redox_users",
- "windows-sys 0.48.0",
-]
-
 [[package]]
 name = "dissimilar"
 version = "1.0.7"
@@ -919,16 +898,6 @@ dependencies = [
  "libc",
 ]
 
-[[package]]
-name = "libredox"
-version = "0.1.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d"
-dependencies = [
- "bitflags 2.4.2",
- "libc",
-]
-
 [[package]]
 name = "limit"
 version = "0.0.0"
@@ -1217,12 +1186,6 @@ version = "11.1.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
 
-[[package]]
-name = "option-ext"
-version = "0.2.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
-
 [[package]]
 name = "parking_lot"
 version = "0.12.1"
@@ -1603,17 +1566,6 @@ dependencies = [
  "bitflags 1.3.2",
 ]
 
-[[package]]
-name = "redox_users"
-version = "0.4.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891"
-dependencies = [
- "getrandom",
- "libredox",
- "thiserror",
-]
-
 [[package]]
 name = "rowan"
 version = "0.15.15"
@@ -2303,6 +2255,7 @@ dependencies = [
  "paths",
  "rustc-hash",
  "stdx",
+ "tracing",
 ]
 
 [[package]]
@@ -2547,7 +2500,6 @@ name = "xtask"
 version = "0.1.0"
 dependencies = [
  "anyhow",
- "directories",
  "flate2",
  "itertools",
  "proc-macro2",
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/base-db/src/lib.rs b/crates/base-db/src/lib.rs
index 82aff6e3b8..2b64a07a5a 100644
--- a/crates/base-db/src/lib.rs
+++ b/crates/base-db/src/lib.rs
@@ -51,7 +51,6 @@ pub trait FileLoader {
     /// Text of the file.
     fn file_text(&self, file_id: FileId) -> Arc<str>;
     fn resolve_path(&self, path: AnchoredPath<'_>) -> Option<FileId>;
-    /// Crates whose root's source root is the same as the source root of `file_id`
     fn relevant_crates(&self, file_id: FileId) -> Arc<[CrateId]>;
 }
 
@@ -105,7 +104,6 @@ pub trait SourceDatabaseExt: SourceDatabase {
     #[salsa::input]
     fn source_root(&self, id: SourceRootId) -> Arc<SourceRoot>;
 
-    /// Crates whose root fool is in `id`.
     fn source_root_crates(&self, id: SourceRootId) -> Arc<[CrateId]>;
 }
 
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/flycheck/src/lib.rs b/crates/flycheck/src/lib.rs
index 6d5ca8321e..5dfaaf7742 100644
--- a/crates/flycheck/src/lib.rs
+++ b/crates/flycheck/src/lib.rs
@@ -125,10 +125,8 @@ impl FlycheckHandle {
         config: FlycheckConfig,
         sysroot_root: Option<AbsPathBuf>,
         workspace_root: AbsPathBuf,
-        manifest_path: Option<AbsPathBuf>,
     ) -> FlycheckHandle {
-        let actor =
-            FlycheckActor::new(id, sender, config, sysroot_root, workspace_root, manifest_path);
+        let actor = FlycheckActor::new(id, sender, config, sysroot_root, workspace_root);
         let (sender, receiver) = unbounded::<StateChange>();
         let thread = stdx::thread::Builder::new(stdx::thread::ThreadIntent::Worker)
             .name("Flycheck".to_owned())
@@ -207,7 +205,6 @@ struct FlycheckActor {
     id: usize,
     sender: Box<dyn Fn(Message) + Send>,
     config: FlycheckConfig,
-    manifest_path: Option<AbsPathBuf>,
     /// Either the workspace root of the workspace we are flychecking,
     /// or the project root of the project.
     root: AbsPathBuf,
@@ -236,7 +233,6 @@ impl FlycheckActor {
         config: FlycheckConfig,
         sysroot_root: Option<AbsPathBuf>,
         workspace_root: AbsPathBuf,
-        manifest_path: Option<AbsPathBuf>,
     ) -> FlycheckActor {
         tracing::info!(%id, ?workspace_root, "Spawning flycheck");
         FlycheckActor {
@@ -245,7 +241,6 @@ impl FlycheckActor {
             config,
             sysroot_root,
             root: workspace_root,
-            manifest_path,
             command_handle: None,
             command_receiver: None,
         }
@@ -393,13 +388,8 @@ impl FlycheckActor {
                     "--message-format=json"
                 });
 
-                if let Some(manifest_path) = &self.manifest_path {
-                    cmd.arg("--manifest-path");
-                    cmd.arg(manifest_path);
-                    if manifest_path.extension().map_or(false, |ext| ext == "rs") {
-                        cmd.arg("-Zscript");
-                    }
-                }
+                cmd.arg("--manifest-path");
+                cmd.arg(self.root.join("Cargo.toml"));
 
                 options.apply_on_command(&mut cmd);
                 (cmd, options.extra_args.clone())
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 f58228c45f..340e95dbc2 100644
--- a/crates/hir-def/src/body/lower.rs
+++ b/crates/hir-def/src/body/lower.rs
@@ -1869,45 +1869,42 @@ impl ExprCollector<'_> {
     ) -> ExprId {
         match count {
             Some(FormatCount::Literal(n)) => {
-                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,
-                })
+                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(),
+                }
             }
             Some(FormatCount::Argument(arg)) => {
                 if let Ok(arg_index) = arg.index {
                     let (i, _) = argmap.insert_full((arg_index, ArgumentType::Usize));
 
-                    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)),
+                    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,
+                            })
+                        }
                         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()
                 }
             }
@@ -1928,8 +1925,7 @@ impl ExprCollector<'_> {
     fn make_argument(&mut self, arg: ExprId, ty: ArgumentType) -> ExprId {
         use ArgumentType::*;
         use FormatTrait::*;
-
-        let new_fn = match LangItem::FormatArgument.ty_rel_path(
+        match LangItem::FormatArgument.ty_rel_path(
             self.db,
             self.krate,
             match ty {
@@ -1945,14 +1941,16 @@ impl ExprCollector<'_> {
                 Usize => name![from_usize],
             },
         ) {
-            Some(new_fn) => self.alloc_expr_desugared(Expr::Path(new_fn)),
+            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,
+                })
+            }
             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/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 d99ef6679e..0bf01b0bc6 100644
--- a/crates/hir-ty/src/chalk_ext.rs
+++ b/crates/hir-ty/src/chalk_ext.rs
@@ -27,7 +27,6 @@ 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;
@@ -88,10 +87,6 @@ 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 2de1aa30c9..045ffb418c 100644
--- a/crates/hir-ty/src/mir/eval.rs
+++ b/crates/hir-ty/src/mir/eval.rs
@@ -428,17 +428,6 @@ 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 {
@@ -1149,7 +1138,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.is_str() {
+                    let size = if ty.kind(Interner) == &TyKind::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 3438712049..fee3dd3ada 100644
--- a/crates/hir-ty/src/mir/eval/shim.rs
+++ b/crates/hir-ty/src/mir/eval/shim.rs
@@ -49,7 +49,6 @@ 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"),
@@ -132,7 +131,9 @@ impl Evaluator<'_> {
             return Ok(true);
         }
         if let Some(it) = self.detect_lang_function(def) {
-            let result = self.exec_lang_item(it, generic_args, args, locals, span)?;
+            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)?;
             destination.write_from_bytes(self, &result)?;
             return Ok(true);
         }
@@ -310,20 +311,16 @@ impl Evaluator<'_> {
 
     fn detect_lang_function(&self, def: FunctionId) -> Option<LangItem> {
         use LangItem::*;
-        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)?;
+        let candidate = self.db.lang_attr(def.into())?;
         // 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
     }
 
@@ -331,52 +328,18 @@ impl Evaluator<'_> {
         &mut self,
         it: LangItem,
         generic_args: &Substitution,
-        args: &[IntervalAndTy],
+        args: &[Vec<u8>],
         locals: &Locals,
         span: MirSpan,
     ) -> Result<Vec<u8>> {
         use LangItem::*;
         let mut args = args.iter();
         match it {
-            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)
-                )))
-            }
+            BeginPanic => Err(MirEvalError::Panic("<unknown-panic-payload>".to_owned())),
             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())
             }
@@ -390,7 +353,6 @@ 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/source_to_def.rs b/crates/hir/src/semantics/source_to_def.rs
index 007709a836..434e4b5a0c 100644
--- a/crates/hir/src/semantics/source_to_def.rs
+++ b/crates/hir/src/semantics/source_to_def.rs
@@ -121,7 +121,7 @@ impl SourceToDefCtx<'_, '_> {
         let _p = tracing::span!(tracing::Level::INFO, "SourceBinder::file_to_module_def").entered();
         let mut mods = SmallVec::new();
         for &crate_id in self.db.relevant_crates(file).iter() {
-            // Note: `mod` declarations in block modules cannot be supported here
+            // FIXME: inner items
             let crate_def_map = self.db.crate_def_map(crate_id);
             mods.extend(
                 crate_def_map
@@ -129,9 +129,6 @@ impl SourceToDefCtx<'_, '_> {
                     .map(|local_id| crate_def_map.module_id(local_id)),
             )
         }
-        if mods.is_empty() {
-            // FIXME: detached file
-        }
         mods
     }
 
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-db/src/prime_caches.rs b/crates/ide-db/src/prime_caches.rs
index 0db87c6bc4..024e8f6ae3 100644
--- a/crates/ide-db/src/prime_caches.rs
+++ b/crates/ide-db/src/prime_caches.rs
@@ -1,6 +1,6 @@
 //! rust-analyzer is lazy and doesn't compute anything unless asked. This
 //! sometimes is counter productive when, for example, the first goto definition
-//! request takes longer to compute. This module implements prepopulation of
+//! request takes longer to compute. This modules implemented prepopulation of
 //! various caches, it's not really advanced at the moment.
 mod topologic_sort;
 
diff --git a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs
index b3dde977b1..241fddbb90 100644
--- a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs
+++ b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs
@@ -7,7 +7,7 @@ use ide_db::{
     helpers::mod_path_to_ast,
     imports::insert_use::{insert_use, ImportScope},
     source_change::SourceChangeBuilder,
-    FxHashMap, RootDatabase,
+    RootDatabase,
 };
 use itertools::Itertools;
 use stdx::{format_to, never};
@@ -22,22 +22,15 @@ use crate::{fix, Diagnostic, DiagnosticCode, DiagnosticsConfig, Severity};
 #[derive(Default)]
 struct State {
     result: String,
+    struct_counts: usize,
     has_serialize: bool,
     has_deserialize: bool,
-    names: FxHashMap<String, usize>,
 }
 
 impl State {
-    fn generate_new_name(&mut self, name: &str) -> ast::Name {
-        let name = stdx::to_camel_case(name);
-        let count = if let Some(count) = self.names.get_mut(&name) {
-            *count += 1;
-            *count
-        } else {
-            self.names.insert(name.clone(), 1);
-            1
-        };
-        make::name(&format!("{}{}", name, count))
+    fn generate_new_name(&mut self) -> ast::Name {
+        self.struct_counts += 1;
+        make::name(&format!("Struct{}", self.struct_counts))
     }
 
     fn serde_derive(&self) -> String {
@@ -59,21 +52,15 @@ impl State {
         }
     }
 
-    fn build_struct(
-        &mut self,
-        name: &str,
-        value: &serde_json::Map<String, serde_json::Value>,
-    ) -> ast::Type {
-        let name = self.generate_new_name(name);
+    fn build_struct(&mut self, value: &serde_json::Map<String, serde_json::Value>) -> ast::Type {
+        let name = self.generate_new_name();
         let ty = make::ty(&name.to_string());
         let strukt = make::struct_(
             None,
             name,
             None,
             make::record_field_list(value.iter().sorted_unstable_by_key(|x| x.0).map(
-                |(name, value)| {
-                    make::record_field(None, make::name(name), self.type_of(name, value))
-                },
+                |(name, value)| make::record_field(None, make::name(name), self.type_of(value)),
             ))
             .into(),
         );
@@ -81,7 +68,7 @@ impl State {
         ty
     }
 
-    fn type_of(&mut self, name: &str, value: &serde_json::Value) -> ast::Type {
+    fn type_of(&mut self, value: &serde_json::Value) -> ast::Type {
         match value {
             serde_json::Value::Null => make::ty_unit(),
             serde_json::Value::Bool(_) => make::ty("bool"),
@@ -89,12 +76,12 @@ impl State {
             serde_json::Value::String(_) => make::ty("String"),
             serde_json::Value::Array(it) => {
                 let ty = match it.iter().next() {
-                    Some(x) => self.type_of(name, x),
+                    Some(x) => self.type_of(x),
                     None => make::ty_placeholder(),
                 };
                 make::ty(&format!("Vec<{ty}>"))
             }
-            serde_json::Value::Object(x) => self.build_struct(name, x),
+            serde_json::Value::Object(x) => self.build_struct(x),
         }
     }
 }
@@ -126,7 +113,7 @@ pub(crate) fn json_in_items(
                 let serialize_resolved = scope_resolve("::serde::Serialize");
                 state.has_deserialize = deserialize_resolved.is_some();
                 state.has_serialize = serialize_resolved.is_some();
-                state.build_struct("Root", &it);
+                state.build_struct(&it);
                 edit.insert(range.start(), state.result);
                 acc.push(
                     Diagnostic::new(
@@ -231,7 +218,7 @@ mod tests {
             }
 
             #[derive(Serialize)]
-            struct Root1{ bar: f64, bay: i64, baz: (), r#box: bool, foo: String }
+            struct Struct1{ bar: f64, bay: i64, baz: (), r#box: bool, foo: String }
 
             "#,
         );
@@ -250,44 +237,9 @@ mod tests {
             }
             "#,
             r#"
-            struct Value1{  }
-            struct Bar1{ kind: String, value: Value1 }
-            struct Root1{ bar: Bar1, foo: String }
-
-            "#,
-        );
-    }
-
-    #[test]
-    fn naming() {
-        check_fix(
-            r#"
-            {$0
-                "user": {
-                    "address": {
-                        "street": "Main St",
-                        "house": 3
-                    },
-                    "email": "example@example.com"
-                },
-                "another_user": {
-                    "user": {
-                        "address": {
-                            "street": "Main St",
-                            "house": 3
-                        },
-                        "email": "example@example.com"
-                    }
-                }
-            }
-            "#,
-            r#"
-            struct Address1{ house: i64, street: String }
-            struct User1{ address: Address1, email: String }
-            struct AnotherUser1{ user: User1 }
-            struct Address2{ house: i64, street: String }
-            struct User2{ address: Address2, email: String }
-            struct Root1{ another_user: AnotherUser1, user: User2 }
+            struct Struct3{  }
+            struct Struct2{ kind: String, value: Struct3 }
+            struct Struct1{ bar: Struct2, foo: String }
 
             "#,
         );
@@ -324,9 +276,9 @@ mod tests {
             use serde::Deserialize;
 
             #[derive(Serialize, Deserialize)]
-            struct OfObject1{ x: i64, y: i64 }
+            struct Struct2{ x: i64, y: i64 }
             #[derive(Serialize, Deserialize)]
-            struct Root1{ empty: Vec<_>, nested: Vec<Vec<Vec<i64>>>, of_object: Vec<OfObject1>, of_string: Vec<String> }
+            struct Struct1{ empty: Vec<_>, nested: Vec<Vec<Vec<i64>>>, of_object: Vec<Struct2>, of_string: Vec<String> }
 
             "#,
         );
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 1232322ee3..f795016205 100644
--- a/crates/load-cargo/src/lib.rs
+++ b/crates/load-cargo/src/lib.rs
@@ -17,6 +17,7 @@ use itertools::Itertools;
 use proc_macro_api::{MacroDylib, ProcMacroServer};
 use project_model::{CargoConfig, PackageRoot, ProjectManifest, ProjectWorkspace};
 use span::Span;
+use tracing::{instrument, Level};
 use vfs::{file_set::FileSetConfig, loader::Handle, AbsPath, AbsPathBuf, VfsPath};
 
 pub struct LoadCargoConfig {
@@ -50,6 +51,7 @@ pub fn load_workspace_at(
     load_workspace(workspace, &cargo_config.extra_env, load_config)
 }
 
+#[instrument(skip_all)]
 pub fn load_workspace(
     ws: ProjectWorkspace,
     extra_env: &FxHashMap<String, String>,
@@ -333,7 +335,9 @@ fn load_crate_graph(
     vfs: &mut vfs::Vfs,
     receiver: &Receiver<vfs::loader::Message>,
 ) -> RootDatabase {
-    let ProjectWorkspace { toolchain, target_layout, .. } = ws;
+    let (ProjectWorkspace::Cargo { toolchain, target_layout, .. }
+    | ProjectWorkspace::Json { toolchain, target_layout, .. }
+    | 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);
@@ -350,6 +354,7 @@ fn load_crate_graph(
                 }
             }
             vfs::loader::Message::Loaded { files } | vfs::loader::Message::Changed { files } => {
+                let _p = tracing::span!(Level::INFO, "LoadCargo::load_file_contents").entered();
                 for (path, contents) in files {
                     vfs.set_file_contents(path.into(), contents);
                 }
@@ -405,7 +410,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/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/project-model/src/build_scripts.rs b/crates/project-model/src/build_scripts.rs
index 4dc3b3f349..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,
-    InvocationStrategy, ManifestPath, Package, Sysroot, TargetKind,
+    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.
@@ -63,7 +61,7 @@ impl WorkspaceBuildScripts {
     fn build_command(
         config: &CargoConfig,
         allowed_features: &FxHashSet<String>,
-        manifest_path: &ManifestPath,
+        workspace_root: &AbsPathBuf,
         sysroot: Option<&Sysroot>,
     ) -> io::Result<Command> {
         let mut cmd = match config.run_build_script_command.as_deref() {
@@ -79,7 +77,7 @@ impl WorkspaceBuildScripts {
                 cmd.args(&config.extra_args);
 
                 cmd.arg("--manifest-path");
-                cmd.arg(manifest_path.as_ref());
+                cmd.arg(workspace_root.join("Cargo.toml"));
 
                 if let Some(target_dir) = &config.target_dir {
                     cmd.arg("--target-dir").arg(target_dir);
@@ -116,10 +114,6 @@ impl WorkspaceBuildScripts {
                     }
                 }
 
-                if manifest_path.is_rust_manifest() {
-                    cmd.arg("-Zscript");
-                }
-
                 cmd
             }
         };
@@ -156,12 +150,37 @@ impl WorkspaceBuildScripts {
         .as_ref();
 
         let allowed_features = workspace.workspace_features();
-        let mut cmd =
-            Self::build_command(config, &allowed_features, workspace.manifest_path(), sysroot)?;
-        if toolchain.as_ref().map_or(false, |it| *it >= RUST_1_75) {
-            cmd.args(["--keep-going"]);
+
+        match Self::run_per_ws(
+            Self::build_command(
+                config,
+                &allowed_features,
+                &workspace.workspace_root().to_path_buf(),
+                sysroot,
+            )?,
+            workspace,
+            current_dir,
+            progress,
+        ) {
+            Ok(WorkspaceBuildScripts { error: Some(error), .. })
+                if toolchain.as_ref().map_or(false, |it| *it >= RUST_1_75) =>
+            {
+                // building build scripts failed, attempt to build with --keep-going so
+                // that we potentially get more build data
+                let mut cmd = Self::build_command(
+                    config,
+                    &allowed_features,
+                    &workspace.workspace_root().to_path_buf(),
+                    sysroot,
+                )?;
+
+                cmd.args(["--keep-going"]);
+                let mut res = Self::run_per_ws(cmd, workspace, current_dir, progress)?;
+                res.error = Some(error);
+                Ok(res)
+            }
+            res => res,
         }
-        Self::run_per_ws(cmd, workspace, current_dir, progress)
     }
 
     /// Runs the build scripts by invoking the configured command *once*.
@@ -183,13 +202,7 @@ impl WorkspaceBuildScripts {
                 ))
             }
         };
-        let cmd = Self::build_command(
-            config,
-            &Default::default(),
-            // This is not gonna be used anyways, so just construct a dummy here
-            &ManifestPath::try_from(workspace_root.clone()).unwrap(),
-            None,
-        )?;
+        let cmd = Self::build_command(config, &Default::default(), workspace_root, None)?;
         // NB: Cargo.toml could have been modified between `cargo metadata` and
         // `cargo check`. We shouldn't assume that package ids we see here are
         // exactly those from `config`.
diff --git a/crates/project-model/src/cargo_workspace.rs b/crates/project-model/src/cargo_workspace.rs
index 9955f2687c..82fee7112f 100644
--- a/crates/project-model/src/cargo_workspace.rs
+++ b/crates/project-model/src/cargo_workspace.rs
@@ -32,7 +32,6 @@ pub struct CargoWorkspace {
     targets: Arena<TargetData>,
     workspace_root: AbsPathBuf,
     target_directory: AbsPathBuf,
-    manifest_path: ManifestPath,
 }
 
 impl ops::Index<Package> for CargoWorkspace {
@@ -136,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,
 }
@@ -240,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
@@ -306,12 +287,6 @@ impl CargoWorkspace {
                     .collect(),
             );
         }
-        // The manifest is a rust file, so this means its a script manifest
-        if cargo_toml.is_rust_manifest() {
-            // 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
@@ -335,7 +310,7 @@ impl CargoWorkspace {
         .with_context(|| format!("Failed to run `{:?}`", meta.cargo_command()))
     }
 
-    pub fn new(mut meta: cargo_metadata::Metadata, manifest_path: ManifestPath) -> CargoWorkspace {
+    pub fn new(mut meta: cargo_metadata::Metadata) -> CargoWorkspace {
         let mut pkg_by_id = FxHashMap::default();
         let mut packages = Arena::default();
         let mut targets = Arena::default();
@@ -355,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();
@@ -380,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(),
@@ -408,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);
@@ -449,7 +398,7 @@ impl CargoWorkspace {
 
         let target_directory = AbsPathBuf::assert(meta.target_directory);
 
-        CargoWorkspace { packages, targets, workspace_root, target_directory, manifest_path }
+        CargoWorkspace { packages, targets, workspace_root, target_directory }
     }
 
     pub fn packages(&self) -> impl ExactSizeIterator<Item = Package> + '_ {
@@ -467,10 +416,6 @@ impl CargoWorkspace {
         &self.workspace_root
     }
 
-    pub fn manifest_path(&self) -> &ManifestPath {
-        &self.manifest_path
-    }
-
     pub fn target_directory(&self) -> &AbsPath {
         &self.target_directory
     }
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 5520cdaff6..0000000000
--- a/crates/project-model/src/env.rs
+++ /dev/null
@@ -1,88 +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(
-    manifest: &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(manifest.parent())
-        .args(["-Z", "unstable-options", "config", "get", "env"])
-        .env("RUSTC_BOOTSTRAP", "1");
-    if manifest.is_rust_manifest() {
-        cargo_config.arg("-Zscript");
-    }
-    // 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 181c07f46b..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,19 +47,16 @@ 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, ProjectWorkspaceKind},
+    workspace::{CfgOverrides, PackageRoot, ProjectWorkspace},
 };
-pub use cargo_metadata::Metadata;
 
 #[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
 pub enum ProjectManifest {
     ProjectJson(ManifestPath),
     CargoToml(ManifestPath),
-    CargoScript(ManifestPath),
 }
 
 impl ProjectManifest {
@@ -73,10 +69,7 @@ impl ProjectManifest {
         if path.file_name().unwrap_or_default() == "Cargo.toml" {
             return Ok(ProjectManifest::CargoToml(path));
         }
-        if path.extension().unwrap_or_default() == "rs" {
-            return Ok(ProjectManifest::CargoScript(path));
-        }
-        bail!("project root must point to a Cargo.toml, rust-project.json or <script>.rs file: {path}");
+        bail!("project root must point to Cargo.toml or rust-project.json: {path}");
     }
 
     pub fn discover_single(path: &AbsPath) -> anyhow::Result<ProjectManifest> {
@@ -151,19 +144,15 @@ impl ProjectManifest {
         res.sort();
         res
     }
-
-    pub fn manifest_path(&self) -> &ManifestPath {
-        match self {
-            ProjectManifest::ProjectJson(it)
-            | ProjectManifest::CargoToml(it)
-            | ProjectManifest::CargoScript(it) => it,
-        }
-    }
 }
 
 impl fmt::Display for ProjectManifest {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        fmt::Display::fmt(self.manifest_path(), f)
+        match self {
+            ProjectManifest::ProjectJson(it) | ProjectManifest::CargoToml(it) => {
+                fmt::Display::fmt(&it, f)
+            }
+        }
     }
 }
 
diff --git a/crates/project-model/src/manifest_path.rs b/crates/project-model/src/manifest_path.rs
index 2331c0c36c..d86e81e7e1 100644
--- a/crates/project-model/src/manifest_path.rs
+++ b/crates/project-model/src/manifest_path.rs
@@ -1,5 +1,5 @@
 //! See [`ManifestPath`].
-use std::{borrow::Borrow, fmt, ops};
+use std::{fmt, ops, path::Path};
 
 use paths::{AbsPath, AbsPathBuf};
 
@@ -38,10 +38,6 @@ impl ManifestPath {
     pub fn canonicalize(&self) -> ! {
         (**self).canonicalize()
     }
-
-    pub fn is_rust_manifest(&self) -> bool {
-        self.file.extension().map_or(false, |ext| ext == "rs")
-    }
 }
 
 impl fmt::Display for ManifestPath {
@@ -58,14 +54,8 @@ impl ops::Deref for ManifestPath {
     }
 }
 
-impl AsRef<AbsPath> for ManifestPath {
-    fn as_ref(&self) -> &AbsPath {
+impl AsRef<Path> for ManifestPath {
+    fn as_ref(&self) -> &Path {
         self.file.as_ref()
     }
 }
-
-impl Borrow<AbsPath> for ManifestPath {
-    fn borrow(&self) -> &AbsPath {
-        self.file.borrow()
-    }
-}
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/sysroot.rs b/crates/project-model/src/sysroot.rs
index 00dd18b5b1..1142d6243d 100644
--- a/crates/project-model/src/sysroot.rs
+++ b/crates/project-model/src/sysroot.rs
@@ -349,7 +349,7 @@ impl Sysroot {
                     .filter(|&package| RELEVANT_SYSROOT_CRATES.contains(&&*package.name))
                     .map(|package| package.id.clone())
                     .collect();
-                let cargo_workspace = CargoWorkspace::new(res, sysroot_cargo_toml);
+                let cargo_workspace = CargoWorkspace::new(res);
                 Some(Sysroot {
                     root: sysroot_dir.clone(),
                     src_root: Some(Ok(sysroot_src_dir.clone())),
@@ -368,7 +368,7 @@ impl Sysroot {
                 .into_iter()
                 .map(|it| sysroot_src_dir.join(it))
                 .filter_map(|it| ManifestPath::try_from(it).ok())
-                .find(|it| fs::metadata(it.as_ref()).is_ok());
+                .find(|it| fs::metadata(it).is_ok());
 
             if let Some(root) = root {
                 stitched.crates.alloc(SysrootCrateData {
@@ -468,7 +468,7 @@ fn get_rustc_src(sysroot_path: &AbsPath) -> Option<ManifestPath> {
     let rustc_src = sysroot_path.join("lib/rustlib/rustc-src/rust/compiler/rustc/Cargo.toml");
     let rustc_src = ManifestPath::try_from(rustc_src).ok()?;
     tracing::debug!("checking for rustc source code: {rustc_src}");
-    if fs::metadata(rustc_src.as_ref()).is_ok() {
+    if fs::metadata(&rustc_src).is_ok() {
         Some(rustc_src)
     } else {
         None
diff --git a/crates/project-model/src/workspace.rs b/crates/project-model/src/workspace.rs
index 7f845f85ae..5fa5383cf9 100644
--- a/crates/project-model/src/workspace.rs
+++ b/crates/project-model/src/workspace.rs
@@ -2,9 +2,9 @@
 //! 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::Context;
+use anyhow::{format_err, Context};
 use base_db::{
     CrateDisplayName, CrateGraph, CrateId, CrateName, CrateOrigin, Dependency, Env, FileId,
     LangCrateOrigin, ProcMacroPaths, TargetLayoutLoadResult,
@@ -14,14 +14,15 @@ use paths::{AbsPath, AbsPathBuf};
 use rustc_hash::{FxHashMap, FxHashSet};
 use semver::Version;
 use span::Edition;
+use stdx::always;
 use toolchain::Tool;
+use tracing::instrument;
 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},
@@ -30,7 +31,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
@@ -44,39 +58,34 @@ pub struct PackageRoot {
 }
 
 #[derive(Clone)]
-pub struct ProjectWorkspace {
-    pub kind: ProjectWorkspaceKind,
-    /// The sysroot loaded for this workspace.
-    pub 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.
-    pub rustc_cfg: Vec<CfgFlag>,
-    /// The toolchain version used by this workspace.
-    pub toolchain: Option<Version>,
-    /// The target data layout queried for workspace.
-    pub target_layout: TargetLayoutLoadResult,
-    /// A set of cfg overrides for this workspace.
-    pub cfg_overrides: CfgOverrides,
-}
-
-#[derive(Clone)]
-pub enum ProjectWorkspaceKind {
+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 rustc workspace loaded for this workspace. An `Err(None)` means loading has been
-        /// disabled or was otherwise not requested.
+        sysroot: Result<Sysroot, Option<String>>,
         rustc: Result<Box<(CargoWorkspace, WorkspaceBuildScripts)>, Option<String>>,
-        /// Environment variables set in the `.cargo/config` file.
+        /// 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>,
+        cfg_overrides: CfgOverrides,
+        toolchain: Option<Version>,
+        target_layout: TargetLayoutLoadResult,
         cargo_config_extra_env: FxHashMap<String, String>,
     },
     /// Project workspace was manually specified using a `rust-project.json` file.
-    Json(ProjectJson),
+    Json {
+        project: ProjectJson,
+        sysroot: Result<Sysroot, Option<String>>,
+        /// Holds cfg flags for the current target. We get those by running
+        /// `rustc --print cfg`.
+        rustc_cfg: Vec<CfgFlag>,
+        toolchain: Option<Version>,
+        target_layout: TargetLayoutLoadResult,
+    },
     // 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.
     // Ideally, you should be able to just open a random detached file in existing cargo projects, and get the basic features working.
@@ -87,25 +96,30 @@ pub enum ProjectWorkspaceKind {
     // //
     /// 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: ManifestPath,
-        /// Is this file a cargo script file?
-        cargo: Option<(CargoWorkspace, WorkspaceBuildScripts)>,
-        /// Environment variables set in the `.cargo/config` file.
-        cargo_config_extra_env: FxHashMap<String, String>,
+    DetachedFiles {
+        files: Vec<AbsPathBuf>,
+        sysroot: Result<Sysroot, Option<String>>,
+        /// Holds cfg flags for the current target. We get those by running
+        /// `rustc --print cfg`.
+        rustc_cfg: Vec<CfgFlag>,
+        toolchain: Option<Version>,
+        target_layout: TargetLayoutLoadResult,
     },
 }
 
 impl fmt::Debug for ProjectWorkspace {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         // Make sure this isn't too verbose.
-        let Self { kind, sysroot, rustc_cfg, toolchain, target_layout, cfg_overrides } = self;
-        match kind {
-            ProjectWorkspaceKind::Cargo {
+        match self {
+            ProjectWorkspace::Cargo {
                 cargo,
                 build_scripts: _,
+                sysroot,
                 rustc,
+                rustc_cfg,
+                cfg_overrides,
+                toolchain,
+                target_layout,
                 cargo_config_extra_env,
             } => f
                 .debug_struct("Cargo")
@@ -122,7 +136,13 @@ impl fmt::Debug for ProjectWorkspace {
                 .field("data_layout", &target_layout)
                 .field("cargo_config_extra_env", &cargo_config_extra_env)
                 .finish(),
-            ProjectWorkspaceKind::Json(project) => {
+            ProjectWorkspace::Json {
+                project,
+                sysroot,
+                rustc_cfg,
+                toolchain,
+                target_layout: data_layout,
+            } => {
                 let mut debug_struct = f.debug_struct("Json");
                 debug_struct.field("n_crates", &project.n_crates());
                 if let Ok(sysroot) = sysroot {
@@ -131,25 +151,22 @@ impl fmt::Debug for ProjectWorkspace {
                 debug_struct
                     .field("n_rustc_cfg", &rustc_cfg.len())
                     .field("toolchain", &toolchain)
-                    .field("data_layout", &target_layout)
-                    .field("n_cfg_overrides", &cfg_overrides.len());
+                    .field("data_layout", &data_layout);
                 debug_struct.finish()
             }
-            ProjectWorkspaceKind::DetachedFile {
-                file,
-                cargo: cargo_script,
-                cargo_config_extra_env,
+            ProjectWorkspace::DetachedFiles {
+                files,
+                sysroot,
+                rustc_cfg,
+                toolchain,
+                target_layout,
             } => 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())
-                .field("cargo_config_extra_env", &cargo_config_extra_env)
                 .finish(),
         }
     }
@@ -193,7 +210,7 @@ impl ProjectWorkspace {
     ) -> anyhow::Result<ProjectWorkspace> {
         let res = match manifest {
             ProjectManifest::ProjectJson(project_json) => {
-                let file = fs::read_to_string(project_json.as_ref())
+                let file = fs::read_to_string(project_json)
                     .with_context(|| format!("Failed to read json file {project_json}"))?;
                 let data = serde_json::from_str(&file)
                     .with_context(|| format!("Failed to deserialize json file {project_json}"))?;
@@ -203,12 +220,8 @@ impl ProjectWorkspace {
                     project_json,
                     config.target.as_deref(),
                     &config.extra_env,
-                    &config.cfg_overrides,
                 )
             }
-            ProjectManifest::CargoScript(rust_file) => {
-                ProjectWorkspace::load_detached_file(rust_file, config)?
-            }
             ProjectManifest::CargoToml(cargo_toml) => {
                 let sysroot = match (&config.sysroot, &config.sysroot_src) {
                     (Some(RustLibSource::Path(path)), None) => {
@@ -265,7 +278,7 @@ impl ProjectWorkspace {
                         progress,
                     ) {
                         Ok(meta) => {
-                            let workspace = CargoWorkspace::new(meta, cargo_toml.clone());
+                            let workspace = CargoWorkspace::new(meta);
                             let buildscripts = WorkspaceBuildScripts::rustc_crates(
                                 &workspace,
                                 cargo_toml.parent(),
@@ -321,24 +334,22 @@ impl ProjectWorkspace {
                         "Failed to read Cargo metadata from Cargo.toml file {cargo_toml}, {toolchain:?}",
                     )
                 })?;
-                let cargo = CargoWorkspace::new(meta, cargo_toml.clone());
+                let cargo = CargoWorkspace::new(meta);
 
                 let cargo_config_extra_env =
                     cargo_config_env(cargo_toml, &config.extra_env, sysroot_ref);
-                ProjectWorkspace {
-                    kind: ProjectWorkspaceKind::Cargo {
-                        cargo,
-                        build_scripts: WorkspaceBuildScripts::default(),
-                        rustc,
-                        cargo_config_extra_env,
-                    },
+                ProjectWorkspace::Cargo {
+                    cargo,
+                    build_scripts: WorkspaceBuildScripts::default(),
                     sysroot,
+                    rustc,
                     rustc_cfg,
                     cfg_overrides,
                     toolchain,
                     target_layout: data_layout
                         .map(Arc::from)
                         .map_err(|it| Arc::from(it.to_string())),
+                    cargo_config_extra_env,
                 }
             }
         };
@@ -350,7 +361,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)) => {
@@ -391,21 +401,23 @@ impl ProjectWorkspace {
 
         let rustc_cfg = rustc_cfg::get(target, extra_env, cfg_config);
         let data_layout = target_data_layout::get(data_layout_config, target, extra_env);
-        ProjectWorkspace {
-            kind: ProjectWorkspaceKind::Json(project_json),
+        ProjectWorkspace::Json {
+            project: project_json,
             sysroot,
             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_file(
-        detached_file: &ManifestPath,
+    pub fn load_detached_files(
+        detached_files: Vec<AbsPathBuf>,
         config: &CargoConfig,
     ) -> anyhow::Result<ProjectWorkspace> {
-        let dir = detached_file.parent();
+        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)
@@ -439,62 +451,37 @@ impl ProjectWorkspace {
             None,
             &config.extra_env,
         );
-
-        let cargo_script =
-            CargoWorkspace::fetch_metadata(detached_file, dir, config, sysroot_ref, &|_| ())
-                .ok()
-                .map(|ws| {
-                    (
-                        CargoWorkspace::new(ws, detached_file.clone()),
-                        WorkspaceBuildScripts::default(),
-                    )
-                });
-
-        let cargo_config_extra_env =
-            cargo_config_env(detached_file, &config.extra_env, sysroot_ref);
-        Ok(ProjectWorkspace {
-            kind: ProjectWorkspaceKind::DetachedFile {
-                file: detached_file.to_owned(),
-                cargo: cargo_script,
-                cargo_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())),
-            cfg_overrides: config.cfg_overrides.clone(),
         })
     }
 
-    pub fn load_detached_files(
-        detached_files: Vec<ManifestPath>,
-        config: &CargoConfig,
-    ) -> Vec<anyhow::Result<ProjectWorkspace>> {
-        detached_files.into_iter().map(|file| Self::load_detached_file(&file, config)).collect()
-    }
-
     /// Runs the build scripts for this [`ProjectWorkspace`].
     pub fn run_build_scripts(
         &self,
         config: &CargoConfig,
         progress: &dyn Fn(String),
     ) -> anyhow::Result<WorkspaceBuildScripts> {
-        match &self.kind {
-            ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _)), .. }
-            | ProjectWorkspaceKind::Cargo { cargo, .. } => {
+        match self {
+            ProjectWorkspace::Cargo { cargo, toolchain, sysroot, .. } => {
                 WorkspaceBuildScripts::run_for_workspace(
                     config,
                     cargo,
                     progress,
-                    &self.toolchain,
-                    self.sysroot.as_ref().ok(),
+                    toolchain,
+                    sysroot.as_ref().ok(),
                 )
                 .with_context(|| {
                     format!("Failed to run build scripts for {}", cargo.workspace_root())
                 })
             }
-            ProjectWorkspaceKind::DetachedFile { cargo: None, .. }
-            | ProjectWorkspaceKind::Json { .. } => Ok(WorkspaceBuildScripts::default()),
+            ProjectWorkspace::Json { .. } | ProjectWorkspace::DetachedFiles { .. } => {
+                Ok(WorkspaceBuildScripts::default())
+            }
         }
     }
 
@@ -514,8 +501,8 @@ impl ProjectWorkspace {
 
         let cargo_ws: Vec<_> = workspaces
             .iter()
-            .filter_map(|it| match &it.kind {
-                ProjectWorkspaceKind::Cargo { cargo, .. } => Some(cargo),
+            .filter_map(|it| match it {
+                ProjectWorkspace::Cargo { cargo, .. } => Some(cargo),
                 _ => None,
             })
             .collect();
@@ -529,8 +516,8 @@ impl ProjectWorkspace {
 
         workspaces
             .iter()
-            .map(|it| match &it.kind {
-                ProjectWorkspaceKind::Cargo { cargo, .. } => match outputs {
+            .map(|it| match it {
+                ProjectWorkspace::Cargo { cargo, .. } => match outputs {
                     Ok(outputs) => Ok(outputs.next().unwrap()),
                     Err(e) => Err(e.clone()).with_context(|| {
                         format!("Failed to run build scripts for {}", cargo.workspace_root())
@@ -542,33 +529,39 @@ impl ProjectWorkspace {
     }
 
     pub fn set_build_scripts(&mut self, bs: WorkspaceBuildScripts) {
-        match &mut self.kind {
-            ProjectWorkspaceKind::Cargo { build_scripts, .. }
-            | ProjectWorkspaceKind::DetachedFile { cargo: Some((_, build_scripts)), .. } => {
-                *build_scripts = bs
+        match self {
+            ProjectWorkspace::Cargo { build_scripts, .. } => *build_scripts = bs,
+            _ => {
+                always!(bs == WorkspaceBuildScripts::default());
             }
-            _ => assert_eq!(bs, WorkspaceBuildScripts::default()),
         }
     }
 
-    pub fn manifest_or_root(&self) -> &AbsPath {
-        match &self.kind {
-            ProjectWorkspaceKind::Cargo { cargo, .. } => cargo.manifest_path(),
-            ProjectWorkspaceKind::Json(project) => project.path(),
-            ProjectWorkspaceKind::DetachedFile { file, .. } => file,
+    pub fn workspace_definition_path(&self) -> Option<&AbsPath> {
+        match self {
+            ProjectWorkspace::Cargo { cargo, .. } => Some(cargo.workspace_root()),
+            ProjectWorkspace::Json { project, .. } => Some(project.path()),
+            ProjectWorkspace::DetachedFiles { .. } => None,
         }
     }
 
     pub fn find_sysroot_proc_macro_srv(&self) -> anyhow::Result<AbsPathBuf> {
-        match &self.sysroot {
-            Ok(sysroot) => sysroot.discover_proc_macro_srv(),
-            Err(None) => Err(anyhow::format_err!(
-                "cannot find proc-macro server, the workspace `{}` is missing a sysroot",
-                self.manifest_or_root()
+        match self {
+            ProjectWorkspace::Cargo { sysroot: Ok(sysroot), .. }
+            | ProjectWorkspace::Json { sysroot: Ok(sysroot), .. }
+            | ProjectWorkspace::DetachedFiles { sysroot: Ok(sysroot), .. } => {
+                sysroot.discover_proc_macro_srv()
+            }
+            ProjectWorkspace::DetachedFiles { .. } => {
+                Err(anyhow::format_err!("cannot find proc-macro server, no sysroot was found"))
+            }
+            ProjectWorkspace::Cargo { cargo, .. } => Err(anyhow::format_err!(
+                "cannot find proc-macro-srv, the workspace `{}` is missing a sysroot",
+                cargo.workspace_root()
             )),
-            Err(Some(e)) => Err(anyhow::format_err!(
-                "cannot find proc-macro server, the workspace `{}` is missing a sysroot: {e}",
-                self.manifest_or_root()
+            ProjectWorkspace::Json { project, .. } => Err(anyhow::format_err!(
+                "cannot find proc-macro-srv, the workspace `{}` is missing a sysroot",
+                project.path()
             )),
         }
     }
@@ -577,8 +570,8 @@ impl ProjectWorkspace {
     /// The return type contains the path and whether or not
     /// the root is a member of the current workspace
     pub fn to_roots(&self) -> Vec<PackageRoot> {
-        let mk_sysroot = || {
-            self.sysroot.as_ref().into_iter().flat_map(move |sysroot: &Sysroot| {
+        let mk_sysroot = |sysroot: Result<_, _>| {
+            sysroot.into_iter().flat_map(move |sysroot: &Sysroot| {
                 let mut r = match sysroot.mode() {
                     SysrootMode::Workspace(ws) => ws
                         .packages()
@@ -612,8 +605,14 @@ impl ProjectWorkspace {
                 r
             })
         };
-        match &self.kind {
-            ProjectWorkspaceKind::Json(project) => project
+        match self {
+            ProjectWorkspace::Json {
+                project,
+                sysroot,
+                rustc_cfg: _,
+                toolchain: _,
+                target_layout: _,
+            } => project
                 .crates()
                 .map(|(_, krate)| PackageRoot {
                     is_local: krate.is_workspace_member,
@@ -622,12 +621,17 @@ impl ProjectWorkspace {
                 })
                 .collect::<FxHashSet<_>>()
                 .into_iter()
-                .chain(mk_sysroot())
+                .chain(mk_sysroot(sysroot.as_ref()))
                 .collect::<Vec<_>>(),
-            ProjectWorkspaceKind::Cargo {
+            ProjectWorkspace::Cargo {
                 cargo,
+                sysroot,
                 rustc,
+                rustc_cfg: _,
+                cfg_overrides: _,
                 build_scripts,
+                toolchain: _,
+                target_layout: _,
                 cargo_config_extra_env: _,
             } => {
                 cargo
@@ -668,7 +672,7 @@ impl ProjectWorkspace {
                         }
                         PackageRoot { is_local, include, exclude }
                     })
-                    .chain(mk_sysroot())
+                    .chain(mk_sysroot(sysroot.as_ref()))
                     .chain(rustc.iter().map(|a| a.as_ref()).flat_map(|(rustc, _)| {
                         rustc.packages().map(move |krate| PackageRoot {
                             is_local: false,
@@ -678,100 +682,70 @@ impl ProjectWorkspace {
                     }))
                     .collect()
             }
-            ProjectWorkspaceKind::DetachedFile { file, cargo: cargo_script, .. } => {
-                iter::once(PackageRoot {
+            ProjectWorkspace::DetachedFiles { files, sysroot, .. } => files
+                .iter()
+                .map(|detached_file| PackageRoot {
                     is_local: true,
-                    include: vec![file.as_ref().to_owned()],
+                    include: vec![detached_file.clone()],
                     exclude: Vec::new(),
                 })
-                .chain(cargo_script.iter().flat_map(|(cargo, build_scripts)| {
-                    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()];
-                        let out_dir =
-                            build_scripts.get_output(pkg).and_then(|it| it.out_dir.clone());
-                        include.extend(out_dir);
-
-                        // 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())
-                .collect()
-            }
+                .chain(mk_sysroot(sysroot.as_ref()))
+                .collect(),
         }
     }
 
     pub fn n_packages(&self) -> usize {
-        match &self.kind {
-            ProjectWorkspaceKind::Json(project) => {
-                let sysroot_package_len = self.sysroot.as_ref().map_or(0, |it| it.num_packages());
+        match self {
+            ProjectWorkspace::Json { project, sysroot, .. } => {
+                let sysroot_package_len = sysroot.as_ref().map_or(0, |it| it.num_packages());
                 sysroot_package_len + project.n_crates()
             }
-            ProjectWorkspaceKind::Cargo { cargo, rustc, .. } => {
+            ProjectWorkspace::Cargo { cargo, sysroot, rustc, .. } => {
                 let rustc_package_len =
                     rustc.as_ref().map(|a| a.as_ref()).map_or(0, |(it, _)| it.packages().len());
-                let sysroot_package_len = self.sysroot.as_ref().map_or(0, |it| it.num_packages());
+                let sysroot_package_len = sysroot.as_ref().map_or(0, |it| it.num_packages());
                 cargo.packages().len() + sysroot_package_len + rustc_package_len
             }
-            ProjectWorkspaceKind::DetachedFile { cargo: cargo_script, .. } => {
-                let sysroot_package_len = self.sysroot.as_ref().map_or(0, |it| it.num_packages());
-                sysroot_package_len
-                    + cargo_script.as_ref().map_or(1, |(cargo, _)| cargo.packages().len())
+            ProjectWorkspace::DetachedFiles { sysroot, files, .. } => {
+                let sysroot_package_len = sysroot.as_ref().map_or(0, |it| it.num_packages());
+                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();
 
-        let Self { kind, sysroot, cfg_overrides, rustc_cfg, .. } = self;
-        let ((mut crate_graph, proc_macros), sysroot) = match kind {
-            ProjectWorkspaceKind::Json(project) => (
+        let ((mut crate_graph, proc_macros), sysroot) = match self {
+            ProjectWorkspace::Json {
+                project,
+                sysroot,
+                rustc_cfg,
+                toolchain: _,
+                target_layout: _,
+            } => (
                 project_json_to_crate_graph(
                     rustc_cfg.clone(),
                     load,
                     project,
                     sysroot.as_ref().ok(),
                     extra_env,
-                    cfg_overrides,
                 ),
                 sysroot,
             ),
-            ProjectWorkspaceKind::Cargo {
+            ProjectWorkspace::Cargo {
                 cargo,
+                sysroot,
                 rustc,
+                rustc_cfg,
+                cfg_overrides,
                 build_scripts,
+                toolchain: _,
+                target_layout: _,
                 cargo_config_extra_env: _,
             } => (
                 cargo_to_crate_graph(
@@ -785,26 +759,19 @@ impl ProjectWorkspace {
                 ),
                 sysroot,
             ),
-            ProjectWorkspaceKind::DetachedFile { file, cargo: cargo_script, .. } => (
-                if let Some((cargo, build_scripts)) = cargo_script {
-                    cargo_to_crate_graph(
-                        &mut |path| load(path),
-                        None,
-                        cargo,
-                        sysroot.as_ref().ok(),
-                        rustc_cfg.clone(),
-                        cfg_overrides,
-                        build_scripts,
-                    )
-                } else {
-                    detached_file_to_crate_graph(
-                        rustc_cfg.clone(),
-                        load,
-                        file,
-                        sysroot.as_ref().ok(),
-                        cfg_overrides,
-                    )
-                },
+            ProjectWorkspace::DetachedFiles {
+                files,
+                sysroot,
+                rustc_cfg,
+                toolchain: _,
+                target_layout: _,
+            } => (
+                detached_files_to_crate_graph(
+                    rustc_cfg.clone(),
+                    load,
+                    files,
+                    sysroot.as_ref().ok(),
+                ),
                 sysroot,
             ),
         };
@@ -820,60 +787,72 @@ impl ProjectWorkspace {
     }
 
     pub fn eq_ignore_build_data(&self, other: &Self) -> bool {
-        let Self { kind, sysroot, rustc_cfg, toolchain, target_layout, cfg_overrides, .. } = self;
-        let Self {
-            kind: o_kind,
-            sysroot: o_sysroot,
-            rustc_cfg: o_rustc_cfg,
-            toolchain: o_toolchain,
-            target_layout: o_target_layout,
-            cfg_overrides: o_cfg_overrides,
-            ..
-        } = other;
-        (match (kind, o_kind) {
+        match (self, other) {
             (
-                ProjectWorkspaceKind::Cargo {
+                Self::Cargo {
                     cargo,
+                    sysroot,
                     rustc,
+                    rustc_cfg,
+                    cfg_overrides,
+                    toolchain,
                     cargo_config_extra_env,
                     build_scripts: _,
+                    target_layout: _,
                 },
-                ProjectWorkspaceKind::Cargo {
+                Self::Cargo {
                     cargo: o_cargo,
+                    sysroot: o_sysroot,
                     rustc: o_rustc,
+                    rustc_cfg: o_rustc_cfg,
+                    cfg_overrides: o_cfg_overrides,
+                    toolchain: o_toolchain,
                     cargo_config_extra_env: o_cargo_config_extra_env,
                     build_scripts: _,
+                    target_layout: _,
                 },
             ) => {
                 cargo == o_cargo
                     && rustc == o_rustc
+                    && rustc_cfg == o_rustc_cfg
+                    && cfg_overrides == o_cfg_overrides
+                    && toolchain == o_toolchain
+                    && sysroot == o_sysroot
                     && cargo_config_extra_env == o_cargo_config_extra_env
             }
-            (ProjectWorkspaceKind::Json(project), ProjectWorkspaceKind::Json(o_project)) => {
+            (
+                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: _,
+                },
+            ) => {
                 project == o_project
+                    && rustc_cfg == o_rustc_cfg
+                    && sysroot == o_sysroot
+                    && toolchain == o_toolchain
             }
             (
-                ProjectWorkspaceKind::DetachedFile {
-                    file,
-                    cargo: Some((cargo_script, _)),
-                    cargo_config_extra_env,
-                },
-                ProjectWorkspaceKind::DetachedFile {
-                    file: o_file,
-                    cargo: Some((o_cargo_script, _)),
-                    cargo_config_extra_env: o_cargo_config_extra_env,
+                Self::DetachedFiles { files, sysroot, rustc_cfg, toolchain, target_layout },
+                Self::DetachedFiles {
+                    files: o_files,
+                    sysroot: o_sysroot,
+                    rustc_cfg: o_rustc_cfg,
+                    toolchain: o_toolchain,
+                    target_layout: o_target_layout,
                 },
             ) => {
-                file == o_file
-                    && cargo_script == o_cargo_script
-                    && cargo_config_extra_env == o_cargo_config_extra_env
+                files == o_files
+                    && sysroot == o_sysroot
+                    && rustc_cfg == o_rustc_cfg
+                    && toolchain == o_toolchain
+                    && target_layout == o_target_layout
             }
-            _ => return false,
-        }) && sysroot == o_sysroot
-            && rustc_cfg == o_rustc_cfg
-            && toolchain == o_toolchain
-            && target_layout == o_target_layout
-            && cfg_overrides == o_cfg_overrides
+            _ => false,
+        }
     }
 
     /// Returns `true` if the project workspace is [`Json`].
@@ -881,17 +860,17 @@ impl ProjectWorkspace {
     /// [`Json`]: ProjectWorkspace::Json
     #[must_use]
     pub fn is_json(&self) -> bool {
-        matches!(self.kind, ProjectWorkspaceKind::Json { .. })
+        matches!(self, Self::Json { .. })
     }
 }
 
+#[instrument(skip_all)]
 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;
@@ -931,22 +910,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,
@@ -993,7 +969,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>,
@@ -1010,7 +986,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();
@@ -1025,13 +1001,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
         };
 
@@ -1167,7 +1155,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
@@ -1181,52 +1168,51 @@ 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: &ManifestPath,
+    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_file_to_crate_graph").entered();
+    let _p = tracing::span!(tracing::Level::INFO, "detached_files_to_crate_graph").entered();
     let mut crate_graph = CrateGraph::default();
     let (public_deps, _libproc_macro) = match sysroot {
         Some(sysroot) => sysroot_to_crate_graph(&mut crate_graph, sysroot, rustc_cfg.clone(), load),
         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())
 }
 
@@ -1234,7 +1220,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,
@@ -1266,7 +1252,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 {
@@ -1368,19 +1367,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),
@@ -1419,7 +1422,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() {
@@ -1430,17 +1433,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(),
             );
 
@@ -1498,18 +1491,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(
@@ -1519,7 +1507,7 @@ fn sysroot_to_crate_graph(
                         None,
                         cfg_options.clone(),
                         None,
-                        Env::default(),
+                        env,
                         false,
                         CrateOrigin::Lang(LangCrateOrigin::from(&*stitched[krate].name)),
                     );
@@ -1577,3 +1565,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/cli/progress_report.rs b/crates/rust-analyzer/src/cli/progress_report.rs
index 8b143daf2a..6964977840 100644
--- a/crates/rust-analyzer/src/cli/progress_report.rs
+++ b/crates/rust-analyzer/src/cli/progress_report.rs
@@ -96,7 +96,7 @@ impl<'a> ProgressReport<'a> {
     }
 
     fn set_value(&mut self, value: f32) {
-        self.curr = value.clamp(0.0, 1.0);
+        self.curr = f32::max(0.0, f32::min(1.0, value));
     }
 
     fn clear(&mut self) {
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs
index 5842c1d2ec..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,
@@ -356,8 +353,7 @@ config_data! {
         /// of projects.
         ///
         /// Elements must be paths pointing to `Cargo.toml`,
-        /// `rust-project.json`, `.rs` files (which will be treated as standalone files) or JSON
-        /// objects in `rust-project.json` format.
+        /// `rust-project.json`, or JSON objects in `rust-project.json` format.
         linkedProjects: Vec<ManifestOrProjectJson> = vec![],
 
         /// Number of syntax trees rust-analyzer keeps in memory. Defaults to 128.
@@ -396,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
@@ -835,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.
@@ -1302,9 +1288,12 @@ impl Config {
                     self.files_excludeDirs().iter().map(|p| self.root_path.join(p)).collect();
                 self.discovered_projects
                     .iter()
-                    .filter(|project| {
-                        !exclude_dirs.iter().any(|p| project.manifest_path().starts_with(p))
-                    })
+                    .filter(
+                        |(ProjectManifest::ProjectJson(path)
+                         | ProjectManifest::CargoToml(path))| {
+                            !exclude_dirs.iter().any(|p| path.starts_with(p))
+                        },
+                    )
                     .cloned()
                     .map(LinkedProject::from)
                     .collect()
@@ -1604,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() {
@@ -1748,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(),
         }
     }
 
@@ -2678,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 1fcb5d4496..8cfb1ece7d 100644
--- a/crates/rust-analyzer/src/global_state.rs
+++ b/crates/rust-analyzer/src/global_state.rs
@@ -18,11 +18,9 @@ use parking_lot::{
     RwLockWriteGuard,
 };
 use proc_macro_api::ProcMacroServer;
-use project_model::{
-    CargoWorkspace, ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, Target,
-    WorkspaceBuildScripts,
-};
+use project_model::{CargoWorkspace, ProjectWorkspace, Target, WorkspaceBuildScripts};
 use rustc_hash::{FxHashMap, FxHashSet};
+use tracing::{span, Level};
 use triomphe::Arc;
 use vfs::{AnchoredPathBuf, ChangedFile, Vfs};
 
@@ -128,7 +126,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<ManifestPath>,
 
     // op queues
     pub(crate) fetch_workspaces_queue:
@@ -237,7 +234,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(),
@@ -252,8 +248,7 @@ impl GlobalState {
     }
 
     pub(crate) fn process_changes(&mut self) -> bool {
-        let _p = tracing::span!(tracing::Level::INFO, "GlobalState::process_changes").entered();
-
+        let _p = span!(Level::INFO, "GlobalState::process_changes").entered();
         let mut file_changes = FxHashMap::<_, (bool, ChangedFile)>::default();
         let (change, modified_rust_files, workspace_structure_change) = {
             let mut change = ChangeWithProcMacros::new();
@@ -263,6 +258,8 @@ impl GlobalState {
                 return false;
             }
 
+            let _p =
+                span!(Level::INFO, "GlobalState::process_changes/gather_changed_files").entered();
             // downgrade to read lock to allow more readers while we are normalizing text
             let guard = RwLockWriteGuard::downgrade_to_upgradable(guard);
             let vfs: &Vfs = &guard.0;
@@ -301,6 +298,8 @@ impl GlobalState {
                 }
             }
 
+            let _p = span!(Level::INFO, "GlobalState::process_changes/calculate_changed_files")
+                .entered();
             let changed_files: Vec<_> = file_changes
                 .into_iter()
                 .filter(|(_, (just_created, change))| {
@@ -366,6 +365,7 @@ impl GlobalState {
             (change, modified_rust_files, workspace_structure_change)
         };
 
+        let _p = span!(Level::INFO, "GlobalState::process_changes/apply_change").entered();
         self.analysis_host.apply_change(change);
 
         {
@@ -379,6 +379,9 @@ impl GlobalState {
             // but something's going wrong with the source root business when we add a new local
             // crate see https://github.com/rust-lang/rust-analyzer/issues/13029
             if let Some((path, force_crate_graph_reload)) = workspace_structure_change {
+                let _p = span!(Level::INFO, "GlobalState::process_changes/ws_structure_change")
+                    .entered();
+
                 self.fetch_workspaces_queue.request_op(
                     format!("workspace vfs file change: {path}"),
                     force_crate_graph_reload,
@@ -519,13 +522,12 @@ impl GlobalStateSnapshot {
         let file_id = self.analysis.crate_root(crate_id).ok()?;
         let path = self.vfs_read().file_path(file_id).clone();
         let path = path.as_path()?;
-        self.workspaces.iter().find_map(|ws| match &ws.kind {
-            ProjectWorkspaceKind::Cargo { cargo, .. }
-            | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _)), .. } => {
+        self.workspaces.iter().find_map(|ws| match ws {
+            ProjectWorkspace::Cargo { cargo, .. } => {
                 cargo.target_by_root(path).map(|it| (cargo, it))
             }
-            ProjectWorkspaceKind::Json { .. } => None,
-            ProjectWorkspaceKind::DetachedFile { .. } => None,
+            ProjectWorkspace::Json { .. } => None,
+            ProjectWorkspace::DetachedFiles { .. } => None,
         })
     }
 
diff --git a/crates/rust-analyzer/src/handlers/notification.rs b/crates/rust-analyzer/src/handlers/notification.rs
index fee8e97273..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);
             }
         }
 
@@ -289,19 +285,17 @@ fn run_flycheck(state: &mut GlobalState, vfs_path: VfsPath) -> bool {
 
             // Find all workspaces that have at least one target containing the saved file
             let workspace_ids = world.workspaces.iter().enumerate().filter_map(|(idx, ws)| {
-                let package = match &ws.kind {
-                    project_model::ProjectWorkspaceKind::Cargo { cargo, .. }
-                    | project_model::ProjectWorkspaceKind::DetachedFile {
-                        cargo: Some((cargo, _)),
-                        ..
-                    } => cargo.packages().find_map(|pkg| {
-                        let has_target_with_root = cargo[pkg]
-                            .targets
-                            .iter()
-                            .any(|&it| crate_root_paths.contains(&cargo[it].root.as_path()));
-                        has_target_with_root.then(|| cargo[pkg].name.clone())
-                    }),
-                    project_model::ProjectWorkspaceKind::Json(project) => {
+                let package = match ws {
+                    project_model::ProjectWorkspace::Cargo { cargo, .. } => {
+                        cargo.packages().find_map(|pkg| {
+                            let has_target_with_root = cargo[pkg]
+                                .targets
+                                .iter()
+                                .any(|&it| crate_root_paths.contains(&cargo[it].root.as_path()));
+                            has_target_with_root.then(|| cargo[pkg].name.clone())
+                        })
+                    }
+                    project_model::ProjectWorkspace::Json { project, .. } => {
                         if !project.crates().any(|(_, krate)| {
                             crate_root_paths.contains(&krate.root_module.as_path())
                         }) {
@@ -309,7 +303,7 @@ fn run_flycheck(state: &mut GlobalState, vfs_path: VfsPath) -> bool {
                         }
                         None
                     }
-                    project_model::ProjectWorkspaceKind::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 6afcc2c51f..9c86704ba3 100644
--- a/crates/rust-analyzer/src/handlers/request.rs
+++ b/crates/rust-analyzer/src/handlers/request.rs
@@ -27,7 +27,7 @@ use lsp_types::{
     SemanticTokensResult, SymbolInformation, SymbolTag, TextDocumentIdentifier, Url, WorkspaceEdit,
 };
 use paths::Utf8PathBuf;
-use project_model::{ManifestPath, ProjectWorkspaceKind, TargetKind};
+use project_model::{ManifestPath, ProjectWorkspace, TargetKind};
 use serde_json::json;
 use stdx::{format_to, never};
 use syntax::{algo, ast, AstNode, TextRange, TextSize};
@@ -99,7 +99,10 @@ pub(crate) fn handle_analyzer_status(
         format_to!(
             buf,
             "Workspace root folders: {:?}",
-            snap.workspaces.iter().map(|ws| ws.manifest_or_root()).collect::<Vec<&AbsPath>>()
+            snap.workspaces
+                .iter()
+                .flat_map(|ws| ws.workspace_definition_path())
+                .collect::<Vec<&AbsPath>>()
         );
     }
     buf.push_str("\nAnalysis:\n");
@@ -225,7 +228,7 @@ pub(crate) fn handle_run_test(
     };
     let mut handles = vec![];
     for ws in &*state.workspaces {
-        if let ProjectWorkspaceKind::Cargo { cargo, .. } = &ws.kind {
+        if let ProjectWorkspace::Cargo { cargo, .. } = ws {
             let handle = flycheck::CargoTestHandle::new(
                 test_path,
                 state.config.cargo_test_options(),
@@ -766,11 +769,8 @@ pub(crate) fn handle_parent_module(
             let links: Vec<LocationLink> = snap
                 .workspaces
                 .iter()
-                .filter_map(|ws| match &ws.kind {
-                    ProjectWorkspaceKind::Cargo { cargo, .. }
-                    | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _)), .. } => {
-                        cargo.parent_manifests(&manifest_path)
-                    }
+                .filter_map(|ws| match ws {
+                    ProjectWorkspace::Cargo { cargo, .. } => cargo.parent_manifests(&manifest_path),
                     _ => None,
                 })
                 .flatten()
@@ -1758,13 +1758,10 @@ pub(crate) fn handle_open_docs(
     let _p = tracing::span!(tracing::Level::INFO, "handle_open_docs").entered();
     let position = from_proto::file_position(&snap, params)?;
 
-    let ws_and_sysroot = snap.workspaces.iter().find_map(|ws| match &ws.kind {
-        ProjectWorkspaceKind::Cargo { cargo, .. }
-        | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, _)), .. } => {
-            Some((cargo, ws.sysroot.as_ref().ok()))
-        }
-        ProjectWorkspaceKind::Json { .. } => None,
-        ProjectWorkspaceKind::DetachedFile { .. } => None,
+    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::DetachedFiles { .. } => None,
     });
 
     let (cargo, sysroot) = match ws_and_sysroot {
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs
index f37b25fb95..95b3d3ecb3 100644
--- a/crates/rust-analyzer/src/main_loop.rs
+++ b/crates/rust-analyzer/src/main_loop.rs
@@ -12,6 +12,7 @@ use ide_db::base_db::{SourceDatabase, SourceDatabaseExt, VfsPath};
 use lsp_server::{Connection, Notification, Request};
 use lsp_types::{notification::Notification as _, TextDocumentIdentifier};
 use stdx::thread::ThreadIntent;
+use tracing::{span, Level};
 use vfs::FileId;
 
 use crate::{
@@ -229,8 +230,7 @@ impl GlobalState {
     fn handle_event(&mut self, event: Event) -> anyhow::Result<()> {
         let loop_start = Instant::now();
         // NOTE: don't count blocking select! call as a loop-turn time
-        let _p = tracing::span!(tracing::Level::INFO, "GlobalState::handle_event", event = %event)
-            .entered();
+        let _p = tracing::span!(Level::INFO, "GlobalState::handle_event", event = %event).entered();
 
         let event_dbg_msg = format!("{event:?}");
         tracing::debug!(?loop_start, ?event, "handle_event");
@@ -669,9 +669,12 @@ impl GlobalState {
     }
 
     fn handle_vfs_msg(&mut self, message: vfs::loader::Message) {
+        let _p = tracing::span!(Level::INFO, "GlobalState::handle_vfs_msg").entered();
         let is_changed = matches!(message, vfs::loader::Message::Changed { .. });
         match message {
             vfs::loader::Message::Changed { files } | vfs::loader::Message::Loaded { files } => {
+                let _p = tracing::span!(Level::INFO, "GlobalState::handle_vfs_msg{changed/load}")
+                    .entered();
                 let vfs = &mut self.vfs.write().0;
                 for (path, contents) in files {
                     let path = VfsPath::from(path);
@@ -685,6 +688,8 @@ impl GlobalState {
                 }
             }
             vfs::loader::Message::Progress { n_total, n_done, dir, config_version } => {
+                let _p =
+                    tracing::span!(Level::INFO, "GlobalState::handle_vfs_mgs/progress").entered();
                 always!(config_version <= self.vfs_config_version);
 
                 let state = match n_done {
@@ -867,6 +872,8 @@ impl GlobalState {
 
     /// Registers and handles a request. This should only be called once per incoming request.
     fn on_new_request(&mut self, request_received: Instant, req: Request) {
+        let _p =
+            span!(Level::INFO, "GlobalState::on_new_request", req.method = ?req.method).entered();
         self.register_request(&req, request_received);
         self.on_request(req);
     }
@@ -980,6 +987,8 @@ impl GlobalState {
 
     /// Handles an incoming notification.
     fn on_notification(&mut self, not: Notification) -> anyhow::Result<()> {
+        let _p =
+            span!(Level::INFO, "GlobalState::on_notification", not.method = ?not.method).entered();
         use crate::handlers::notification as handlers;
         use lsp_types::notification as notifs;
 
diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs
index f2b6e3ed03..d2e495dbfc 100644
--- a/crates/rust-analyzer/src/reload.rs
+++ b/crates/rust-analyzer/src/reload.rs
@@ -25,7 +25,7 @@ use ide_db::{
 use itertools::Itertools;
 use load_cargo::{load_proc_macro, ProjectFolders};
 use proc_macro_api::ProcMacroServer;
-use project_model::{ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, WorkspaceBuildScripts};
+use project_model::{ProjectWorkspace, WorkspaceBuildScripts};
 use stdx::{format_to, thread::ThreadIntent};
 use triomphe::Arc;
 use vfs::{AbsPath, AbsPathBuf, ChangeKind};
@@ -151,7 +151,9 @@ impl GlobalState {
         }
 
         for ws in self.workspaces.iter() {
-            let sysroot = ws.sysroot.as_ref();
+            let (ProjectWorkspace::Cargo { sysroot, .. }
+            | ProjectWorkspace::Json { sysroot, .. }
+            | ProjectWorkspace::DetachedFiles { sysroot, .. }) = ws;
             match sysroot {
                 Err(None) => (),
                 Err(Some(e)) => {
@@ -167,7 +169,7 @@ impl GlobalState {
                     }
                 }
             }
-            if let ProjectWorkspaceKind::Cargo { rustc: Err(Some(e)), .. } = &ws.kind {
+            if let ProjectWorkspace::Cargo { rustc: Err(Some(e)), .. } = ws {
                 status.health = lsp_ext::Health::Warning;
                 message.push_str(e);
                 message.push_str("\n\n");
@@ -202,14 +204,7 @@ impl GlobalState {
 
         self.task_pool.handle.spawn_with_sender(ThreadIntent::Worker, {
             let linked_projects = self.config.linked_or_discovered_projects();
-            let detached_files: Vec<_> = self
-                .config
-                .detached_files()
-                .iter()
-                .cloned()
-                .map(ManifestPath::try_from)
-                .filter_map(Result::ok)
-                .collect();
+            let detached_files = self.config.detached_files().to_vec();
             let cargo_config = self.config.cargo();
 
             move |sender| {
@@ -239,7 +234,6 @@ impl GlobalState {
                                 it.clone(),
                                 cargo_config.target.as_deref(),
                                 &cargo_config.extra_env,
-                                &cargo_config.cfg_overrides,
                             ))
                         }
                     })
@@ -260,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,
                     ));
@@ -499,25 +493,20 @@ impl GlobalState {
                     None => ws.find_sysroot_proc_macro_srv()?,
                 };
 
-                let env = match &ws.kind {
-                    ProjectWorkspaceKind::Cargo { cargo_config_extra_env, .. }
-                    | ProjectWorkspaceKind::DetachedFile {
-                        cargo: Some(_),
-                        cargo_config_extra_env,
-                        ..
-                    } => cargo_config_extra_env
-                        .iter()
-                        .chain(self.config.extra_env())
-                        .map(|(a, b)| (a.clone(), b.clone()))
-                        .chain(
-                            ws.sysroot
-                                .as_ref()
-                                .map(|it| ("RUSTUP_TOOLCHAIN".to_owned(), it.root().to_string())),
-                        )
-                        .collect(),
-
-                    _ => Default::default(),
-                };
+                let env =
+                    match ws {
+                        ProjectWorkspace::Cargo { cargo_config_extra_env, sysroot, .. } => {
+                            cargo_config_extra_env
+                                .iter()
+                                .chain(self.config.extra_env())
+                                .map(|(a, b)| (a.clone(), b.clone()))
+                                .chain(sysroot.as_ref().map(|it| {
+                                    ("RUSTUP_TOOLCHAIN".to_owned(), it.root().to_string())
+                                }))
+                                .collect()
+                        }
+                        _ => Default::default(),
+                    };
                 tracing::info!("Using proc-macro server at {path}");
 
                 ProcMacroServer::spawn(path.clone(), &env).map_err(|err| {
@@ -550,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,
@@ -558,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.kind {
-                ProjectWorkspaceKind::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)
             };
 
@@ -596,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,
@@ -669,37 +650,32 @@ impl GlobalState {
                 config,
                 None,
                 self.config.root_path().clone(),
-                None,
             )],
             flycheck::InvocationStrategy::PerWorkspace => {
                 self.workspaces
                     .iter()
                     .enumerate()
-                    .filter_map(|(id, ws)| {
-                        Some((
+                    .filter_map(|(id, w)| match w {
+                        ProjectWorkspace::Cargo { cargo, sysroot, .. } => Some((
                             id,
-                            match &ws.kind {
-                                ProjectWorkspaceKind::Cargo { cargo, .. }
-                                | ProjectWorkspaceKind::DetachedFile {
-                                    cargo: Some((cargo, _)),
-                                    ..
-                                } => (cargo.workspace_root(), Some(cargo.manifest_path())),
-                                ProjectWorkspaceKind::Json(project) => {
-                                    // Enable flychecks for json projects if a custom flycheck command was supplied
-                                    // in the workspace configuration.
-                                    match config {
-                                        FlycheckConfig::CustomCommand { .. } => {
-                                            (project.path(), None)
-                                        }
-                                        _ => return None,
-                                    }
-                                }
-                                ProjectWorkspaceKind::DetachedFile { .. } => return None,
-                            },
-                            ws.sysroot.as_ref().ok().map(|sysroot| sysroot.root().to_owned()),
-                        ))
+                            cargo.workspace_root(),
+                            sysroot.as_ref().ok().map(|sysroot| sysroot.root().to_owned()),
+                        )),
+                        ProjectWorkspace::Json { project, sysroot, .. } => {
+                            // Enable flychecks for json projects if a custom flycheck command was supplied
+                            // in the workspace configuration.
+                            match config {
+                                FlycheckConfig::CustomCommand { .. } => Some((
+                                    id,
+                                    project.path(),
+                                    sysroot.as_ref().ok().map(|sysroot| sysroot.root().to_owned()),
+                                )),
+                                _ => None,
+                            }
+                        }
+                        ProjectWorkspace::DetachedFiles { .. } => None,
                     })
-                    .map(|(id, (root, manifest_path), sysroot_root)| {
+                    .map(|(id, root, sysroot_root)| {
                         let sender = sender.clone();
                         FlycheckHandle::spawn(
                             id,
@@ -707,7 +683,6 @@ impl GlobalState {
                             config.clone(),
                             sysroot_root,
                             root.to_path_buf(),
-                            manifest_path.map(|it| it.to_path_buf()),
                         )
                     })
                     .collect()
@@ -737,7 +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 { 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,
@@ -746,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
@@ -758,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/syntax/rust.ungram b/crates/syntax/rust.ungram
index 8a775dd874..e1765b25fd 100644
--- a/crates/syntax/rust.ungram
+++ b/crates/syntax/rust.ungram
@@ -391,7 +391,6 @@ 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/crates/vfs/Cargo.toml b/crates/vfs/Cargo.toml
index c88f346655..84f2110eba 100644
--- a/crates/vfs/Cargo.toml
+++ b/crates/vfs/Cargo.toml
@@ -13,6 +13,7 @@ doctest = false
 
 [dependencies]
 rustc-hash.workspace = true
+tracing.workspace = true
 fst = "0.4.7"
 indexmap.workspace = true
 nohash-hasher.workspace = true
@@ -21,4 +22,4 @@ paths.workspace = true
 stdx.workspace = true
 
 [lints]
-workspace = true
\ No newline at end of file
+workspace = true
diff --git a/crates/vfs/src/lib.rs b/crates/vfs/src/lib.rs
index ddd6bbe3f7..cb3e058355 100644
--- a/crates/vfs/src/lib.rs
+++ b/crates/vfs/src/lib.rs
@@ -56,6 +56,8 @@ pub use crate::{
 };
 pub use paths::{AbsPath, AbsPathBuf};
 
+use tracing::{span, Level};
+
 /// Handle to a file in [`Vfs`]
 ///
 /// Most functions in rust-analyzer use this when they need to refer to a file.
@@ -210,6 +212,7 @@ impl Vfs {
     /// If the path does not currently exists in the `Vfs`, allocates a new
     /// [`FileId`] for it.
     pub fn set_file_contents(&mut self, path: VfsPath, contents: Option<Vec<u8>>) -> bool {
+        let _p = span!(Level::INFO, "Vfs::set_file_contents").entered();
         let file_id = self.alloc_file_id(path);
         let state = self.get(file_id);
         let change_kind = match (state, contents) {
@@ -236,6 +239,7 @@ impl Vfs {
 
     /// Drain and returns all the changes in the `Vfs`.
     pub fn take_changes(&mut self) -> Vec<ChangedFile> {
+        let _p = span!(Level::INFO, "Vfs::take_changes").entered();
         for file_id in self.created_this_cycle.drain(..) {
             if self.data[file_id.0 as usize] == FileState::Created {
                 // downgrade the file from `Created` to `Exists` as the cycle is done
diff --git a/docs/dev/README.md b/docs/dev/README.md
index 8897f02e27..cdab6b0992 100644
--- a/docs/dev/README.md
+++ b/docs/dev/README.md
@@ -229,22 +229,12 @@ Release steps:
      * publishes the VS Code extension to the marketplace
    * call the GitHub API for PR details
    * create a new changelog in `rust-analyzer.github.io`
-3. While the release is in progress, fill in the changelog.
-4. Commit & push the changelog.
+3. While the release is in progress, fill in the changelog
+4. Commit & push the changelog
 5. Run `cargo xtask publish-release-notes <CHANGELOG>` -- this will convert the changelog entry in AsciiDoc to Markdown and update the body of GitHub Releases entry.
-6. Tweet.
-7. Make a new branch and run `cargo xtask rustc-pull`, open a PR, and merge it.
-   This will pull any changes from `rust-lang/rust` into `rust-analyzer`.
-8. Switch to `master`, pull, then run `cargo xtask rustc-push --rust-path ../rust-rust-analyzer --rust-fork matklad/rust`.
-   Replace `matklad/rust` with your own fork of `rust-lang/rust`.
-   You can use the token to authenticate when you get prompted for a password, since `josh` will push over HTTPS, not SSH.
-   This will push the `rust-analyzer` changes to your fork.
-   You can then open a PR against `rust-lang/rust`.
-
-Note: besides the `rust-rust-analyzer` clone, the Josh cache (stored under `~/.cache/rust-analyzer-josh`) will contain a bare clone of `rust-lang/rust`.
-This currently takes about 3.5 GB.
-
-This [HackMD](https://hackmd.io/7pOuxnkdQDaL1Y1FQr65xg) has details about how `josh` syncs work.
+6. Tweet
+7. Inside `rust-analyzer`, run `cargo xtask promote` -- this will create a PR to rust-lang/rust updating rust-analyzer's subtree.
+   Self-approve the PR.
 
 If the GitHub Actions release fails because of a transient problem like a timeout, you can re-run the job from the Actions console.
 If it fails because of something that needs to be fixed, remove the release tag (if needed), fix the problem, then start over.
diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc
index 6e4820c5de..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`)::
 +
@@ -778,8 +782,7 @@ Disable project auto-discovery in favor of explicitly specified set
 of projects.
 
 Elements must be paths pointing to `Cargo.toml`,
-`rust-project.json`, `.rs` files (which will be treated as standalone files) or JSON
-objects in `rust-project.json` format.
+`rust-project.json`, or JSON objects in `rust-project.json` format.
 --
 [[rust-analyzer.lru.capacity]]rust-analyzer.lru.capacity (default: `null`)::
 +
@@ -848,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 352eb24229..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,
@@ -1495,7 +1502,7 @@
                     "type": "boolean"
                 },
                 "rust-analyzer.linkedProjects": {
-                    "markdownDescription": "Disable project auto-discovery in favor of explicitly specified set\nof projects.\n\nElements must be paths pointing to `Cargo.toml`,\n`rust-project.json`, `.rs` files (which will be treated as standalone files) or JSON\nobjects in `rust-project.json` format.",
+                    "markdownDescription": "Disable project auto-discovery in favor of explicitly specified set\nof projects.\n\nElements must be paths pointing to `Cargo.toml`,\n`rust-project.json`, or JSON objects in `rust-project.json` format.",
                     "default": [],
                     "type": "array",
                     "items": {
@@ -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,
diff --git a/rust-version b/rust-version
deleted file mode 100644
index e2a22b2395..0000000000
--- a/rust-version
+++ /dev/null
@@ -1,1 +0,0 @@
-688c30dc9f8434d63bddb65bd6a4d2258d19717c
diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml
index 192de86947..a83d32e414 100644
--- a/xtask/Cargo.toml
+++ b/xtask/Cargo.toml
@@ -8,7 +8,6 @@ rust-version.workspace = true
 
 [dependencies]
 anyhow.workspace = true
-directories = "5.0"
 flate2 = "1.0.24"
 write-json = "0.1.2"
 xshell.workspace = true
diff --git a/xtask/src/flags.rs b/xtask/src/flags.rs
index dd7bfd0bda..9066545920 100644
--- a/xtask/src/flags.rs
+++ b/xtask/src/flags.rs
@@ -14,16 +14,16 @@ xflags::xflags! {
         cmd install {
             /// Install only VS Code plugin.
             optional --client
-            /// One of `code`, `code-exploration`, `code-insiders`, `codium`, or `code-oss`.
+            /// One of 'code', 'code-exploration', 'code-insiders', 'codium', or 'code-oss'.
             optional --code-bin name: String
 
             /// Install only the language server.
             optional --server
-            /// Use mimalloc allocator for server.
+            /// Use mimalloc allocator for server
             optional --mimalloc
-            /// Use jemalloc allocator for server.
+            /// Use jemalloc allocator for server
             optional --jemalloc
-            /// build in release with debug info set to 2.
+            /// build in release with debug info set to 2
             optional --dev-rel
         }
 
@@ -32,21 +32,9 @@ xflags::xflags! {
         cmd release {
             optional --dry-run
         }
-
-        cmd rustc-pull {
-            /// rustc commit to pull.
-            optional --commit refspec: String
-        }
-
-        cmd rustc-push {
-            /// rust local path, e.g. `../rust-rust-analyzer`.
-            required --rust-path rust_path: String
-            /// rust fork name, e.g.  `matklad/rust`.
-            required --rust-fork rust_fork: String
-            /// branch name.
-            optional --branch branch: String
+        cmd promote {
+            optional --dry-run
         }
-
         cmd dist {
             /// Use mimalloc allocator for server
             optional --mimalloc
@@ -89,8 +77,7 @@ pub enum XtaskCmd {
     Install(Install),
     FuzzTests(FuzzTests),
     Release(Release),
-    RustcPull(RustcPull),
-    RustcPush(RustcPush),
+    Promote(Promote),
     Dist(Dist),
     PublishReleaseNotes(PublishReleaseNotes),
     Metrics(Metrics),
@@ -117,15 +104,8 @@ pub struct Release {
 }
 
 #[derive(Debug)]
-pub struct RustcPull {
-    pub commit: Option<String>,
-}
-
-#[derive(Debug)]
-pub struct RustcPush {
-    pub rust_path: String,
-    pub rust_fork: String,
-    pub branch: Option<String>,
+pub struct Promote {
+    pub dry_run: bool,
 }
 
 #[derive(Debug)]
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index e070576303..9418675a34 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -34,8 +34,7 @@ fn main() -> anyhow::Result<()> {
         flags::XtaskCmd::Install(cmd) => cmd.run(sh),
         flags::XtaskCmd::FuzzTests(_) => run_fuzzer(sh),
         flags::XtaskCmd::Release(cmd) => cmd.run(sh),
-        flags::XtaskCmd::RustcPull(cmd) => cmd.run(sh),
-        flags::XtaskCmd::RustcPush(cmd) => cmd.run(sh),
+        flags::XtaskCmd::Promote(cmd) => cmd.run(sh),
         flags::XtaskCmd::Dist(cmd) => cmd.run(sh),
         flags::XtaskCmd::PublishReleaseNotes(cmd) => cmd.run(sh),
         flags::XtaskCmd::Metrics(cmd) => cmd.run(sh),
diff --git a/xtask/src/release.rs b/xtask/src/release.rs
index 9dcf7af00b..1a5e6dfb4c 100644
--- a/xtask/src/release.rs
+++ b/xtask/src/release.rs
@@ -1,12 +1,5 @@
 mod changelog;
 
-use std::process::{Command, Stdio};
-use std::thread;
-use std::time::Duration;
-
-use anyhow::{bail, Context as _};
-use directories::ProjectDirs;
-use stdx::JodChild;
 use xshell::{cmd, Shell};
 
 use crate::{codegen, date_iso, flags, is_release_tag, project_root};
@@ -78,154 +71,26 @@ impl flags::Release {
     }
 }
 
-// git sync implementation adapted from https://github.com/rust-lang/miri/blob/62039ac/miri-script/src/commands.rs
-impl flags::RustcPull {
-    pub(crate) fn run(self, sh: &Shell) -> anyhow::Result<()> {
-        sh.change_dir(project_root());
-        let commit = self.commit.map(Result::Ok).unwrap_or_else(|| {
-            let rust_repo_head =
-                cmd!(sh, "git ls-remote https://github.com/rust-lang/rust/ HEAD").read()?;
-            rust_repo_head
-                .split_whitespace()
-                .next()
-                .map(|front| front.trim().to_owned())
-                .ok_or_else(|| anyhow::format_err!("Could not obtain Rust repo HEAD from remote."))
-        })?;
-        // Make sure the repo is clean.
-        if !cmd!(sh, "git status --untracked-files=no --porcelain").read()?.is_empty() {
-            bail!("working directory must be clean before running `cargo xtask pull`");
-        }
-        // Make sure josh is running.
-        let josh = start_josh()?;
-
-        // Update rust-version file. As a separate commit, since making it part of
-        // the merge has confused the heck out of josh in the past.
-        // We pass `--no-verify` to avoid running any git hooks that might exist,
-        // in case they dirty the repository.
-        sh.write_file("rust-version", format!("{commit}\n"))?;
-        const PREPARING_COMMIT_MESSAGE: &str = "Preparing for merge from rust-lang/rust";
-        cmd!(sh, "git commit rust-version --no-verify -m {PREPARING_COMMIT_MESSAGE}")
-            .run()
-            .context("FAILED to commit rust-version file, something went wrong")?;
-
-        // Fetch given rustc commit.
-        cmd!(sh, "git fetch http://localhost:{JOSH_PORT}/rust-lang/rust.git@{commit}{JOSH_FILTER}.git")
-            .run()
-            .map_err(|e| {
-                // Try to un-do the previous `git commit`, to leave the repo in the state we found it it.
-                cmd!(sh, "git reset --hard HEAD^")
-                    .run()
-                    .expect("FAILED to clean up again after failed `git fetch`, sorry for that");
-                e
-            })
-            .context("FAILED to fetch new commits, something went wrong (committing the rust-version file has been undone)")?;
-
-        // Merge the fetched commit.
-        const MERGE_COMMIT_MESSAGE: &str = "Merge from rust-lang/rust";
-        cmd!(sh, "git merge FETCH_HEAD --no-verify --no-ff -m {MERGE_COMMIT_MESSAGE}")
-            .run()
-            .context("FAILED to merge new commits, something went wrong")?;
-
-        drop(josh);
-        Ok(())
-    }
-}
-
-impl flags::RustcPush {
+impl flags::Promote {
     pub(crate) fn run(self, sh: &Shell) -> anyhow::Result<()> {
-        let branch = self.branch.as_deref().unwrap_or("sync-from-ra");
-        let rust_path = self.rust_path;
-        let rust_fork = self.rust_fork;
-
-        sh.change_dir(project_root());
-        let base = sh.read_file("rust-version")?.trim().to_owned();
-        // Make sure the repo is clean.
-        if !cmd!(sh, "git status --untracked-files=no --porcelain").read()?.is_empty() {
-            bail!("working directory must be clean before running `cargo xtask push`");
-        }
-        // Make sure josh is running.
-        let josh = start_josh()?;
+        let _dir = sh.push_dir("../rust-rust-analyzer");
+        cmd!(sh, "git switch master").run()?;
+        cmd!(sh, "git fetch upstream").run()?;
+        cmd!(sh, "git reset --hard upstream/master").run()?;
 
-        // Find a repo we can do our preparation in.
-        sh.change_dir(rust_path);
+        let date = date_iso(sh)?;
+        let branch = format!("rust-analyzer-{date}");
+        cmd!(sh, "git switch -c {branch}").run()?;
+        cmd!(sh, "git subtree pull -m ':arrow_up: rust-analyzer' -P src/tools/rust-analyzer rust-analyzer release").run()?;
 
-        // Prepare the branch. Pushing works much better if we use as base exactly
-        // the commit that we pulled from last time, so we use the `rust-version`
-        // file to find out which commit that would be.
-        println!("Preparing {rust_fork} (base: {base})...");
-        if cmd!(sh, "git fetch https://github.com/{rust_fork} {branch}")
-            .ignore_stderr()
-            .read()
-            .is_ok()
-        {
-            bail!(
-                "The branch `{branch}` seems to already exist in `https://github.com/{rust_fork}`. Please delete it and try again."
-            );
-        }
-        cmd!(sh, "git fetch https://github.com/rust-lang/rust {base}").run()?;
-        cmd!(sh, "git push https://github.com/{rust_fork} {base}:refs/heads/{branch}")
-            .ignore_stdout()
-            .ignore_stderr() // silence the "create GitHub PR" message
+        if !self.dry_run {
+            cmd!(sh, "git push -u origin {branch}").run()?;
+            cmd!(
+                sh,
+                "xdg-open https://github.com/matklad/rust/pull/new/{branch}?body=r%3F%20%40ghost"
+            )
             .run()?;
-        println!();
-
-        // Do the actual push.
-        sh.change_dir(project_root());
-        println!("Pushing rust-analyzer changes...");
-        cmd!(
-            sh,
-            "git push http://localhost:{JOSH_PORT}/{rust_fork}.git{JOSH_FILTER}.git HEAD:{branch}"
-        )
-        .run()?;
-        println!();
-
-        // Do a round-trip check to make sure the push worked as expected.
-        cmd!(
-            sh,
-            "git fetch http://localhost:{JOSH_PORT}/{rust_fork}.git{JOSH_FILTER}.git {branch}"
-        )
-        .ignore_stderr()
-        .read()?;
-        let head = cmd!(sh, "git rev-parse HEAD").read()?;
-        let fetch_head = cmd!(sh, "git rev-parse FETCH_HEAD").read()?;
-        if head != fetch_head {
-            bail!("Josh created a non-roundtrip push! Do NOT merge this into rustc!");
         }
-        println!("Confirmed that the push round-trips back to rust-analyzer properly. Please create a rustc PR:");
-        // https://github.com/github-linguist/linguist/compare/master...octocat:linguist:master
-        let fork_path = rust_fork.replace('/', ":");
-        println!(
-            "    https://github.com/rust-lang/rust/compare/{fork_path}:{branch}?quick_pull=1&title=Subtree+update+of+rust-analyzer&body=r?+@ghost"
-        );
-
-        drop(josh);
         Ok(())
     }
 }
-
-/// Used for rustc syncs.
-const JOSH_FILTER: &str =
-    ":rev(55d9a533b309119c8acd13061581b43ae8840823:prefix=src/tools/rust-analyzer):/src/tools/rust-analyzer";
-const JOSH_PORT: &str = "42042";
-
-fn start_josh() -> anyhow::Result<impl Drop> {
-    // Determine cache directory.
-    let local_dir = {
-        let user_dirs = ProjectDirs::from("org", "rust-lang", "rust-analyzer-josh").unwrap();
-        user_dirs.cache_dir().to_owned()
-    };
-
-    // Start josh, silencing its output.
-    let mut cmd = Command::new("josh-proxy");
-    cmd.arg("--local").arg(local_dir);
-    cmd.arg("--remote").arg("https://github.com");
-    cmd.arg("--port").arg(JOSH_PORT);
-    cmd.arg("--no-background");
-    cmd.stdout(Stdio::null());
-    cmd.stderr(Stdio::null());
-    let josh = cmd.spawn().context("failed to start josh-proxy, make sure it is installed")?;
-    // Give it some time so hopefully the port is open. (100ms was not enough.)
-    thread::sleep(Duration::from_millis(200));
-
-    Ok(JodChild(josh))
-}


Test patch:
diff --git a/crates/hir-def/src/body/tests.rs b/crates/hir-def/src/body/tests.rs
index 4c8a54f7c8..a27ffe2167 100644
--- a/crates/hir-def/src/body/tests.rs
+++ b/crates/hir-def/src/body/tests.rs
@@ -318,20 +318,18 @@ 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 4abbda56cb..381522c9ab 100644
--- a/crates/hir-ty/src/mir/eval/tests.rs
+++ b/crates/hir-ty/src/mir/eval/tests.rs
@@ -31,7 +31,6 @@ 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()))
@@ -73,13 +72,6 @@ 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(
@@ -95,43 +87,6 @@ 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 cd5e95cc1e..bb5c2b7913 100644
--- a/crates/ide-diagnostics/src/tests.rs
+++ b/crates/ide-diagnostics/src/tests.rs
@@ -293,7 +293,6 @@ 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 0f666d40da..6bbc8b380d 100644
--- a/crates/ide/src/hover/tests.rs
+++ b/crates/ide/src/hover/tests.rs
@@ -7864,8 +7864,8 @@ impl Iterator for S {
                                 file_id: FileId(
                                     1,
                                 ),
-                                full_range: 7791..7999,
-                                focus_range: 7856..7862,
+                                full_range: 6290..6498,
+                                focus_range: 6355..6361,
                                 name: "Future",
                                 kind: Trait,
                                 container_name: "future",
@@ -7878,8 +7878,8 @@ impl Iterator for S {
                                 file_id: FileId(
                                     1,
                                 ),
-                                full_range: 8629..9095,
-                                focus_range: 8673..8681,
+                                full_range: 7128..7594,
+                                focus_range: 7172..7180,
                                 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 893e3c0675..366895ce7e 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 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 consuming 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 22706dea1f..7a07d17b27 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="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="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">"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="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="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/project-model/src/tests.rs b/crates/project-model/src/tests.rs
index 1308015d13..fc0b507b33 100644
--- a/crates/project-model/src/tests.rs
+++ b/crates/project-model/src/tests.rs
@@ -1,7 +1,6 @@
 use std::ops::Deref;
 
 use base_db::{CrateGraph, FileId, ProcMacroPaths};
-use cargo_metadata::Metadata;
 use cfg::{CfgAtom, CfgDiff};
 use expect_test::{expect_file, ExpectFile};
 use paths::{AbsPath, AbsPathBuf, Utf8Path, Utf8PathBuf};
@@ -10,8 +9,8 @@ use serde::de::DeserializeOwned;
 use triomphe::Arc;
 
 use crate::{
-    workspace::ProjectWorkspaceKind, CargoWorkspace, CfgOverrides, ManifestPath, ProjectJson,
-    ProjectJsonData, ProjectWorkspace, Sysroot, WorkspaceBuildScripts,
+    CargoWorkspace, CfgOverrides, ProjectJson, ProjectJsonData, ProjectWorkspace, Sysroot,
+    WorkspaceBuildScripts,
 };
 
 fn load_cargo(file: &str) -> (CrateGraph, ProcMacroPaths) {
@@ -22,22 +21,18 @@ fn load_cargo_with_overrides(
     file: &str,
     cfg_overrides: CfgOverrides,
 ) -> (CrateGraph, ProcMacroPaths) {
-    let meta: Metadata = get_test_json_file(file);
-    let manifest_path =
-        ManifestPath::try_from(AbsPathBuf::try_from(meta.workspace_root.clone()).unwrap()).unwrap();
-    let cargo_workspace = CargoWorkspace::new(meta, manifest_path);
-    let project_workspace = ProjectWorkspace {
-        kind: ProjectWorkspaceKind::Cargo {
-            cargo: cargo_workspace,
-            build_scripts: WorkspaceBuildScripts::default(),
-            rustc: Err(None),
-            cargo_config_extra_env: Default::default(),
-        },
-        cfg_overrides,
+    let meta = get_test_json_file(file);
+    let cargo_workspace = CargoWorkspace::new(meta);
+    let project_workspace = ProjectWorkspace::Cargo {
+        cargo: cargo_workspace,
+        build_scripts: WorkspaceBuildScripts::default(),
         sysroot: Err(None),
+        rustc: Err(None),
         rustc_cfg: Vec::new(),
+        cfg_overrides,
         toolchain: None,
         target_layout: Err("target_data_layout not loaded".into()),
+        cargo_config_extra_env: Default::default(),
     };
     to_crate_graph(project_workspace)
 }
@@ -46,22 +41,18 @@ fn load_cargo_with_fake_sysroot(
     file_map: &mut FxHashMap<AbsPathBuf, FileId>,
     file: &str,
 ) -> (CrateGraph, ProcMacroPaths) {
-    let meta: Metadata = get_test_json_file(file);
-    let manifest_path =
-        ManifestPath::try_from(AbsPathBuf::try_from(meta.workspace_root.clone()).unwrap()).unwrap();
-    let cargo_workspace = CargoWorkspace::new(meta, manifest_path);
-    let project_workspace = ProjectWorkspace {
-        kind: ProjectWorkspaceKind::Cargo {
-            cargo: cargo_workspace,
-            build_scripts: WorkspaceBuildScripts::default(),
-            rustc: Err(None),
-            cargo_config_extra_env: Default::default(),
-        },
+    let meta = get_test_json_file(file);
+    let cargo_workspace = CargoWorkspace::new(meta);
+    let project_workspace = ProjectWorkspace::Cargo {
+        cargo: cargo_workspace,
+        build_scripts: WorkspaceBuildScripts::default(),
         sysroot: Ok(get_fake_sysroot()),
+        rustc: Err(None),
         rustc_cfg: Vec::new(),
         cfg_overrides: Default::default(),
         toolchain: None,
         target_layout: Err("target_data_layout not loaded".into()),
+        cargo_config_extra_env: Default::default(),
     };
     project_workspace.to_crate_graph(
         &mut {
@@ -78,13 +69,12 @@ fn load_rust_project(file: &str) -> (CrateGraph, ProcMacroPaths) {
     let data = get_test_json_file(file);
     let project = rooted_project_json(data);
     let sysroot = Ok(get_fake_sysroot());
-    let project_workspace = ProjectWorkspace {
-        kind: ProjectWorkspaceKind::Json(project),
+    let project_workspace = ProjectWorkspace::Json {
+        project,
         sysroot,
         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)
 }
@@ -107,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/" };
@@ -170,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);
 }
@@ -277,10 +260,9 @@ fn smoke_test_real_sysroot_cargo() {
         return;
     }
     let file_map = &mut FxHashMap::<AbsPathBuf, FileId>::default();
-    let meta: Metadata = get_test_json_file("hello-world-metadata.json");
-    let manifest_path =
-        ManifestPath::try_from(AbsPathBuf::try_from(meta.workspace_root.clone()).unwrap()).unwrap();
-    let cargo_workspace = CargoWorkspace::new(meta, manifest_path);
+    let meta = get_test_json_file("hello-world-metadata.json");
+
+    let cargo_workspace = CargoWorkspace::new(meta);
     let sysroot = Ok(Sysroot::discover(
         AbsPath::assert(Utf8Path::new(env!("CARGO_MANIFEST_DIR"))),
         &Default::default(),
@@ -288,18 +270,16 @@ fn smoke_test_real_sysroot_cargo() {
     )
     .unwrap());
 
-    let project_workspace = ProjectWorkspace {
-        kind: ProjectWorkspaceKind::Cargo {
-            cargo: cargo_workspace,
-            build_scripts: WorkspaceBuildScripts::default(),
-            rustc: Err(None),
-            cargo_config_extra_env: Default::default(),
-        },
+    let project_workspace = ProjectWorkspace::Cargo {
+        cargo: cargo_workspace,
+        build_scripts: WorkspaceBuildScripts::default(),
         sysroot,
+        rustc: Err(None),
         rustc_cfg: Vec::new(),
         cfg_overrides: Default::default(),
         toolchain: None,
         target_layout: Err("target_data_layout not loaded".into()),
+        cargo_config_extra_env: Default::default(),
     };
     project_workspace.to_crate_graph(
         &mut {
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 85f964b1dd..eeec13a14b 100644
--- a/crates/rust-analyzer/src/cli/rustc_tests.rs
+++ b/crates/rust-analyzer/src/cli/rustc_tests.rs
@@ -10,10 +10,7 @@ use ide::{AnalysisHost, DiagnosticCode, DiagnosticsConfig};
 use itertools::Either;
 use profile::StopWatch;
 use project_model::target_data_layout::RustcDataLayoutConfig;
-use project_model::{
-    target_data_layout, CargoConfig, ManifestPath, ProjectWorkspace, ProjectWorkspaceKind,
-    RustLibSource, Sysroot,
-};
+use project_model::{target_data_layout, CargoConfig, ProjectWorkspace, RustLibSource, Sysroot};
 
 use load_cargo::{load_workspace, LoadCargoConfig, ProcMacroServerChoice};
 use rustc_hash::FxHashMap;
@@ -78,17 +75,12 @@ impl Tester {
             &cargo_config.extra_env,
         );
 
-        let workspace = ProjectWorkspace {
-            kind: ProjectWorkspaceKind::DetachedFile {
-                file: ManifestPath::try_from(tmp_file).unwrap(),
-                cargo: None,
-                cargo_config_extra_env: Default::default(),
-            },
+        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(),
         };
         let load_cargo_config = LoadCargoConfig {
             load_out_dirs_from_check: false,
diff --git a/crates/rust-analyzer/tests/crate_graph.rs b/crates/rust-analyzer/tests/crate_graph.rs
index 59b229cd06..cf38032b94 100644
--- a/crates/rust-analyzer/tests/crate_graph.rs
+++ b/crates/rust-analyzer/tests/crate_graph.rs
@@ -1,31 +1,24 @@
 use std::path::PathBuf;
 
-use project_model::{
-    CargoWorkspace, ManifestPath, Metadata, ProjectWorkspace, ProjectWorkspaceKind, Sysroot,
-    WorkspaceBuildScripts,
-};
+use project_model::{CargoWorkspace, ProjectWorkspace, Sysroot, WorkspaceBuildScripts};
 use rust_analyzer::ws_to_crate_graph;
 use rustc_hash::FxHashMap;
 use serde::de::DeserializeOwned;
 use vfs::{AbsPathBuf, FileId};
 
 fn load_cargo_with_fake_sysroot(file: &str) -> ProjectWorkspace {
-    let meta: Metadata = get_test_json_file(file);
-    let manifest_path =
-        ManifestPath::try_from(AbsPathBuf::try_from(meta.workspace_root.clone()).unwrap()).unwrap();
-    let cargo_workspace = CargoWorkspace::new(meta, manifest_path);
-    ProjectWorkspace {
-        kind: ProjectWorkspaceKind::Cargo {
-            cargo: cargo_workspace,
-            build_scripts: WorkspaceBuildScripts::default(),
-            rustc: Err(None),
-            cargo_config_extra_env: Default::default(),
-        },
+    let meta = get_test_json_file(file);
+    let cargo_workspace = CargoWorkspace::new(meta);
+    ProjectWorkspace::Cargo {
+        cargo: cargo_workspace,
+        build_scripts: WorkspaceBuildScripts::default(),
         sysroot: Ok(get_fake_sysroot()),
+        rustc: Err(None),
         rustc_cfg: Vec::new(),
         cfg_overrides: Default::default(),
         toolchain: None,
         target_layout: Err("target_data_layout not loaded".into()),
+        cargo_config_extra_env: Default::default(),
     }
 }
 
diff --git a/crates/rust-analyzer/tests/slow-tests/main.rs b/crates/rust-analyzer/tests/slow-tests/main.rs
index 5a1397bbb0..8c982b4687 100644
--- a/crates/rust-analyzer/tests/slow-tests/main.rs
+++ b/crates/rust-analyzer/tests/slow-tests/main.rs
@@ -117,106 +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 },
-        "linkedProjects": ["src/lib.rs"],
-    }))
-    .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() {
@@ -257,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")
@@ -290,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 cf27cc7eef..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(
@@ -188,7 +188,7 @@ impl Project<'_> {
         config.update(self.config).expect("invalid config");
         config.rediscover_workspaces();
 
-        Server::new(tmp_dir.keep(), config)
+        Server::new(tmp_dir, config)
     }
 }
 
@@ -283,7 +283,6 @@ impl Server {
         }
     }
 
-    #[track_caller]
     pub(crate) fn send_request<R>(&self, params: R::Params) -> Value
     where
         R: lsp_types::request::Request,
@@ -295,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();
@@ -376,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/rust-analyzer/tests/slow-tests/tidy.rs b/crates/rust-analyzer/tests/slow-tests/tidy.rs
index 4a7415b016..3443939133 100644
--- a/crates/rust-analyzer/tests/slow-tests/tidy.rs
+++ b/crates/rust-analyzer/tests/slow-tests/tidy.rs
@@ -144,7 +144,6 @@ MIT OR Apache-2.0
 MIT OR Apache-2.0 OR Zlib
 MIT OR Zlib OR Apache-2.0
 MIT/Apache-2.0
-MPL-2.0
 Unlicense OR MIT
 Unlicense/MIT
 Zlib OR Apache-2.0 OR MIT
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 0257ed9ab4..f125792d12 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, copy, clone, derive
+//!     fmt: option, result, transmute, coerce_unsized
 //!     fn:
 //!     from: sized
 //!     future: pin
@@ -913,13 +913,11 @@ pub mod fmt {
     }
 
     mod rt {
-        use super::*;
 
         extern "C" {
             type Opaque;
         }
 
-        #[derive(Copy, Clone)]
         #[lang = "format_argument"]
         pub struct Argument<'a> {
             value: &'a Opaque,
@@ -932,8 +930,8 @@ pub mod fmt {
                 unsafe { Argument { formatter: transmute(f), value: transmute(x) } }
             }
 
-            pub fn new_display<'b, T: crate::fmt::Display>(x: &'b T) -> Argument<'_> {
-                Self::new(x, crate::fmt::Display::fmt)
+            pub fn new_display<'b, T: Display>(x: &'b T) -> Argument<'_> {
+                Self::new(x, Display::fmt)
             }
         }
 
@@ -970,9 +968,7 @@ pub mod fmt {
                 flags: u32,
                 precision: Count,
                 width: Count,
-            ) -> Self {
-                Placeholder { position, fill, align, flags, precision, width }
-            }
+            ) -> Self;
         }
 
         #[lang = "format_unsafe_arg"]
@@ -981,13 +977,10 @@ pub mod fmt {
         }
 
         impl UnsafeArg {
-            pub unsafe fn new() -> Self {
-                UnsafeArg { _private: () }
-            }
+            pub unsafe fn new() -> Self;
         }
     }
 
-    #[derive(Copy, Clone)]
     #[lang = "format_arguments"]
     pub struct Arguments<'a> {
         pieces: &'a [&'static str],
@@ -1012,14 +1005,6 @@ 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
@@ -1169,8 +1154,8 @@ pub mod pin {
         pointer: P,
     }
     impl<P> Pin<P> {
-        pub fn new(pointer: P) -> Pin<P> {
-            Pin { pointer }
+        pub fn new(_pointer: P) -> Pin<P> {
+            loop {}
         }
     }
     // region:deref
@@ -1371,48 +1356,18 @@ pub mod iter {
 // region:panic
 mod panic {
     pub macro panic_2021 {
-        () => ({
-            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)+));
-        }),
+        () => (
+            $crate::panicking::panic("explicit panic")
+        ),
+        ($($t:tt)+) => (
+            $crate::panicking::panic_fmt($crate::const_format_args!($($t)+))
+        ),
     }
 }
 
 mod panicking {
-    #[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<'_>) -> ! {
+    #[lang = "panic_fmt"]
+    pub const fn panic_fmt(_fmt: crate::fmt::Arguments<'_>) -> ! {
         loop {}
     }
 
@@ -1423,7 +1378,6 @@ mod panicking {
 }
 // endregion:panic
 
-#[macro_use]
 mod macros {
     // region:panic
     #[macro_export]
@@ -1516,6 +1470,7 @@ mod macros {
     }
     // endregion:unimplemented
 
+
     // region:derive
     pub(crate) mod builtin {
         #[rustc_builtin_macro]