diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index f7f31cc2e365..cf61716b268f 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -10,9 +10,8 @@ use itertools::Itertools; use ra_ap_hir::Semantics; use ra_ap_ide_db::RootDatabase; use ra_ap_ide_db::line_index::{LineCol, LineIndex}; -use ra_ap_load_cargo::LoadCargoConfig; use ra_ap_paths::{AbsPathBuf, Utf8PathBuf}; -use ra_ap_project_model::{CargoConfig, ProjectManifest}; +use ra_ap_project_model::ProjectManifest; use ra_ap_vfs::Vfs; use rust_analyzer::{ParseResult, RustAnalyzer}; use std::collections::{BTreeMap, HashSet}; @@ -24,6 +23,7 @@ use std::{env, fs}; use tracing::{error, info, warn}; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; +use workspaces::LoadedWorkspaces; mod archive; mod config; @@ -38,6 +38,7 @@ mod toolchain; mod translate; pub mod trap; mod util; +mod workspaces; struct Extractor<'a> { archiver: &'a Archiver, @@ -128,19 +129,6 @@ impl<'a> Extractor<'a> { self.extract(&RustAnalyzer::from(err), file, source_kind); } - pub fn load_manifest( - &mut self, - project: &ProjectManifest, - config: &CargoConfig, - load_config: &LoadCargoConfig, - ) -> Option<(RootDatabase, Vfs)> { - let before = Instant::now(); - let ret = RustAnalyzer::load_workspace(project, config, load_config); - self.steps - .push(ExtractionStep::load_manifest(before, project)); - ret - } - pub fn load_source( &mut self, file: &Path, @@ -386,25 +374,29 @@ fn main() -> anyhow::Result<()> { // workspace a dependency file should be extracted. let dependency_extraction_ambiguity = workspaces.len() == 1; - for (manifest, files) in workspaces.values() { - if let Some((db, vfs)) = - extractor.load_manifest(manifest, &cargo_config, &load_cargo_config) - { + // loading in the background needs a thread beyond the sequential extraction one + let mut loaded = LoadedWorkspaces::new(threads > 1, move |manifest| { + RustAnalyzer::load_workspace(manifest, &cargo_config, &load_cargo_config) + }); + let mut workspaces = workspaces.values().peekable(); + while let Some((manifest, files)) = workspaces.next() { + let next = workspaces.peek().map(|(next, _)| *next); + if let Some((db, vfs)) = loaded.get(manifest, next, &mut extractor.steps) { let before_crate_graph = Instant::now(); - crate_graph::extract_crate_graph(extractor.traps, &db, &vfs); + crate_graph::extract_crate_graph(extractor.traps, db, vfs); extractor .steps .push(ExtractionStep::crate_graph(before_crate_graph)); let mut items: Vec<(&Path, bool)> = files.iter().map(|f| (*f, true)).collect(); // Fast path when there is no ambiguity in dependency extraction. if dependency_extraction_ambiguity { - items.extend(dependency_files(&db, &vfs, &source_files).map(|(_, f)| (f, false))); + items.extend(dependency_files(db, vfs, &source_files).map(|(_, f)| (f, false))); } - prime_def_maps(&db, &vfs, items.iter().map(|(f, _)| *f), threads); + prime_def_maps(db, vfs, items.iter().map(|(f, _)| *f), threads); debug_assert!(items.iter().map(|(f, _)| f).all_unique()); extractor.run_parallel( - &db, - &vfs, + db, + vfs, threads, &items, |extractor, semantics, vfs, &(file, is_source)| { @@ -421,8 +413,8 @@ fn main() -> anyhow::Result<()> { }, ); if !dependency_extraction_ambiguity { - let semantics = Semantics::new(&db); - dependencies.add_manifest(manifest, &semantics, &vfs, &source_files); + let semantics = Semantics::new(db); + dependencies.add_manifest(manifest, &semantics, vfs, &source_files); } } else { for file in files { @@ -439,14 +431,17 @@ fn main() -> anyhow::Result<()> { // preferred. Note that when `dependency_extraction_ambiguity` is true then // `selected` below is empty. loop { - let selected = dependencies.by_manifests(); + let mut selected = dependencies.by_manifests().into_iter().collect_vec(); if selected.is_empty() { break; } - for (manifest, files) in selected { - if let Some((db, vfs)) = - extractor.load_manifest(manifest, &cargo_config, &load_cargo_config) - { + // The order does not affect what is extracted: start with the workspaces still loaded. + selected + .sort_by_key(|&(manifest, _)| (!loaded.contains(manifest), manifest_parent(manifest))); + let mut selected = selected.into_iter().peekable(); + while let Some((manifest, files)) = selected.next() { + let next = selected.peek().map(|(next, _)| *next); + if let Some((db, vfs)) = loaded.get(manifest, next, &mut extractor.steps) { // `has_alternative` is evaluated upfront, which is equivalent to evaluating it // just before each extraction as each file occurs at most once in `selected`. let items: Vec<_> = files @@ -458,8 +453,8 @@ fn main() -> anyhow::Result<()> { .collect(); debug_assert!(items.iter().map(|(f, _)| f).all_unique()); let extracted = extractor.run_parallel( - &db, - &vfs, + db, + vfs, threads, &items, |extractor, semantics, vfs, (file, has_alternative)| { @@ -496,6 +491,7 @@ fn main() -> anyhow::Result<()> { } } } + drop(loaded); let builtins_dir = env::var("CODEQL_EXTRACTOR_RUST_ROOT") .map(|path| Path::new(&path).join("tools").join("builtins"))?; diff --git a/rust/extractor/src/parallel.rs b/rust/extractor/src/parallel.rs index c38490a761ab..e3706487ff65 100644 --- a/rust/extractor/src/parallel.rs +++ b/rust/extractor/src/parallel.rs @@ -25,7 +25,7 @@ fn threads_from(value: Option<&str>, cores: usize) -> usize { /// Extraction recurses deeply on nested code, so workers need more than the default 2 MiB stack. /// This matches what rust-analyzer uses for its own threads. -const WORKER_STACK_SIZE: usize = 16 << 20; +pub const WORKER_STACK_SIZE: usize = 16 << 20; /// Sets the flag if the current thread unwinds while this is alive. struct AbortOnPanic<'a>(&'a AtomicBool); diff --git a/rust/extractor/src/workspaces.rs b/rust/extractor/src/workspaces.rs new file mode 100644 index 000000000000..56c4e7fea75e --- /dev/null +++ b/rust/extractor/src/workspaces.rs @@ -0,0 +1,247 @@ +use crate::diagnostics::ExtractionStep; +use crate::parallel::WORKER_STACK_SIZE; +use ra_ap_project_model::ProjectManifest; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::time::Instant; +use tracing::{error, warn}; + +type Loaded = (Option, ExtractionStep); + +/// The workspace loaded from the last requested manifest, kept so that it need not be reloaded +/// if requested again. Optionally, the manifest that is going to be requested next is loaded in +/// the background meanwhile, so at most two workspaces are held at any time. +pub struct LoadedWorkspaces<'m, W, L> { + current: Option<(&'m ProjectManifest, W)>, + prefetched: Option<(&'m ProjectManifest, JoinHandle>)>, + load: Arc, + prefetch: bool, +} + +impl<'m, W, L> LoadedWorkspaces<'m, W, L> +where + W: Send + 'static, + L: Fn(&ProjectManifest) -> Option + Send + Sync + 'static, +{ + pub fn new(prefetch: bool, load: L) -> Self { + Self { + current: None, + prefetched: None, + load: Arc::new(load), + prefetch, + } + } + + pub fn contains(&self, manifest: &ProjectManifest) -> bool { + self.current.as_ref().is_some_and(|(m, _)| *m == manifest) + } + + /// Returns the workspace of `manifest`, loading it unless still loaded, or `None` if it cannot + /// be loaded. Then starts loading `next` in the background, if prefetching is enabled. + pub fn get( + &mut self, + manifest: &'m ProjectManifest, + next: Option<&'m ProjectManifest>, + steps: &mut Vec, + ) -> Option<&W> { + if !self.contains(manifest) { + let prefetched = self.take_prefetched(manifest, steps); + self.current = None; + let (workspace, step) = prefetched.unwrap_or_else(|| load_timed(&*self.load, manifest)); + steps.push(step); + self.current = workspace.map(|workspace| (manifest, workspace)); + } + if let Some(next) = next { + self.start_prefetch(next); + } + let (_, workspace) = self.current.as_ref()?; + Some(workspace) + } + + fn take_prefetched( + &mut self, + manifest: &ProjectManifest, + steps: &mut Vec, + ) -> Option> { + let (prefetched, handle) = self.prefetched.take()?; + let loaded = handle + .join() + .unwrap_or_else(|e| std::panic::resume_unwind(e)); + if prefetched == manifest { + return Some(loaded); + } + warn!("discarding {prefetched}, loaded in the background instead of {manifest}"); + steps.push(loaded.1); + None + } + + fn start_prefetch(&mut self, next: &'m ProjectManifest) { + if !self.prefetch || self.prefetched.is_some() || self.contains(next) { + return; + } + let load = Arc::clone(&self.load); + let manifest = next.clone(); + match std::thread::Builder::new() + .stack_size(WORKER_STACK_SIZE) + .spawn(move || load_timed(&*load, &manifest)) + { + Ok(handle) => self.prefetched = Some((next, handle)), + // `next` is then loaded when requested + Err(e) => warn!("cannot load {next} in the background: {e}"), + } + } +} + +impl Drop for LoadedWorkspaces<'_, W, L> { + fn drop(&mut self) { + // do not leave cargo or proc-macro server processes behind + if let Some((manifest, handle)) = self.prefetched.take() + && handle.join().is_err() + { + error!("loading {manifest} in the background panicked"); + } + } +} + +fn load_timed( + load: &impl Fn(&ProjectManifest) -> Option, + manifest: &ProjectManifest, +) -> Loaded { + let before = Instant::now(); + let ret = load(manifest); + (ret, ExtractionStep::load_manifest(before, manifest)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::mpsc::{Receiver, Sender, channel}; + use std::time::Duration; + + struct Stats { + loads: Mutex>, + live: AtomicUsize, + peak: AtomicUsize, + /// Background loads wait for a message on this, so that tests can check that `get` + /// returns while the next workspace is still loading. + gate: Mutex>, + } + + struct Workspace(Arc); + + impl Drop for Workspace { + fn drop(&mut self) { + self.0.live.fetch_sub(1, Ordering::SeqCst); + } + } + + fn stats() -> (Arc, Sender<()>) { + let (sender, receiver) = channel(); + let stats = Stats { + loads: Mutex::default(), + live: AtomicUsize::default(), + peak: AtomicUsize::default(), + gate: Mutex::new(receiver), + }; + (Arc::new(stats), sender) + } + + fn manifests(names: [&str; N]) -> [ProjectManifest; N] { + let root = crate::cwd().unwrap(); + names.map(|name| { + ProjectManifest::from_manifest_file(root.join(name).join("Cargo.toml")).unwrap() + }) + } + + /// Loads workspaces named after their directory, failing for `broken`. + fn loader(stats: &Arc) -> impl Fn(&ProjectManifest) -> Option + use<> { + let stats = Arc::clone(stats); + move |manifest| { + let name = manifest.manifest_path().parent().file_name()?.to_owned(); + // test threads are named, background loading ones are not + let background = std::thread::current().name().is_none(); + if background { + let gate = stats.gate.lock().unwrap(); + gate.recv_timeout(Duration::from_secs(10)) + .expect("background load not released"); + } + let entry = format!("{name}{}", if background { " (background)" } else { "" }); + stats.loads.lock().unwrap().push(entry); + if name == "broken" { + return None; + } + let live = stats.live.fetch_add(1, Ordering::SeqCst) + 1; + stats.peak.fetch_max(live, Ordering::SeqCst); + Some(Workspace(Arc::clone(&stats))) + } + } + + #[test] + fn reuses_last_workspace() { + let (stats, _) = stats(); + let [a, b, broken] = &manifests(["a", "b", "broken"]); + let mut loaded = LoadedWorkspaces::new(false, loader(&stats)); + let mut steps = Vec::new(); + for manifest in [a, a, b, a, broken, broken] { + let got = loaded.get(manifest, None, &mut steps); + assert_eq!(got.is_some(), manifest != broken); + } + // failed loads are not kept + assert_eq!( + *stats.loads.lock().unwrap(), + ["a", "b", "a", "broken", "broken"] + ); + assert_eq!(steps.len(), 5); + assert!(!loaded.contains(a)); + assert_eq!(stats.peak.load(Ordering::SeqCst), 1); + } + + #[test] + fn loads_next_workspace_in_background() { + let (stats, release) = stats(); + let all = manifests(["a", "b", "broken", "c", "d"]); + let mut loaded = LoadedWorkspaces::new(true, loader(&stats)); + let mut steps = Vec::new(); + for (i, manifest) in all.iter().enumerate() { + let next = all.get(i + 1); + let got = loaded.get(manifest, next, &mut steps); + assert_eq!(got.is_some(), i != 2); + if next.is_some() { + release.send(()).unwrap(); + } + } + assert_eq!( + *stats.loads.lock().unwrap(), + [ + "a", + "b (background)", + "broken (background)", + "c (background)", + "d (background)" + ] + ); + assert_eq!(steps.len(), 5); + assert_eq!(stats.peak.load(Ordering::SeqCst), 2); + drop(loaded); + assert_eq!(stats.live.load(Ordering::SeqCst), 0); + } + + #[test] + fn drop_waits_for_background_load() { + let (stats, release) = stats(); + let [a, b] = &manifests(["a", "b"]); + let mut loaded = LoadedWorkspaces::new(true, loader(&stats)); + assert!(loaded.get(a, Some(b), &mut Vec::new()).is_some()); + let releaser = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(100)); + release.send(()).unwrap(); + }); + drop(loaded); + assert_eq!(*stats.loads.lock().unwrap(), ["a", "b (background)"]); + assert_eq!(stats.peak.load(Ordering::SeqCst), 2); + assert_eq!(stats.live.load(Ordering::SeqCst), 0); + releaser.join().unwrap(); + } +} diff --git a/rust/ql/integration-tests/proc-macro-workspaces/a/Cargo.toml b/rust/ql/integration-tests/proc-macro-workspaces/a/Cargo.toml new file mode 100644 index 000000000000..8be3201d8483 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/a/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +[package] +name = "a" +version = "0.1.0" +edition = "2024" + +[dependencies] +macros = { path = "../macros" } diff --git a/rust/ql/integration-tests/proc-macro-workspaces/a/src/lib.rs b/rust/ql/integration-tests/proc-macro-workspaces/a/src/lib.rs new file mode 100644 index 000000000000..987118f4b777 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/a/src/lib.rs @@ -0,0 +1,5 @@ +macros::generate!(a); + +pub fn call() -> u32 { + from_a() +} diff --git a/rust/ql/integration-tests/proc-macro-workspaces/b/Cargo.toml b/rust/ql/integration-tests/proc-macro-workspaces/b/Cargo.toml new file mode 100644 index 000000000000..f4800e33fb03 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/b/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +[package] +name = "b" +version = "0.1.0" +edition = "2024" + +[dependencies] +macros = { path = "../macros" } diff --git a/rust/ql/integration-tests/proc-macro-workspaces/b/src/lib.rs b/rust/ql/integration-tests/proc-macro-workspaces/b/src/lib.rs new file mode 100644 index 000000000000..4ddd933d2f0c --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/b/src/lib.rs @@ -0,0 +1,5 @@ +macros::generate!(b); + +pub fn call() -> u32 { + from_b() +} diff --git a/rust/ql/integration-tests/proc-macro-workspaces/calls.expected b/rust/ql/integration-tests/proc-macro-workspaces/calls.expected new file mode 100644 index 000000000000..fac9fa604cdf --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/calls.expected @@ -0,0 +1,2 @@ +| a/src/lib.rs:4:5:4:12 | from_a(...) | a::from_a | +| b/src/lib.rs:4:5:4:12 | from_b(...) | b::from_b | diff --git a/rust/ql/integration-tests/proc-macro-workspaces/calls.ql b/rust/ql/integration-tests/proc-macro-workspaces/calls.ql new file mode 100644 index 000000000000..8cb0f9b4dfd9 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/calls.ql @@ -0,0 +1,6 @@ +import rust + +from Call c, Function target +where + c.fromSource() and target = c.getStaticTarget() and target.getName().getText().matches("from_%") +select c, target.getCanonicalPath() diff --git a/rust/ql/integration-tests/proc-macro-workspaces/macros/Cargo.toml b/rust/ql/integration-tests/proc-macro-workspaces/macros/Cargo.toml new file mode 100644 index 000000000000..4c7ce9065891 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/macros/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +[package] +name = "macros" +version = "0.1.0" +edition = "2024" + +[lib] +proc-macro = true diff --git a/rust/ql/integration-tests/proc-macro-workspaces/macros/src/lib.rs b/rust/ql/integration-tests/proc-macro-workspaces/macros/src/lib.rs new file mode 100644 index 000000000000..3ad686a8e52b --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/macros/src/lib.rs @@ -0,0 +1,6 @@ +extern crate proc_macro; + +#[proc_macro] +pub fn generate(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + format!("pub fn from_{input}() -> u32 {{ 42 }}").parse().unwrap() +} diff --git a/rust/ql/integration-tests/proc-macro-workspaces/test_proc_macro_workspaces.py b/rust/ql/integration-tests/proc-macro-workspaces/test_proc_macro_workspaces.py new file mode 100644 index 000000000000..6f1a1dc7bfcf --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/test_proc_macro_workspaces.py @@ -0,0 +1,6 @@ +import pytest + + +@pytest.mark.parametrize("threads", [1, 4]) +def test_proc_macro_workspaces(codeql, rust, threads): + codeql.database.create(threads=threads) diff --git a/rust/ql/integration-tests/workspace-with-glob/steps.expected b/rust/ql/integration-tests/workspace-with-glob/steps.expected index 3ea9ee61bed3..4b0e6ed828b6 100644 --- a/rust/ql/integration-tests/workspace-with-glob/steps.expected +++ b/rust/ql/integration-tests/workspace-with-glob/steps.expected @@ -6,7 +6,6 @@ | lib/src/lib.rs:0:0:0:0 | Extract(lib/src/lib.rs) | | lib/src/lib.rs:0:0:0:0 | Parse(lib/src/lib.rs) | | other/Cargo.toml:0:0:0:0 | LoadManifest(other/Cargo.toml) | -| other/Cargo.toml:0:0:0:0 | LoadManifest(other/Cargo.toml) | | other/src/lib.rs:0:0:0:0 | Extract(other/src/lib.rs) | | other/src/lib.rs:0:0:0:0 | LoadSource(other/src/lib.rs) | | other/src/lib.rs:0:0:0:0 | Parse(other/src/lib.rs) |