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
1 change: 1 addition & 0 deletions rust/extractor/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ impl Display for HumanReadableDuration {
#[derive(Debug, Default, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct DurationsSummary {
/// Summed over all extraction threads, so with more than one thread these may exceed `total`.
#[serde(flatten)]
durations: HashMap<ExtractionStepKind, HumanReadableDuration>,
total: HumanReadableDuration,
Expand Down
248 changes: 189 additions & 59 deletions rust/extractor/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::trap::TrapId;
use anyhow::Context;
use archive::Archiver;
use configuration::{DependencyFiles, dependency_files, manifest_parent};
use itertools::Itertools;
use ra_ap_hir::Semantics;
use ra_ap_ide_db::RootDatabase;
use ra_ap_ide_db::line_index::{LineCol, LineIndex};
Expand All @@ -30,6 +31,7 @@ mod configuration;
mod crate_graph;
mod diagnostics;
pub mod generated;
mod parallel;
mod qltest;
mod rust_analyzer;
mod toolchain;
Expand Down Expand Up @@ -194,22 +196,78 @@ impl<'a> Extractor<'a> {
Ok(())
}

/// Runs `work` on `items` using up to `threads` workers, each with its own `Extractor` and
/// `Semantics` over a clone of `db` (sharing its query storage). Returns results in item order.
fn run_parallel<T: Sync, R: Send>(
&mut self,
db: &RootDatabase,
vfs: &Vfs,
threads: usize,
items: &[T],
work: impl for<'s> Fn(&mut Extractor<'a>, &'s Semantics<'s, RootDatabase>, &'s Vfs, &T) -> R
+ Sync,
) -> Vec<R> {
let (archiver, traps) = (self.archiver, self.traps);
let (steps, results) = parallel::parallel_map(
threads,
items,
|| db.clone(),
|db, drive| {
let semantics = Semantics::new(&db);
let mut extractor = Extractor::new(archiver, traps);
drive(&mut |item| work(&mut extractor, &semantics, vfs, item));
extractor.steps
},
);
self.steps.extend(steps.into_iter().flatten());
results
}

/// Runs `extract_without_semantics` on `files` using up to `threads` workers.
fn extract_without_semantics_parallel<P: AsRef<Path> + Sync>(
&mut self,
threads: usize,
files: &[P],
source_kind: SourceKind,
err: &RustAnalyzerNoSemantics,
) {
let (archiver, traps) = (self.archiver, self.traps);
let (steps, _) = parallel::parallel_map(
threads,
files,
|| (),
|(), drive| {
let mut extractor = Extractor::new(archiver, traps);
drive(&mut |file| {
extractor.extract_without_semantics(file.as_ref(), source_kind, err.clone());
});
extractor.steps
},
);
self.steps.extend(steps.into_iter().flatten());
}

pub fn find_manifests(&mut self, files: &[PathBuf]) -> anyhow::Result<Vec<ProjectManifest>> {
let before = Instant::now();
let ret = rust_analyzer::find_project_manifests(files);
self.steps.push(ExtractionStep::find_manifests(before));
ret
}

/// Groups `files` by workspace, also returning the files that belong to none.
#[allow(clippy::type_complexity)]
fn group_files<'b>(
&mut self,
manifests: &'b [ProjectManifest],
files: &'b [PathBuf],
) -> BTreeMap<&'b Path, (&'b ProjectManifest, Vec<&'b Path>)> {
) -> (
BTreeMap<&'b Path, (&'b ProjectManifest, Vec<&'b Path>)>,
Vec<&'b Path>,
) {
let mut workspaces: BTreeMap<&Path, (&ProjectManifest, Vec<&Path>)> = manifests
.iter()
.map(|manifest| (manifest_parent(manifest), (manifest, Vec::new())))
.collect();
let mut unmanaged = Vec::new();

'outer: for file in files {
for ancestor in file.as_path().ancestors() {
Expand All @@ -218,15 +276,11 @@ impl<'a> Extractor<'a> {
continue 'outer;
}
}
self.extract_without_semantics(
file,
SourceKind::Source,
RustAnalyzerNoSemantics::warning("no manifest found"),
);
unmanaged.push(file.as_path());
}

workspaces.retain(|_, (_, files)| !files.is_empty());
workspaces
(workspaces, unmanaged)
}
}

Expand All @@ -239,6 +293,22 @@ fn cwd() -> anyhow::Result<AbsPathBuf> {
Ok(abs_path)
}

/// Canonicalizes `inputs`, dropping repeated files.
fn canonical_files(inputs: &[PathBuf]) -> Vec<PathBuf> {
inputs
.iter()
.map(|file| {
let file = std::path::absolute(file).unwrap_or_else(|_| file.clone());
// On Windows, rust analyzer expects non-`//?/` prefixed paths (see [1]), which is what
// `std::fs::canonicalize` returns. So we use `dunce::canonicalize` instead.
// [1]: https://github.com/rust-lang/rust-analyzer/issues/18894#issuecomment-2580014730
dunce::canonicalize(&file).unwrap_or(file)
})
// each file must be extracted at most once at a time, as trap and archive writes are not atomic
.unique()
.collect()
}

#[allow(clippy::too_many_lines)]
fn main() -> anyhow::Result<()> {
let start = Instant::now();
Expand Down Expand Up @@ -279,18 +349,9 @@ fn main() -> anyhow::Result<()> {
root: config.source_archive_dir.clone(),
};
let mut extractor = Extractor::new(&archiver, &traps);
let files = inputs
.iter()
.map(|file| {
let file = std::path::absolute(file).unwrap_or_else(|_| file.clone());
// On Windows, rust analyzer expects non-`//?/` prefixed paths (see [1]), which is what
// `std::fs::canonicalize` returns. So we use `dunce::canonicalize` instead.
// [1]: https://github.com/rust-lang/rust-analyzer/issues/18894#issuecomment-2580014730
dunce::canonicalize(&file).unwrap_or(file)
})
.collect::<Vec<_>>();
let files = canonical_files(&inputs);
let manifests = extractor.find_manifests(&files)?;
let workspaces = extractor.group_files(&manifests, &files);
let (workspaces, unmanaged) = Extractor::group_files(&manifests, &files);
let cwd = cwd()?;
log_project_toolchain();
let (cargo_config, load_cargo_config) = config.to_cargo_config(&cwd);
Expand All @@ -305,6 +366,14 @@ fn main() -> anyhow::Result<()> {
SourceKind::Source
};
let source_files = HashSet::from_iter(files.iter().cloned());
let threads = parallel::extraction_threads();
info!("extraction threads: {threads}");
extractor.extract_without_semantics_parallel(
threads,
&unmanaged,
SourceKind::Source,
&RustAnalyzerNoSemantics::warning("no manifest found"),
);

let mut dependencies = DependencyFiles::default();

Expand All @@ -321,29 +390,41 @@ fn main() -> anyhow::Result<()> {
extractor
.steps
.push(ExtractionStep::crate_graph(before_crate_graph));
let semantics = Semantics::new(&db);
for file in files {
match extractor.load_source(file, &semantics, &vfs) {
Ok(()) => extractor.extract_with_semantics(file, &semantics, &vfs, source_mode),
Err(e) => extractor.extract_without_semantics(file, source_mode, e),
}
}
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 {
for (_, file) in dependency_files(&db, &vfs, &source_files) {
extractor.extract_with_semantics(file, &semantics, &vfs, library_mode);
}
} else {
items.extend(dependency_files(&db, &vfs, &source_files).map(|(_, f)| (f, false)));
}
debug_assert!(items.iter().map(|(f, _)| f).all_unique());
extractor.run_parallel(
Comment thread
redsun82 marked this conversation as resolved.
Resolved
&db,
&vfs,
threads,
&items,
|extractor, semantics, vfs, &(file, is_source)| {
if !is_source {
extractor.extract_with_semantics(file, semantics, vfs, library_mode);
return;
}
match extractor.load_source(file, semantics, vfs) {
Ok(()) => {
extractor.extract_with_semantics(file, semantics, vfs, source_mode);
}
Err(e) => extractor.extract_without_semantics(file, source_mode, e),
}
},
);
if !dependency_extraction_ambiguity {
let semantics = Semantics::new(&db);
dependencies.add_manifest(manifest, &semantics, &vfs, &source_files);
}
} else {
for file in files {
extractor.extract_without_semantics(
file,
SourceKind::Source,
RustAnalyzerNoSemantics::warning("unable to load manifest"),
);
}
extractor.extract_without_semantics_parallel(
threads,
files,
SourceKind::Source,
&RustAnalyzerNoSemantics::warning("unable to load manifest"),
);
}
}

Expand All @@ -359,31 +440,52 @@ fn main() -> anyhow::Result<()> {
if let Some((db, vfs)) =
extractor.load_manifest(manifest, &cargo_config, &load_cargo_config)
{
let semantics = Semantics::new(&db);
for file in files {
// A richer configuration can disable a file when using cfg
// options like `#[cfg(not(feature = "foo"))]`. When this is
// the case `file_to_module_def` will return `None` for the
// file. When this is the case and there are alternatives we
// do not extract the file yet. Instead the file will be
// considered again in the next iteration of the loop.
if !dependencies.has_alternative(&file)
|| path_to_file_id(&file, &vfs)
.and_then(|id| semantics.file_to_module_def(id))
.is_some()
{
extractor.extract_with_semantics(&file, &semantics, &vfs, library_mode);
dependencies.extracted(&file);
// `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
.into_iter()
.map(|file| {
let has_alternative = dependencies.has_alternative(&file);
(file, has_alternative)
})
.collect();
debug_assert!(items.iter().map(|(f, _)| f).all_unique());
let extracted = extractor.run_parallel(
&db,
&vfs,
threads,
&items,
|extractor, semantics, vfs, (file, has_alternative)| {
// A richer configuration can disable a file when using cfg
// options like `#[cfg(not(feature = "foo"))]`. When this is
// the case `file_to_module_def` will return `None` for the
// file. When this is the case and there are alternatives we
// do not extract the file yet. Instead the file will be
// considered again in the next iteration of the loop.
let extract = !has_alternative
|| path_to_file_id(file, vfs)
.and_then(|id| semantics.file_to_module_def(id))
.is_some();
if extract {
extractor.extract_with_semantics(file, semantics, vfs, library_mode);
}
extract
},
);
for ((file, _), extracted) in items.iter().zip(extracted) {
if extracted {
dependencies.extracted(file);
}
}
} else {
for file in files {
extractor.extract_without_semantics(
&file,
library_mode,
RustAnalyzerNoSemantics::warning("unable to reload manifest"),
);
dependencies.extracted(&file);
extractor.extract_without_semantics_parallel(
threads,
&files,
library_mode,
&RustAnalyzerNoSemantics::warning("unable to reload manifest"),
);
for file in &files {
dependencies.extracted(file);
}
}
}
Expand All @@ -406,3 +508,31 @@ fn main() -> anyhow::Result<()> {

extractor.emit_extraction_diagnostics(start, &config)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn canonical_files_drops_repeated_and_aliased_inputs() {
let dir = env::temp_dir().join(format!(
"codeql-rust-canonical-files-{}",
std::process::id()
));
fs::create_dir_all(dir.join("sub")).unwrap();
let file = dir.join("a.rs");
fs::write(&file, "").unwrap();
let missing = dir.join("missing.rs");
let files = canonical_files(&[
file.clone(),
dir.join("sub").join("..").join("a.rs"),
dir.join(".").join("a.rs"),
file,
missing.clone(),
missing,
]);
fs::remove_dir_all(&dir).unwrap();
assert_eq!(files.len(), 2, "{files:?}");
assert!(files[0].ends_with("a.rs") && files[1].ends_with("missing.rs"));
}
}
Loading
Loading