Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 29 additions & 33 deletions rust/extractor/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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;
Expand All @@ -38,6 +38,7 @@ mod toolchain;
mod translate;
pub mod trap;
mod util;
mod workspaces;

struct Extractor<'a> {
archiver: &'a Archiver,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)| {
Expand All @@ -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 {
Expand All @@ -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) {
Comment thread
redsun82 marked this conversation as resolved.
Resolved
// `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
Expand All @@ -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)| {
Expand Down Expand Up @@ -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"))?;
Expand Down
2 changes: 1 addition & 1 deletion rust/extractor/src/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
247 changes: 247 additions & 0 deletions rust/extractor/src/workspaces.rs
Original file line number Diff line number Diff line change
@@ -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<W> = (Option<W>, 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<Loaded<W>>)>,
load: Arc<L>,
prefetch: bool,
}

impl<'m, W, L> LoadedWorkspaces<'m, W, L>
where
W: Send + 'static,
L: Fn(&ProjectManifest) -> Option<W> + 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<ExtractionStep>,
) -> 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<ExtractionStep>,
) -> Option<Loaded<W>> {
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))
Comment thread
redsun82 marked this conversation as resolved.
Resolved
{
Ok(handle) => self.prefetched = Some((next, handle)),
// `next` is then loaded when requested
Err(e) => warn!("cannot load {next} in the background: {e}"),
}
}
}

impl<W, L> 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()
Comment thread
redsun82 marked this conversation as resolved.
Resolved
{
error!("loading {manifest} in the background panicked");
}
}
}

fn load_timed<W>(
load: &impl Fn(&ProjectManifest) -> Option<W>,
manifest: &ProjectManifest,
) -> Loaded<W> {
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<Vec<String>>,
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<Receiver<()>>,
}

struct Workspace(Arc<Stats>);

impl Drop for Workspace {
fn drop(&mut self) {
self.0.live.fetch_sub(1, Ordering::SeqCst);
}
}

fn stats() -> (Arc<Stats>, 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<const N: usize>(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<Stats>) -> impl Fn(&ProjectManifest) -> Option<Workspace> + 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();
}
}
Loading
Loading