1use std::fs;
2use std::path::Path;
3use std::path::PathBuf;
4use std::thread;
5use std::time::Instant;
6
7use anyhow::Context as _;
8use anyhow::Result;
9use anyhow::anyhow;
10use anyhow::ensure;
11use derive_new::new;
12use serde_json::Map;
13use serde_json::Value;
14
15use crate::analyzer_config::without_test_cfg;
16use crate::analyzer_options::Options as AnalyzerOptions;
17use crate::analyzer_prerequisites;
18use crate::analyzer_process::Phase;
19use crate::analyzer_process::ScipProcess;
20use crate::scip_repair::IndexRepair;
21use crate::test_dependencies::mark_test_references;
22
23pub trait IndexSource {
24 fn index(&self) -> Result<Vec<u8>>;
25}
26
27#[must_use]
28pub fn contains_project_file(directory: &Path) -> bool {
29 directory.join("Cargo.toml").is_file() || directory.join("rust-project.json").is_file()
30}
31
32#[derive(new)]
33pub struct RustAnalyzer<'a> {
34 project: &'a Path,
35 configuration_path: Option<&'a Path>,
36 options: &'a AnalyzerOptions,
37}
38
39impl IndexSource for RustAnalyzer<'_> {
40 fn index(&self) -> Result<Vec<u8>> {
41 let project = if self.project.is_file() {
42 ensure!(
43 self.project
44 .file_name()
45 .is_some_and(|name| name == "Cargo.toml"),
46 "Expected a project directory or Cargo.toml"
47 );
48 self.project
49 .parent()
50 .filter(|parent| !parent.as_os_str().is_empty())
51 .unwrap_or_else(|| Path::new("."))
52 } else {
53 self.project
54 };
55 let project =
56 dunce::canonicalize(project).context("Cannot resolve Rust project directory")?;
57 ensure!(
58 contains_project_file(&project),
59 "No Cargo.toml or rust-project.json in {}",
60 project.display()
61 );
62 analyzer_prerequisites::ensure_available(&project)?;
63 let index_directory =
64 tempfile::tempdir().context("Cannot create temporary index directory")?;
65 let index_file = index_directory.path().join("index.scip");
66 let production_index_file = index_directory.path().join("production.scip");
67 let configuration_path = self
68 .configuration_path
69 .map(dunce::canonicalize)
70 .transpose()
71 .context("Cannot resolve rust-analyzer config")?;
72 let configuration = configuration_path.as_ref().map_or_else(
73 || Ok(Value::Object(Map::default())),
74 |path| -> Result<Value> {
75 serde_json::from_slice(
76 &fs::read(path).context("Cannot read rust-analyzer config")?,
77 ).context("Cannot parse rust-analyzer config")
78 },
79 )?;
80 let production_configuration_path = index_directory.path().join("production.json");
81 fs::write(
82 &production_configuration_path,
83 serde_json::to_vec(&without_test_cfg(configuration)?)?,
84 ).context("Cannot write non-test analysis configuration")?;
85 let configured_analyzer =
86 ScipProcess::new(&project, configuration_path.as_deref(), self.options);
87 let production_analyzer =
88 ScipProcess::new(&project, Some(&production_configuration_path), self.options);
89 let indexing_started = Instant::now();
90 eprintln!("Analyzing Rust dependencies...");
91 if self.options.verbose() {
92 eprintln!("Indexing configured and non-test cfg in parallel (Cargo may serialize shared build work)...");
93 }
94 let (configured_result, production_result) = thread::scope(|scope| {
95 let configured_pass =
96 scope.spawn(|| configured_analyzer.generate_index(&index_file, Phase::Configured));
97 let production_pass =
98 scope.spawn(|| production_analyzer.generate_index(&production_index_file, Phase::Production));
99 (configured_pass.join(), production_pass.join())
100 });
101 let index_bytes = configured_result.map_err(|_| anyhow!("Configured SCIP pass panicked"))??;
102 let production_bytes = production_result.map_err(|_| anyhow!("Non-test SCIP pass panicked"))??;
103 if self.options.verbose() {
104 eprintln!("SCIP processes completed in {:.2}s.", indexing_started.elapsed().as_secs_f64());
105 }
106 let (index_bytes, production_bytes) = IndexRepair::new(
107 &project,
108 configuration_path.as_deref(),
109 &production_configuration_path,
110 self.options,
111 ).repair(index_bytes, production_bytes)?;
112 if self.options.verbose() {
113 eprintln!("Comparing SCIP references to classify test dependencies...");
114 }
115 let classification_started = Instant::now();
116 let classified = mark_test_references(&index_bytes, &production_bytes)?;
117 if self.options.verbose() {
118 eprintln!("Test classification completed in {:.2}s.", classification_started.elapsed().as_secs_f64());
119 }
120 eprintln!("Dependency analysis completed in {:.2}s.", indexing_started.elapsed().as_secs_f64());
121 Ok(classified)
122 }
123}
124
125#[derive(new)]
126pub struct ScipFile {
127 path: PathBuf,
128}
129
130impl IndexSource for ScipFile {
131 fn index(&self) -> Result<Vec<u8>> {
132 fs::read(&self.path)
133 .with_context(|| format!("Cannot read SCIP index {}", self.path.display()))
134 }
135}
136
137#[cfg(test)]
138mod tests {
139 use std::collections::BTreeSet;
140 use std::path::Path;
141 use std::path::PathBuf;
142
143 use anyhow::Result;
144 use pretty_assertions::assert_eq;
145
146 use super::IndexSource as _;
147 use super::RustAnalyzer;
148 use super::ScipFile;
149 use crate::analyzer_options::Options;
150 use crate::model::DependencyKind;
151 use crate::model::FileEdge;
152 use crate::model::FileGraph;
153 use crate::model::FileNode;
154 use crate::scip_backend::parse_scip;
155
156 #[must_use]
157 fn analyzer_fixture() -> (PathBuf, Options) {
158 (
159 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
160 .join("src")
161 .join("fixtures"),
162 Options::new(false),
163 )
164 }
165
166 #[test]
167 #[ignore = "slow multi-pass rust-analyzer indexing; excluded to keep default tests fast; run Test-All.ps1 from the repository root"]
168 fn test_rust_analyzer_generated_method_dependencies() -> Result<()> {
169 let (fixture, options) = analyzer_fixture();
170 let project = fixture.join("generated-methods");
171 let source_directory = Path::new("src");
172 let client = FileNode::new(source_directory.join("client.rs"))?;
173 let factory = FileNode::new(source_directory.join("factory.rs"))?;
174 let model = FileNode::new(source_directory.join("model.rs"))?;
175 let validation = FileNode::new(source_directory.join("validation.rs"))?;
176 let expected = BTreeSet::from([
177 FileEdge::new(client.clone(), factory.clone(), DependencyKind::Production),
178 FileEdge::new(client, model.clone(), DependencyKind::Production),
179 FileEdge::new(factory.clone(), model.clone(), DependencyKind::Production),
180 FileEdge::new(validation.clone(), factory, DependencyKind::Test),
181 FileEdge::new(validation, model, DependencyKind::Test),
182 ]);
183 let system_under_test = RustAnalyzer::new(&project, None, &options);
184
185 let index = system_under_test.index()?;
186 let graph = parse_scip(&index)?;
187
188 assert_eq!(graph.edges(), &expected, "Calls to generated accessors must retain their defining file and test classification");
189 Ok(())
190 }
191
192 #[test]
193 #[ignore = "slow multi-pass rust-analyzer indexing; excluded to keep default tests fast; run Test-All.ps1 from the repository root"]
194 fn test_rust_analyzer_cargo_target_collisions() -> Result<()> {
195 let (fixture, options) = analyzer_fixture();
196 let project = fixture.join("cargo-targets");
197 let library = FileNode::new(Path::new("src").join("library.rs"))?;
198 let expected = BTreeSet::from([
199 FileEdge::new(FileNode::new(Path::new("src").join("bin").join("first.rs"))?, library.clone(), DependencyKind::Production),
200 FileEdge::new(FileNode::new(Path::new("src").join("bin").join("second.rs"))?, library, DependencyKind::Production),
201 ]);
202 let system_under_test = RustAnalyzer::new(&project, None, &options);
203
204 let index = system_under_test.index()?;
205 let graph = parse_scip(&index)?;
206
207 assert_eq!(graph.edges(), &expected, "Cargo target collisions must not create links between binaries or hide library calls");
208 Ok(())
209 }
210 #[test]
211 #[ignore = "slow multi-pass rust-analyzer indexing; excluded to keep default tests fast; run Test-All.ps1 from the repository root"]
212 fn test_rust_analyzer_manifest_file_graph() -> Result<()> {
213 let (fixture, options) = analyzer_fixture();
214 let manifest = fixture.join("dependency-graph").join("Cargo.toml");
215 let expected = parse_scip(&ScipFile::new(fixture.join("dependency-graph.scip")).index()?)?;
216 let system_under_test = RustAnalyzer::new(&manifest, None, &options);
217
218 let index = system_under_test.index()?;
219 let graph = parse_scip(&index)?;
220
221 assert_eq!(
222 graph.files(),
223 expected.files(),
224 "rust-analyzer indexing changed fixture files"
225 );
226 assert_eq!(
227 graph.edges(),
228 expected.edges(),
229 "rust-analyzer indexing changed fixture dependencies"
230 );
231 Ok(())
232 }
233
234 #[test]
235 #[ignore = "slow multi-pass rust-analyzer indexing; excluded to keep default tests fast; run Test-All.ps1 from the repository root"]
236 fn test_rust_analyzer_test_configuration_classification() -> Result<()> {
237 let (fixture, options) = analyzer_fixture();
238 let manifest = fixture.join("test-dependencies").join("Cargo.toml");
239 let source_directory = Path::new("src");
240 let module_file = "mod.rs";
241 let client = FileNode::new(source_directory.join("client").join("calls.rs"))?;
242 let shared = FileNode::new(source_directory.join("shared").join("value.rs"))?;
243 let test_only = FileNode::new(source_directory.join("test_only").join("value.rs"))?;
244 let validation = FileNode::new(source_directory.join("validation").join("checks.rs"))?;
245 let expected = FileGraph::new(
246 BTreeSet::from([
247 FileNode::new(source_directory.join("lib.rs"))?,
248 FileNode::new(source_directory.join("client").join(module_file))?,
249 FileNode::new(source_directory.join("shared").join(module_file))?,
250 FileNode::new(source_directory.join("test_only").join(module_file))?,
251 client.clone(),
252 shared.clone(),
253 test_only.clone(),
254 validation.clone(),
255 ]),
256 BTreeSet::from([
257 FileEdge::new(client.clone(), shared.clone(), DependencyKind::Production),
258 FileEdge::new(client.clone(), shared, DependencyKind::Test),
259 FileEdge::new(client, test_only.clone(), DependencyKind::Test),
260 FileEdge::new(validation, test_only, DependencyKind::Test),
261 ]),
262 )?;
263 let system_under_test = RustAnalyzer::new(&manifest, None, &options);
264
265 let index = system_under_test.index()?;
266 let graph = parse_scip(&index)?;
267
268 assert_eq!(
269 graph.files(),
270 expected.files(),
271 "rust-analyzer analysis changed classified fixture files"
272 );
273 assert_eq!(
274 graph.edges(),
275 expected.edges(),
276 "rust-analyzer analysis changed classified fixture dependencies"
277 );
278 Ok(())
279 }
280}