Skip to main content

source_mesh_core/
backend.rs

1use std::error::Error;
2use std::fmt;
3use std::fs;
4use std::io::ErrorKind;
5use std::path::Path;
6use std::path::PathBuf;
7use std::time::Instant;
8
9use anyhow::Context as _;
10use anyhow::Result;
11use anyhow::ensure;
12use derive_new::new;
13use protobuf::Message as _;
14use serde_json::Map;
15use serde_json::Value;
16
17use crate::analyzer::config::without_test_cfg;
18use crate::analyzer::options::Options as AnalyzerOptions;
19use crate::analyzer::parallel::try_pair;
20use crate::analyzer::prerequisites;
21use crate::analyzer::process::Phase;
22use crate::analyzer::process::ScipProcess;
23use crate::analyzer::repair::IndexRepair;
24use crate::diagnostics::emit;
25use crate::scip::index::ParsedIndex;
26use crate::scip::test_dependencies::mark_test_references;
27
28const NAME_CARGO_MANIFEST: &str = "Cargo.toml";
29const NAME_RUST_PROJECT_FILE: &str = "rust-project.json";
30const MESSAGE_PROJECT_INPUT_ERROR: &str = "Expected a project directory or Cargo.toml";
31const MESSAGE_SCIP_READ_ERROR: &str = "Cannot read SCIP index";
32
33pub trait IndexSource {
34    fn index(&self) -> Result<Vec<u8>>;
35}
36
37#[must_use]
38pub fn contains_project_file(directory: &Path) -> bool {
39    directory.join(NAME_CARGO_MANIFEST).is_file() || directory.join(NAME_RUST_PROJECT_FILE).is_file()
40}
41
42#[derive(new)]
43pub struct RustAnalyzer<'a> {
44    project: &'a Path,
45    configuration_path_original: Option<&'a Path>,
46    options: &'a AnalyzerOptions,
47}
48
49impl IndexSource for RustAnalyzer<'_> {
50    fn index(&self) -> Result<Vec<u8>> {
51        self.index_parsed()?.into_index().write_to_bytes().context("Cannot serialize classified SCIP index")
52    }
53}
54
55impl RustAnalyzer<'_> {
56    pub(crate) fn index_parsed(&self) -> Result<ParsedIndex> {
57        let project = resolve_project_directory(self.project)?;
58        prerequisites::ensure_available(&project)?;
59        let index_directory = tempfile::tempdir().context("Cannot create temporary index directory")?;
60        let index_file_original = index_directory.path().join("original.scip");
61        let index_file_without_test = index_directory.path().join("without_test.scip");
62        let configuration_path_original = self.configuration_path_original.map(dunce::canonicalize).transpose();
63        let configuration_path_original = configuration_path_original.context("Cannot resolve original rust-analyzer config")?;
64        let configuration_original = configuration_path_original.as_ref().map_or_else(
65            || Ok(Value::Object(Map::default())),
66            |path| -> Result<Value> {
67                let contents = fs::read(path).context("Cannot read original rust-analyzer config")?;
68                serde_json::from_slice(&contents).context("Cannot parse original rust-analyzer config")
69            },
70        )?;
71        let configuration_path_without_test = index_directory.path().join("without_test.json");
72        let configuration_without_test = serde_json::to_vec(&without_test_cfg(configuration_original)?)?;
73        let configuration_write_without_test = fs::write(&configuration_path_without_test, configuration_without_test);
74        configuration_write_without_test.context("Cannot write analysis configuration without cfg(test)")?;
75        let analyzer_original = ScipProcess::new(&project, configuration_path_original.as_deref(), self.options);
76        let analyzer_without_test = ScipProcess::new(&project, Some(&configuration_path_without_test), self.options);
77        let indexing_started = Instant::now();
78        emit(format_args!("Analyzing Rust dependencies..."));
79        if self.options.verbose() {
80            emit(format_args!("Indexing original cfg and without cfg(test) in parallel (Cargo may serialize shared builds)..."));
81        }
82        let (index_original, index_without_test) = try_pair(
83            || {
84                let index = analyzer_original.generate_index(&index_file_original, Phase::Original)?;
85                ParsedIndex::parse(&index).context("Cannot decode original dependency index")
86            },
87            || {
88                let index = analyzer_without_test.generate_index(&index_file_without_test, Phase::WithoutTest)?;
89                ParsedIndex::parse_baseline(&index).context("Cannot decode dependency index without cfg(test)")
90            },
91        )?;
92        if self.options.verbose() {
93            emit(format_args!("SCIP processes completed in {:.2}s.", indexing_started.elapsed().as_secs_f64()));
94        }
95        let repair = IndexRepair::new(
96            &project, configuration_path_original.as_deref(), &configuration_path_without_test, self.options,
97        );
98        let (index_original, index_without_test) = repair.perform(index_original, index_without_test)?;
99        if self.options.verbose() {
100            emit(format_args!("Comparing SCIP references to classify test dependencies..."));
101        }
102        let classification_started = Instant::now();
103        let classified = mark_test_references(index_original, index_without_test.as_ref())?;
104        if self.options.verbose() {
105            emit(format_args!("Test classification completed in {:.2}s.", classification_started.elapsed().as_secs_f64()));
106        }
107        emit(format_args!("Dependency analysis completed in {:.2}s.", indexing_started.elapsed().as_secs_f64()));
108        Ok(classified)
109    }
110}
111
112#[derive(Debug)]
113enum ProjectValidationError {
114    InspectPath(PathBuf),
115    UnsupportedFile(PathBuf),
116    ResolveDirectory(PathBuf),
117    ReadManifest(PathBuf),
118    ReadProjectFile { project_file: PathBuf, directory: PathBuf },
119}
120
121impl fmt::Display for ProjectValidationError {
122    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
123        match *self {
124            Self::InspectPath(ref path) => write!(formatter, "Cannot inspect Rust project path {}", path.display()),
125            Self::UnsupportedFile(ref path) => write!(formatter, "{MESSAGE_PROJECT_INPUT_ERROR}: {}", path.display()),
126            Self::ResolveDirectory(ref path) => write!(formatter, "Cannot resolve Rust project directory {}", path.display()),
127            Self::ReadManifest(ref path) => write!(formatter, "Cannot read project manifest {}", path.display()),
128            Self::ReadProjectFile { ref project_file, ref directory } => write!(
129                formatter,
130                "Cannot read project file {} after {NAME_CARGO_MANIFEST} was not found in {}",
131                project_file.display(),
132                directory.display()
133            ),
134        }
135    }
136}
137
138impl Error for ProjectValidationError {}
139
140
141pub fn project_directory(project: &Path) -> Result<PathBuf> {
142    let metadata = fs::metadata(project).with_context(|| ProjectValidationError::InspectPath(project.to_path_buf()))?;
143    let directory = if metadata.is_dir() {
144        project
145    } else {
146        ensure!(
147            project.file_name().is_some_and(|name| name == NAME_CARGO_MANIFEST),
148            ProjectValidationError::UnsupportedFile(project.to_path_buf())
149        );
150        project.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."))
151    };
152    dunce::canonicalize(directory).with_context(|| ProjectValidationError::ResolveDirectory(directory.to_path_buf()))
153}
154
155fn resolve_project_directory(project: &Path) -> Result<PathBuf> {
156    let directory = project_directory(project)?;
157    let manifest = directory.join(NAME_CARGO_MANIFEST);
158    match fs::read(&manifest) {
159        Ok(_) => {}
160        Err(error) if error.kind() == ErrorKind::NotFound => {
161            let project_file = directory.join(NAME_RUST_PROJECT_FILE);
162            fs::read(&project_file).with_context(|| ProjectValidationError::ReadProjectFile {
163                project_file,
164                directory: directory.clone(),
165            })?;
166        }
167        Err(error) => {
168            return Err(error).context(ProjectValidationError::ReadManifest(manifest));
169        }
170    }
171    Ok(directory)
172}
173
174#[derive(new)]
175pub struct ScipFile {
176    path: PathBuf,
177}
178
179impl IndexSource for ScipFile {
180    fn index(&self) -> Result<Vec<u8>> {
181        fs::read(&self.path).with_context(|| format!("{MESSAGE_SCIP_READ_ERROR} {}", self.path.display()))
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use std::collections::BTreeSet;
188    use std::fs;
189    use std::io;
190    use std::path::Path;
191    use std::path::PathBuf;
192
193    use anyhow::Result;
194    use claims::assert_ok;
195    use claims::assert_some;
196    use pretty_assertions::assert_eq;
197    use rstest::rstest;
198    use tempfile::tempdir;
199
200    use super::NAME_CARGO_MANIFEST;
201    use super::IndexSource as _;
202    use super::NAME_RUST_PROJECT_FILE;
203    use super::RustAnalyzer;
204    use super::MESSAGE_SCIP_READ_ERROR;
205    use super::ProjectValidationError;
206    use super::ScipFile;
207    use super::contains_project_file;
208    use super::project_directory;
209    use super::resolve_project_directory;
210    use crate::SourcePath;
211    use crate::analyzer::options::Options;
212    use crate::model::DependencyKind;
213    use crate::model::FileEdge;
214    use crate::model::FileGraph;
215    use crate::model::FileNode;
216    use crate::scip::backend::file_graph;
217    use crate::scip::backend::parse_scip;
218
219    #[rstest]
220    #[case::empty(&[], &[], false)]
221    #[case::cargo(&[NAME_CARGO_MANIFEST], &[], true)]
222    #[case::rust_project(&[NAME_RUST_PROJECT_FILE], &[], true)]
223    #[case::both(&[NAME_CARGO_MANIFEST, NAME_RUST_PROJECT_FILE], &[], true)]
224    #[case::unrelated(&["source.rs"], &[], false)]
225    #[case::directories(&[], &[NAME_CARGO_MANIFEST, NAME_RUST_PROJECT_FILE], false)]
226    #[case::cargo_directory(&[NAME_RUST_PROJECT_FILE], &[NAME_CARGO_MANIFEST], true)]
227    fn test_project_file_detection(#[case] files: &[&str], #[case] directories: &[&str], #[case] expected: bool) {
228        let fixture_creation = tempdir();
229        let fixture = assert_ok!(fixture_creation, "The project-file detection fixture directory must be created");
230        for filename in files {
231            let file_write = fs::write(fixture.path().join(filename), "");
232            assert_ok!(file_write, "The project-file detection fixture must write {filename}");
233        }
234        for directory in directories {
235            let directory_creation = fs::create_dir_all(fixture.path().join(directory));
236            assert_ok!(directory_creation, "The project-file detection fixture must create directory {directory}");
237        }
238
239        let system_under_test = contains_project_file(fixture.path());
240
241        assert_eq!(system_under_test, expected, "Project detection must distinguish supported files from directories");
242    }
243
244    #[rstest]
245    #[case::missing_project(false)]
246    #[case::missing_project_files(true)]
247    fn test_rust_analyzer_index_project_validation(#[case] create_project: bool) {
248        let fixture_creation = tempdir();
249        let fixture = assert_ok!(fixture_creation, "The analyzer project-validation fixture directory must be created");
250        let project = fixture.path().join("project");
251        if create_project {
252            let project_creation = fs::create_dir_all(&project);
253            assert_ok!(project_creation, "The project fixture without project files must be created");
254        }
255        let options = Options::new(false);
256        let system_under_test = RustAnalyzer::new(&project, None, &options);
257
258        let index_generation = system_under_test.index();
259
260        let error = assert_some!(index_generation.err(), "IndexSource::index must reject an invalid project");
261        assert!(
262            error.is::<ProjectValidationError>(),
263            "IndexSource::index must preserve the project-validation error, not a later analyzer failure: {error:#}"
264        );
265        let cause = error.downcast_ref::<io::Error>();
266        let cause = assert_some!(cause, "IndexSource::index must retain the project filesystem error");
267        assert_eq!(cause.kind(), io::ErrorKind::NotFound, "IndexSource::index must reject a missing project or project file");
268    }
269
270    #[rstest]
271    #[case::binary(&[0, 1, 255, 128, 13, 10, 42])]
272    #[case::empty(&[])]
273    fn test_scip_file_bytes(#[case] bytes: &[u8]) {
274        let fixture_creation = tempdir();
275        let fixture = assert_ok!(fixture_creation, "The SCIP byte-preservation fixture directory must be created");
276        let path = fixture.path().join("input.scip");
277        let index_write = fs::write(&path, bytes);
278        assert_ok!(index_write, "The SCIP fixture bytes must be written before reading the index");
279        let system_under_test = ScipFile::new(path);
280
281        let index_read = system_under_test.index();
282        let index = assert_ok!(index_read, "The file adapter must read the SCIP fixture bytes");
283
284        assert_eq!(index, bytes, "The file adapter must preserve bytes without decoding or rewriting them");
285    }
286
287    #[rstest]
288    #[case::missing(false)]
289    #[case::directory(true)]
290    fn test_scip_file_read_failure(#[case] unreadable_directory: bool) {
291        let fixture_creation = tempdir();
292        let fixture = assert_ok!(fixture_creation, "The SCIP read-failure fixture directory must be created");
293        let path = fixture.path().join("input.scip");
294        if unreadable_directory {
295            let directory_creation = fs::create_dir_all(&path);
296            assert_ok!(directory_creation, "The unreadable SCIP fixture must contain a directory at the index path");
297        }
298        let expected_message = format!("{MESSAGE_SCIP_READ_ERROR} {}", path.display());
299        let system_under_test = ScipFile::new(path);
300
301        let index_read = system_under_test.index();
302
303        let error = index_read.as_ref().err();
304        let error = assert_some!(error, "A missing SCIP file or directory at the index path must fail to read");
305        assert_eq!(error.to_string(), expected_message, "SCIP read errors must identify the requested index path");
306        let cause = error.downcast_ref::<io::Error>();
307        let cause = assert_some!(cause, "SCIP read errors must retain their filesystem cause");
308        assert_eq!(cause.kind() == io::ErrorKind::NotFound, !unreadable_directory, "Missing and unreadable indexes must differ");
309    }
310
311    #[rstest]
312    #[case::directory(false)]
313    #[case::manifest(true)]
314    fn test_project_directory_selection(
315        #[case] manifest_input: bool,
316        #[values(project_directory, resolve_project_directory)] resolve: fn(&Path) -> Result<PathBuf>,
317    ) {
318        let (system_under_test, expected) = {
319            let fixture_creation = tempdir();
320            let fixture = assert_ok!(fixture_creation, "The project-directory selection fixture must be created");
321            let manifest = fixture.path().join(NAME_CARGO_MANIFEST);
322            let manifest_write = fs::write(&manifest, "");
323            assert_ok!(manifest_write, "The project-directory selection fixture must contain a Cargo manifest");
324            let project = if manifest_input { &manifest } else { fixture.path() };
325            let project_resolution = resolve(project);
326            let directory = assert_ok!(project_resolution, "A project directory or its manifest must resolve successfully");
327            let fixture_resolution = dunce::canonicalize(fixture.path());
328            let expected = assert_ok!(fixture_resolution, "The selected project fixture must have a canonical path");
329            (directory, expected)
330        };
331
332        assert_eq!(system_under_test, expected, "Project input must select its canonical directory");
333    }
334
335    #[rstest]
336    #[case::missing(None)]
337    #[case::unreadable_manifest(Some(NAME_CARGO_MANIFEST))]
338    #[case::unreadable_project_file(Some(NAME_RUST_PROJECT_FILE))]
339    fn test_project_directory_without_project_files(#[case] unreadable_file: Option<&str>) {
340        let fixture = tempdir();
341        let fixture = assert_ok!(fixture, "Project-directory discovery fixture must be created");
342        if let Some(filename) = unreadable_file {
343            let created = fs::create_dir_all(fixture.path().join(filename));
344            assert_ok!(created, "Discovery fixture must contain an unreadable project file at {filename}");
345        }
346        let expected = dunce::canonicalize(fixture.path());
347        let expected = assert_ok!(expected, "Discovery fixture must have a canonical directory");
348
349        let system_under_test = project_directory(&fixture.path().join("."));
350        let system_under_test = assert_ok!(system_under_test, "Directory discovery must not require readable project files");
351
352        assert_eq!(expected, system_under_test, "Configuration discovery must resolve the selected directory canonically");
353    }
354
355    #[rstest]
356    fn test_project_path_io_error(
357        #[values(project_directory, resolve_project_directory)] resolve: fn(&Path) -> Result<PathBuf>,
358    ) {
359        let system_under_test = {
360            let fixture_creation = tempdir();
361            let fixture = assert_ok!(fixture_creation, "The missing-project-path fixture directory must be created");
362            resolve(&fixture.path().join("missing"))
363        };
364
365        assert!(
366            system_under_test.is_err_and(|error| {
367                error.downcast_ref::<io::Error>().is_some_and(|cause| cause.kind() == io::ErrorKind::NotFound)
368            }),
369            "Missing project path lost its filesystem error"
370        );
371    }
372
373    #[test]
374    fn test_rust_project_file() {
375        let (system_under_test, expected) = {
376            let fixture_creation = tempdir();
377            let fixture = assert_ok!(fixture_creation, "The rust-project.json fixture directory must be created");
378            let project_file_write = fs::write(fixture.path().join(NAME_RUST_PROJECT_FILE), "{}");
379            assert_ok!(project_file_write, "The rust-project.json fixture must be written before project resolution");
380            let project_resolution = resolve_project_directory(fixture.path());
381            let directory = assert_ok!(project_resolution, "A rust-project.json project must resolve without a manifest");
382            let fixture_resolution = dunce::canonicalize(fixture.path());
383            let expected = assert_ok!(fixture_resolution, "The rust-project.json fixture must have a canonical path");
384            (directory, expected)
385        };
386
387        assert_eq!(system_under_test, expected, "A rust-project.json project must select its canonical directory");
388    }
389
390    #[rstest]
391    #[case::manifest(NAME_CARGO_MANIFEST)]
392    #[case::rust_project(NAME_RUST_PROJECT_FILE)]
393    fn test_project_file_read_error(#[case] filename: &str) {
394        let system_under_test = {
395            let fixture_creation = tempdir();
396            let fixture = assert_ok!(fixture_creation, "The unreadable project-file fixture directory must be created");
397            let directory_creation = fs::create_dir_all(fixture.path().join(filename));
398            assert_ok!(directory_creation, "The project fixture must contain a directory at the {filename} file path");
399            resolve_project_directory(fixture.path())
400        };
401
402        assert!(
403            system_under_test.is_err_and(|error| {
404                error.downcast_ref::<io::Error>().is_some_and(|cause| cause.kind() != io::ErrorKind::NotFound)
405            }),
406            "An unreadable project file was reported as a missing file"
407        );
408    }
409
410    #[test]
411    fn test_missing_project_files() {
412        let system_under_test = {
413            let fixture_creation = tempdir();
414            let fixture = assert_ok!(fixture_creation, "The project fixture without project files must be created");
415            resolve_project_directory(fixture.path())
416        };
417
418        assert!(
419            system_under_test.is_err_and(|error| {
420                error.downcast_ref::<io::Error>().is_some_and(|cause| cause.kind() == io::ErrorKind::NotFound)
421            }),
422            "A directory without project files lost its missing-file error"
423        );
424    }
425
426    #[rstest]
427    fn test_non_manifest_project_file(
428        #[values(project_directory, resolve_project_directory)] resolve: fn(&Path) -> Result<PathBuf>,
429    ) {
430        let fixture_creation = tempdir();
431        let fixture = assert_ok!(fixture_creation, "The non-manifest project-file fixture directory must be created");
432        let project = fixture.path().join("source.rs");
433        let source_write = fs::write(&project, "");
434        assert_ok!(source_write, "The non-manifest source file must exist before project resolution");
435
436        let system_under_test = resolve(&project);
437
438        let error = assert_some!(system_under_test.err(), "A non-manifest project file must be rejected");
439        let validation_error = error.downcast_ref::<ProjectValidationError>();
440        let validation_error = assert_some!(validation_error, "Project validation must retain its failure context: {error:#}");
441        assert!(
442            matches!(*validation_error, ProjectValidationError::UnsupportedFile(ref path) if path == &project),
443            "Project validation must reject the supplied file as unsupported, not fail for an unrelated reason: {error:#}"
444        );
445    }
446
447    #[must_use]
448    fn analyzer_fixture() -> (PathBuf, Options) {
449        (PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src").join("fixtures"), Options::new(false))
450    }
451
452    #[test]
453    #[ignore = "slow multi-pass rust-analyzer indexing; excluded to keep default tests fast; \
454                run scripts/Test-All.ps1 from the repository root"]
455    fn test_rust_analyzer_generated_method_dependencies() {
456        let (fixture, options) = analyzer_fixture();
457        let project = fixture.join("generated-methods");
458        let source_directory = Path::new("src");
459        let client_path_result = SourcePath::new(source_directory.join("client.rs"));
460        let client_path = assert_ok!(client_path_result, "Failed to create the generated-method caller source path");
461        let client = FileNode::new(client_path);
462        let factory_path_result = SourcePath::new(source_directory.join("factory.rs"));
463        let factory_path = assert_ok!(factory_path_result, "Failed to create the generated-method factory source path");
464        let factory = FileNode::new(factory_path);
465        let model_path_result = SourcePath::new(source_directory.join("model.rs"));
466        let model_path = assert_ok!(model_path_result, "Failed to create the generated-method model source path");
467        let model = FileNode::new(model_path);
468        let validation_path_result = SourcePath::new(source_directory.join("validation.rs"));
469        let validation_path = assert_ok!(validation_path_result, "Failed to create the generated-method test caller path");
470        let validation = FileNode::new(validation_path);
471        let comparison_path_result = SourcePath::new(source_directory.join("comparison.rs"));
472        let comparison_path = assert_ok!(comparison_path_result, "Failed to create the generated comparison caller path");
473        let comparison = FileNode::new(comparison_path);
474        let expected = BTreeSet::from([
475            FileEdge::new(comparison.clone(), factory.clone(), DependencyKind::Production),
476            FileEdge::new(comparison, model.clone(), DependencyKind::Production),
477            FileEdge::new(client.clone(), factory.clone(), DependencyKind::Production),
478            FileEdge::new(client, model.clone(), DependencyKind::Production),
479            FileEdge::new(factory.clone(), model.clone(), DependencyKind::Production),
480            FileEdge::new(validation.clone(), factory, DependencyKind::Test),
481            FileEdge::new(validation, model, DependencyKind::Test),
482        ]);
483        let system_under_test = RustAnalyzer::new(&project, None, &options);
484
485        let index_generation = system_under_test.index_parsed();
486        let index = assert_ok!(index_generation, "Failed to index the generated-method fixture with rust-analyzer");
487        let graph_build = file_graph(&index);
488        let graph = assert_ok!(graph_build, "Failed to build the generated-method file dependency graph");
489
490        assert_eq!(
491            graph.edges(),
492            &expected,
493            "Generated-call and comparison dependency edges differ from the expected set"
494        );
495    }
496
497    #[test]
498    #[ignore = "slow multi-pass rust-analyzer indexing; excluded to keep default tests fast; \
499                run scripts/Test-All.ps1 from the repository root"]
500    fn test_rust_analyzer_cargo_target_collisions() {
501        let (fixture, options) = analyzer_fixture();
502        let project = fixture.join("cargo-targets");
503        let library_path_result = SourcePath::new(Path::new("src").join("library.rs"));
504        let library_path = assert_ok!(library_path_result, "The shared Cargo library must have a valid source path");
505        let library = FileNode::new(library_path);
506        let first_binary_path_result = SourcePath::new(Path::new("src").join("bin").join("first.rs"));
507        let first_binary_path = assert_ok!(first_binary_path_result, "The first Cargo binary path must be valid");
508        let second_binary_path_result = SourcePath::new(Path::new("src").join("bin").join("second.rs"));
509        let second_binary_path = assert_ok!(second_binary_path_result, "The second Cargo binary path must be valid");
510        let expected = BTreeSet::from([
511            FileEdge::new(FileNode::new(first_binary_path), library.clone(), DependencyKind::Production),
512            FileEdge::new(FileNode::new(second_binary_path), library, DependencyKind::Production),
513        ]);
514        let system_under_test = RustAnalyzer::new(&project, None, &options);
515
516        let index_generation = system_under_test.index_parsed();
517        let index = assert_ok!(index_generation, "rust-analyzer must index the colliding Cargo targets");
518        let graph_build = file_graph(&index);
519        let graph = assert_ok!(graph_build, "The Cargo-target index must produce a file dependency graph");
520
521        assert_eq!(
522            graph.edges(),
523            &expected,
524            "Cargo target collisions must not create links between binaries or hide library calls"
525        );
526    }
527    #[test]
528    #[ignore = "slow multi-pass rust-analyzer indexing; excluded to keep default tests fast; \
529                run scripts/Test-All.ps1 from the repository root"]
530    fn test_rust_analyzer_manifest_file_graph() {
531        let (fixture, options) = analyzer_fixture();
532        let manifest = fixture.join("dependency-graph").join(NAME_CARGO_MANIFEST);
533        let expected = {
534            let fixture_read = ScipFile::new(fixture.join("dependency-graph.scip")).index();
535            let expected_index = assert_ok!(fixture_read, "The checked-in dependency-graph SCIP fixture must be readable");
536            let fixture_parse = parse_scip(&expected_index);
537            assert_ok!(fixture_parse, "The checked-in SCIP fixture must produce the expected dependency graph")
538        };
539        let system_under_test = RustAnalyzer::new(&manifest, None, &options);
540
541        let index_generation = system_under_test.index();
542        let index = assert_ok!(index_generation, "rust-analyzer must index a project selected by its Cargo manifest");
543        let index_parse = parse_scip(&index);
544        let graph = assert_ok!(index_parse, "The analyzer index bytes must parse into a file dependency graph");
545
546        assert_eq!(graph.files(), expected.files(), "rust-analyzer indexing changed fixture files");
547        assert_eq!(graph.edges(), expected.edges(), "rust-analyzer indexing changed fixture dependencies");
548    }
549
550    #[test]
551    #[ignore = "slow multi-pass rust-analyzer indexing; excluded to keep default tests fast; \
552                run scripts/Test-All.ps1 from the repository root"]
553    fn test_rust_analyzer_test_configuration_classification() {
554        let (fixture, options) = analyzer_fixture();
555        let manifest = fixture.join("test-dependencies").join(NAME_CARGO_MANIFEST);
556        let source_directory = Path::new("src");
557        let module_file = "mod.rs";
558        let client_path_result = SourcePath::new(source_directory.join("client").join("calls.rs"));
559        let client_path = assert_ok!(client_path_result, "The classified fixture caller must have a valid source path");
560        let client = FileNode::new(client_path);
561        let shared_path_result = SourcePath::new(source_directory.join("shared").join("value.rs"));
562        let shared_path = assert_ok!(shared_path_result, "The classified fixture shared value must have a valid path");
563        let shared = FileNode::new(shared_path);
564        let test_only_path_result = SourcePath::new(source_directory.join("test_only").join("value.rs"));
565        let test_only_path = assert_ok!(test_only_path_result, "The classified fixture test-only value path must be valid");
566        let test_only = FileNode::new(test_only_path);
567        let validation_path_result = SourcePath::new(source_directory.join("validation").join("checks.rs"));
568        let validation_path = assert_ok!(validation_path_result, "The classified fixture validation path must be valid");
569        let validation = FileNode::new(validation_path);
570        let library_path_result = SourcePath::new(source_directory.join("lib.rs"));
571        let library = assert_ok!(library_path_result, "The classified fixture library must have a valid source path");
572        let client_module_result = SourcePath::new(source_directory.join("client").join(module_file));
573        let client_module = assert_ok!(client_module_result, "The classified fixture client module path must be valid");
574        let shared_module_result = SourcePath::new(source_directory.join("shared").join(module_file));
575        let shared_module = assert_ok!(shared_module_result, "The classified fixture shared module path must be valid");
576        let test_only_module_result = SourcePath::new(source_directory.join("test_only").join(module_file));
577        let test_only_module = assert_ok!(test_only_module_result, "The classified fixture test-only module path must be valid");
578        let expected_graph_build = FileGraph::new(
579            BTreeSet::from([
580                FileNode::new(library),
581                FileNode::new(client_module),
582                FileNode::new(shared_module),
583                FileNode::new(test_only_module),
584                client.clone(),
585                shared.clone(),
586                test_only.clone(),
587                validation.clone(),
588            ]),
589            BTreeSet::from([
590                FileEdge::new(client.clone(), shared.clone(), DependencyKind::Production),
591                FileEdge::new(client.clone(), shared, DependencyKind::Test),
592                FileEdge::new(client, test_only.clone(), DependencyKind::Test),
593                FileEdge::new(validation, test_only, DependencyKind::Test),
594            ]),
595        );
596        let expected = assert_ok!(expected_graph_build, "Expected classified dependencies must form a valid file graph");
597        let system_under_test = RustAnalyzer::new(&manifest, None, &options);
598
599        let index_generation = system_under_test.index_parsed();
600        let index = assert_ok!(index_generation, "rust-analyzer must index the test-configuration fixture");
601        let graph_build = file_graph(&index);
602        let graph = assert_ok!(graph_build, "The classified analyzer index must produce a file dependency graph");
603
604        assert_eq!(graph.files(), expected.files(), "rust-analyzer analysis changed classified fixture files");
605        assert_eq!(graph.edges(), expected.edges(), "rust-analyzer analysis changed classified fixture dependencies");
606    }
607}