provable_contracts/query/
cross_project.rs1use std::collections::HashMap;
8use std::path::{Path, PathBuf};
9
10use serde::{Deserialize, Serialize};
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct ProjectEntry {
15 pub name: String,
16 pub path: PathBuf,
17 pub has_cargo_toml: bool,
18 pub has_binding: bool,
19 pub binding_path: Option<PathBuf>,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct CallSite {
25 pub project: String,
26 pub file: String,
27 pub line: u32,
28 pub contract_stem: String,
29 pub equation: Option<String>,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct BindingRef {
35 pub project: String,
36 pub binding_path: String,
37 pub contract: String,
38 pub equation: String,
39 pub status: String,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct KaizenRef {
45 pub project: String,
46 pub file: String,
47 pub line: u32,
48 pub pattern: String,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct CommitRef {
54 pub project: String,
55 pub commit_hash: String,
56 pub pattern: String,
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct CrossProjectIndex {
62 pub projects: Vec<ProjectEntry>,
63 pub call_sites: HashMap<String, Vec<CallSite>>,
64 pub binding_refs: HashMap<String, Vec<BindingRef>>,
65 pub kaizen_refs: HashMap<String, Vec<KaizenRef>>,
66 pub commit_refs: HashMap<String, Vec<CommitRef>>,
67}
68
69impl CrossProjectIndex {
70 pub fn build(contracts_repo_root: &Path) -> Self {
76 Self::build_with_extra(contracts_repo_root, None)
77 }
78
79 pub fn build_with_extra(contracts_repo_root: &Path, extra_path: Option<&Path>) -> Self {
81 let root = contracts_repo_root
82 .canonicalize()
83 .unwrap_or_else(|_| contracts_repo_root.to_path_buf());
84 let parent = root.parent().unwrap_or(&root);
85
86 let mut projects = discover_projects(parent, &root);
87
88 if let Some(extra) = extra_path {
90 let extra_canon = extra.canonicalize().unwrap_or_else(|_| extra.to_path_buf());
91 if extra_canon.is_dir() && !projects.iter().any(|p| p.path == extra_canon) {
92 let name = extra_canon
93 .file_name()
94 .and_then(|n| n.to_str())
95 .unwrap_or("unknown")
96 .to_string();
97 let binding_path = find_binding_path(&extra_canon, &name);
98 projects.push(ProjectEntry {
99 name,
100 has_cargo_toml: extra_canon.join("Cargo.toml").exists(),
101 has_binding: binding_path.is_some(),
102 binding_path,
103 path: extra_canon,
104 });
105 }
106 }
107
108 let mut call_sites: HashMap<String, Vec<CallSite>> = HashMap::new();
109 let mut binding_refs: HashMap<String, Vec<BindingRef>> = HashMap::new();
110 let mut kaizen_refs: HashMap<String, Vec<KaizenRef>> = HashMap::new();
111 let mut commit_refs: HashMap<String, Vec<CommitRef>> = HashMap::new();
112
113 for project in &projects {
114 scan_contract_annotations(project, &mut call_sites);
115 scan_binding_refs(project, &mut binding_refs);
116 scan_kaizen_refs(project, &mut kaizen_refs);
117 scan_commit_refs(project, &mut commit_refs);
118 }
119
120 Self {
121 projects,
122 call_sites,
123 binding_refs,
124 kaizen_refs,
125 commit_refs,
126 }
127 }
128
129 pub fn call_sites_for(&self, stem: &str) -> &[CallSite] {
131 self.call_sites.get(stem).map_or(&[], Vec::as_slice)
132 }
133
134 pub fn binding_refs_for(&self, stem: &str) -> &[BindingRef] {
136 self.binding_refs.get(stem).map_or(&[], Vec::as_slice)
137 }
138
139 pub fn kaizen_refs_for(&self, pattern: &str) -> &[KaizenRef] {
141 self.kaizen_refs.get(pattern).map_or(&[], Vec::as_slice)
142 }
143
144 pub fn commit_refs_for(&self, pattern: &str) -> &[CommitRef] {
146 self.commit_refs.get(pattern).map_or(&[], Vec::as_slice)
147 }
148
149 pub fn total_call_sites(&self) -> usize {
151 self.call_sites.values().map(Vec::len).sum()
152 }
153
154 pub fn project_count(&self) -> usize {
156 self.projects.len()
157 }
158}
159
160fn discover_projects(parent_dir: &Path, self_dir: &Path) -> Vec<ProjectEntry> {
162 let mut projects = Vec::new();
163 let Ok(entries) = std::fs::read_dir(parent_dir) else {
164 return projects;
165 };
166
167 for entry in entries.flatten() {
168 let path = entry.path();
169 if !path.is_dir() || path == self_dir {
170 continue;
171 }
172
173 let has_cargo_toml = path.join("Cargo.toml").exists();
174 if !has_cargo_toml {
175 continue;
176 }
177
178 let name = path
179 .file_name()
180 .and_then(|n| n.to_str())
181 .unwrap_or("unknown")
182 .to_string();
183
184 let binding_path = find_binding_path(&path, &name);
186
187 projects.push(ProjectEntry {
188 name,
189 has_cargo_toml,
190 has_binding: binding_path.is_some(),
191 binding_path,
192 path,
193 });
194 }
195
196 projects.sort_by(|a, b| a.name.cmp(&b.name));
197 projects
198}
199
200fn find_binding_path(project_dir: &Path, name: &str) -> Option<PathBuf> {
202 let in_tree_binding = project_dir
204 .join("contracts")
205 .join(name)
206 .join("binding.yaml");
207 if in_tree_binding.exists() {
208 return Some(in_tree_binding);
209 }
210
211 let sibling_binding = project_dir
213 .parent()?
214 .join("provable-contracts/contracts")
215 .join(name)
216 .join("binding.yaml");
217 if sibling_binding.exists() {
218 return Some(sibling_binding);
219 }
220
221 let root_binding = project_dir.join("binding.yaml");
223 if root_binding.exists() {
224 return Some(root_binding);
225 }
226
227 None
228}
229
230fn scan_contract_annotations(
232 project: &ProjectEntry,
233 call_sites: &mut HashMap<String, Vec<CallSite>>,
234) {
235 let src_dir = project.path.join("src");
236 if !src_dir.exists() {
237 return;
238 }
239
240 let output = std::process::Command::new("grep")
241 .args(["-rn", "contract(\"", "--include=*.rs"])
242 .arg(&src_dir)
243 .output();
244
245 let Ok(output) = output else { return };
246 if !output.status.success() {
247 return;
248 }
249
250 let stdout = String::from_utf8_lossy(&output.stdout);
251 for line in stdout.lines() {
252 if let Some(site) = parse_contract_annotation(line, &project.name, &project.path) {
253 call_sites
254 .entry(site.contract_stem.clone())
255 .or_default()
256 .push(site);
257 }
258 }
259}
260
261fn parse_contract_annotation(
263 line: &str,
264 project_name: &str,
265 project_path: &Path,
266) -> Option<CallSite> {
267 let parts: Vec<&str> = line.splitn(3, ':').collect();
269 if parts.len() < 3 {
270 return None;
271 }
272 let file_path = parts[0];
273 let line_no: u32 = parts[1].parse().ok()?;
274 let content = parts[2];
275
276 let stem = extract_contract_stem(content)?;
278
279 let equation = extract_equation(content);
281
282 let relative = file_path
284 .strip_prefix(project_path.to_string_lossy().as_ref())
285 .unwrap_or(file_path)
286 .trim_start_matches('/');
287
288 Some(CallSite {
289 project: project_name.to_string(),
290 file: relative.to_string(),
291 line: line_no,
292 contract_stem: stem,
293 equation,
294 })
295}
296
297fn extract_contract_stem(content: &str) -> Option<String> {
299 let idx = content.find("contract(\"")?;
301 let start = idx + "contract(\"".len();
302 let rest = &content[start..];
303 let end = rest.find('"')?;
304 let stem = &rest[..end];
305 Some(stem.strip_suffix(".yaml").unwrap_or(stem).to_string())
307}
308
309fn extract_equation(content: &str) -> Option<String> {
311 let idx = content.find("equation")?;
313 let rest = &content[idx..];
314 let q_start = rest.find('"')? + 1;
315 let q_rest = &rest[q_start..];
316 let q_end = q_rest.find('"')?;
317 Some(q_rest[..q_end].to_string())
318}
319
320fn scan_binding_refs(project: &ProjectEntry, refs: &mut HashMap<String, Vec<BindingRef>>) {
322 let Some(binding_path) = &project.binding_path else {
323 return;
324 };
325 let Ok(content) = std::fs::read_to_string(binding_path) else {
326 return;
327 };
328 let Ok(registry) = crate::binding::parse_binding_str(&content) else {
329 return;
330 };
331
332 for binding in ®istry.bindings {
333 let stem = binding
334 .contract
335 .strip_suffix(".yaml")
336 .unwrap_or(&binding.contract)
337 .to_string();
338
339 refs.entry(stem).or_default().push(BindingRef {
340 project: project.name.clone(),
341 binding_path: binding_path.display().to_string(),
342 contract: binding.contract.clone(),
343 equation: binding.equation.clone(),
344 status: binding.status.to_string(),
345 });
346 }
347}
348
349fn scan_kaizen_refs(project: &ProjectEntry, refs: &mut HashMap<String, Vec<KaizenRef>>) {
351 let src_dir = project.path.join("src");
352 if !src_dir.exists() {
353 return;
354 }
355
356 let output = std::process::Command::new("grep")
357 .args([
358 "-rn",
359 "-E",
360 r"KAIZEN-[0-9]+|C-[A-Z]+-[0-9]+",
361 "--include=*.rs",
362 ])
363 .arg(&src_dir)
364 .output();
365
366 let Ok(output) = output else { return };
367 if !output.status.success() {
368 return;
369 }
370
371 let stdout = String::from_utf8_lossy(&output.stdout);
372 for line in stdout.lines() {
373 let parts: Vec<&str> = line.splitn(3, ':').collect();
374 if parts.len() < 3 {
375 continue;
376 }
377 let line_no: u32 = match parts[1].parse() {
378 Ok(n) => n,
379 Err(_) => continue,
380 };
381 let content = parts[2];
382
383 let relative = parts[0]
384 .strip_prefix(project.path.to_string_lossy().as_ref())
385 .unwrap_or(parts[0])
386 .trim_start_matches('/');
387
388 for pattern in extract_patterns(content) {
390 refs.entry(pattern.clone()).or_default().push(KaizenRef {
391 project: project.name.clone(),
392 file: relative.to_string(),
393 line: line_no,
394 pattern,
395 });
396 }
397 }
398}
399
400fn extract_patterns(content: &str) -> Vec<String> {
402 let mut patterns = Vec::new();
403 let mut rest = content;
404 while let Some(idx) = rest.find("KAIZEN-") {
405 let start = idx;
406 let after = &rest[idx + 7..];
407 let end = after
408 .find(|c: char| !c.is_ascii_digit())
409 .unwrap_or(after.len());
410 if end > 0 {
411 patterns.push(rest[start..start + 7 + end].to_string());
412 }
413 rest = &rest[start + 7 + end..];
414 }
415
416 rest = content;
417 while let Some(idx) = rest.find("C-") {
418 let after_c = &rest[idx + 2..];
419 let alpha_end = after_c.find(|c: char| !c.is_ascii_uppercase()).unwrap_or(0);
421 if alpha_end > 0 && after_c.get(alpha_end..=alpha_end) == Some("-") {
422 let digit_start = alpha_end + 1;
423 let digit_rest = &after_c[digit_start..];
424 let digit_end = digit_rest
425 .find(|c: char| !c.is_ascii_digit())
426 .unwrap_or(digit_rest.len());
427 if digit_end > 0 {
428 let full_end = idx + 2 + digit_start + digit_end;
429 patterns.push(rest[idx..full_end].to_string());
430 rest = &rest[full_end..];
431 continue;
432 }
433 }
434 rest = &rest[idx + 2..];
435 }
436
437 patterns
438}
439
440fn scan_commit_refs(project: &ProjectEntry, refs: &mut HashMap<String, Vec<CommitRef>>) {
442 if !project.path.join(".git").exists() {
443 return;
444 }
445 let output = std::process::Command::new("git")
447 .args(["log", "--oneline", "-200", "--format=%H %s"])
448 .current_dir(&project.path)
449 .output();
450
451 let Ok(output) = output else { return };
452 if !output.status.success() {
453 return;
454 }
455
456 let stdout = String::from_utf8_lossy(&output.stdout);
457 for line in stdout.lines() {
458 let Some((hash, subject)) = line.split_once(' ') else {
459 continue;
460 };
461 let short_hash = &hash[..hash.len().min(12)];
462 for pattern in extract_patterns(subject) {
463 refs.entry(pattern.clone()).or_default().push(CommitRef {
464 project: project.name.clone(),
465 commit_hash: short_hash.to_string(),
466 pattern,
467 });
468 }
469 }
470}
471
472#[cfg(test)]
473mod tests {
474 include!("cross_project_tests.rs");
475}