1use anyhow::{Context, Result};
2use sha2::{Digest, Sha256};
3use std::collections::BTreeMap;
4use std::fs;
5use std::path::{Path, PathBuf};
6use syn::visit::Visit;
7
8#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
9pub struct ShapeManifest {
10 pub crates: BTreeMap<String, String>,
11 pub version: String,
12}
13
14#[derive(Debug)]
15pub struct CrateShape {
16 pub name: String,
17 pub path: PathBuf,
18 pub canonical_text: String,
19 pub hash: String,
20}
21
22pub fn hash_workspace(workspace_root: &Path) -> Result<Vec<CrateShape>> {
23 let crate_paths = resolve_workspace_members(workspace_root)?;
24 let mut results = Vec::new();
25 for crate_path in crate_paths {
26 match hash_crate(&crate_path) {
27 Ok(shape) => results.push(shape),
28 Err(e) => {
29 eprintln!("warn: {}: {}", crate_path.display(), e);
30 }
31 }
32 }
33 results.sort_by(|a, b| a.name.cmp(&b.name));
34 Ok(results)
35}
36
37pub fn hash_crate(crate_path: &Path) -> Result<CrateShape> {
38 let name = crate_name(crate_path)?;
39 let entry = find_crate_entry(crate_path)?;
40 if !entry.exists() {
41 anyhow::bail!("entry point {} does not exist", entry.display());
42 }
43
44 let mut canonical = String::new();
45 walk_module(&entry, "", true, &mut canonical)?;
46
47 let mut hasher = Sha256::new();
48 hasher.update(canonical.as_bytes());
49 let hash = hex_encode(hasher.finalize());
50
51 Ok(CrateShape {
52 name,
53 path: crate_path.to_path_buf(),
54 canonical_text: canonical,
55 hash,
56 })
57}
58
59pub fn to_manifest(shapes: &[CrateShape]) -> ShapeManifest {
60 let mut crates = BTreeMap::new();
61 for s in shapes {
62 crates.insert(s.name.clone(), s.hash.clone());
63 }
64 ShapeManifest {
65 crates,
66 version: env!("CARGO_PKG_VERSION").to_string(),
67 }
68}
69
70pub fn diff_manifests(
71 old: &ShapeManifest,
72 new: &ShapeManifest,
73) -> (Vec<String>, Vec<String>, Vec<String>) {
74 let mut unchanged = Vec::new();
75 let mut changed = Vec::new();
76 let mut added = Vec::new();
77
78 for (name, new_hash) in &new.crates {
79 match old.crates.get(name) {
80 Some(old_hash) if old_hash == new_hash => unchanged.push(name.clone()),
81 Some(_) => changed.push(name.clone()),
82 None => added.push(name.clone()),
83 }
84 }
85 (unchanged, changed, added)
86}
87
88pub fn workspace_crate_map(workspace_root: &Path) -> Result<BTreeMap<String, PathBuf>> {
89 let members = resolve_workspace_members(workspace_root)?;
90 let mut map = BTreeMap::new();
91 for crate_path in members {
92 if let Ok(name) = crate_name(&crate_path) {
93 map.insert(name, crate_path);
94 }
95 }
96 Ok(map)
97}
98
99pub fn crate_rel_paths(workspace_root: &Path) -> Result<BTreeMap<String, String>> {
100 let members = resolve_workspace_members(workspace_root)?;
101 let mut map = BTreeMap::new();
102 for crate_path in members {
103 if let Ok(name) = crate_name(&crate_path) {
104 let rel = crate_path
105 .strip_prefix(workspace_root)
106 .unwrap_or(&crate_path)
107 .to_string_lossy()
108 .replace('\\', "/");
109 map.insert(name, rel);
110 }
111 }
112 Ok(map)
113}
114
115pub const MANIFEST_FILENAME: &str = ".shape-check.json";
116
117pub fn load_manifest(workspace_root: &Path) -> Result<Option<ShapeManifest>> {
118 let path = workspace_root.join(MANIFEST_FILENAME);
119 if !path.exists() {
120 return Ok(None);
121 }
122 let text = fs::read_to_string(&path)?;
123 let manifest: ShapeManifest = serde_json::from_str(&text)?;
124 Ok(Some(manifest))
125}
126
127pub fn save_manifest(workspace_root: &Path, manifest: &ShapeManifest) -> Result<()> {
128 let path = workspace_root.join(MANIFEST_FILENAME);
129 let text = serde_json::to_string_pretty(manifest)?;
130 fs::write(&path, text)?;
131 Ok(())
132}
133
134pub fn resolve_workspace_members(workspace_root: &Path) -> Result<Vec<PathBuf>> {
139 let cargo_toml = workspace_root.join("Cargo.toml");
140 let toml_text =
141 fs::read_to_string(&cargo_toml).with_context(|| format!("read {}", cargo_toml.display()))?;
142 let manifest: toml::Value = toml::from_str(&toml_text)?;
143
144 let workspace = manifest
145 .get("workspace")
146 .context("no [workspace] section in Cargo.toml")?
147 .as_table()
148 .context("[workspace] is not a table")?;
149
150 let members = workspace
151 .get("members")
152 .and_then(|v| v.as_array())
153 .context("no workspace.members")?;
154
155 let excludes: std::collections::HashSet<String> = workspace
156 .get("exclude")
157 .and_then(|v| v.as_array())
158 .map(|arr| {
159 arr.iter()
160 .filter_map(|v| v.as_str().map(String::from))
161 .collect()
162 })
163 .unwrap_or_default();
164
165 let mut crate_paths: Vec<PathBuf> = Vec::new();
166 for m in members {
167 let glob_str = m.as_str().unwrap_or("").trim_end_matches('/');
168 if glob_str.is_empty() {
169 continue;
170 }
171 if glob_str.contains('*') {
172 let parent_glob = glob_str.replace("/*", "").replace("*", "");
173 let parent = workspace_root.join(&parent_glob);
174 if parent.is_dir() {
175 let mut entries: Vec<_> = fs::read_dir(&parent)?
176 .filter_map(|e| e.ok())
177 .filter(|e| e.file_type().map(|ft| ft.is_dir()).unwrap_or(false))
178 .collect();
179 entries.sort_by_key(|e| e.file_name());
180 for entry in entries {
181 let p = entry.path();
182 if p.join("Cargo.toml").exists() {
183 let rel = p
184 .strip_prefix(workspace_root)
185 .unwrap_or(&p)
186 .to_string_lossy()
187 .replace('\\', "/");
188 if !excludes.contains(&rel) {
189 crate_paths.push(p);
190 }
191 }
192 }
193 }
194 } else {
195 let p = workspace_root.join(glob_str);
196 if p.join("Cargo.toml").exists() {
197 let rel = p
198 .strip_prefix(workspace_root)
199 .unwrap_or(&p)
200 .to_string_lossy()
201 .replace('\\', "/");
202 if !excludes.contains(&rel) {
203 crate_paths.push(p);
204 }
205 }
206 }
207 }
208
209 Ok(crate_paths)
210}
211
212fn crate_name(crate_path: &Path) -> Result<String> {
213 let toml_text = fs::read_to_string(crate_path.join("Cargo.toml"))?;
214 let v: toml::Value = toml::from_str(&toml_text)?;
215 let name = v
216 .get("package")
217 .and_then(|p| p.get("name"))
218 .and_then(|n| n.as_str())
219 .context("no package.name in Cargo.toml")?
220 .to_string();
221 Ok(name)
222}
223
224fn find_crate_entry(crate_path: &Path) -> Result<PathBuf> {
225 let cargo_toml = crate_path.join("Cargo.toml");
226 if cargo_toml.exists() {
227 let toml_text = fs::read_to_string(&cargo_toml)?;
228 let v: toml::Value = toml::from_str(&toml_text)?;
229 if let Some(lib) = v.get("lib").and_then(|l| l.get("path")).and_then(|p| p.as_str()) {
230 return Ok(crate_path.join(lib));
231 }
232 if let Some(bins) = v.get("bin").and_then(|b| b.as_array()) {
233 if let Some(first) = bins.first() {
234 if let Some(p) = first.get("path").and_then(|p| p.as_str()) {
235 return Ok(crate_path.join(p));
236 }
237 }
238 }
239 }
240 let candidates = [
241 crate_path.join("src/lib.rs"),
242 crate_path.join("src/main.rs"),
243 crate_path.join("lib.rs"),
244 crate_path.join("main.rs"),
245 ];
246 for c in &candidates {
247 if c.exists() {
248 return Ok(c.clone());
249 }
250 }
251 anyhow::bail!("no entry point found for crate at {}", crate_path.display())
252}
253
254fn walk_module(file_path: &Path, mod_path: &str, is_crate_root: bool, out: &mut String) -> Result<()> {
259 let src = fs::read_to_string(file_path).with_context(|| format!("parse {}", file_path.display()))?;
260 let file = syn::parse_file(&src).with_context(|| format!("parse {}", file_path.display()))?;
261
262 let file_stem = file_path
263 .file_stem()
264 .and_then(|s| s.to_str())
265 .unwrap_or("")
266 .to_string();
267 let effective_stem = if is_crate_root { "lib".to_string() } else { file_stem.clone() };
269
270 let mut visitor = ShapeVisitor {
271 items: Vec::new(),
272 mod_path: mod_path.to_string(),
273 file_dir: file_path.parent().map(Path::to_path_buf).unwrap_or_default(),
274 file_stem: effective_stem,
275 };
276 visitor.visit_file(&file);
277
278 let mut items = visitor.items;
279 items.sort();
280
281 out.push_str(&format!("=== mod {} ===\n", mod_path));
282 for item_text in &items {
283 out.push_str(item_text);
284 out.push('\n');
285 }
286
287 let reexport_targets = find_reexport_targets(&file);
289
290 for sub in find_submodules(&file) {
291 let sub_path = resolve_submodule(&visitor.file_dir, &visitor.file_stem, &sub.name)?;
292 let new_mod_path = if mod_path.is_empty() {
293 sub.name.clone()
294 } else {
295 format!("{}::{}", mod_path, sub.name)
296 };
297 if sub.is_pub || reexport_targets.contains(&sub.name) {
298 walk_module(&sub_path, &new_mod_path, false, out)?;
299 }
300 }
301
302 Ok(())
303}
304
305fn find_reexport_targets(file: &syn::File) -> std::collections::HashSet<String> {
312 let mut targets = std::collections::HashSet::new();
313 for item in &file.items {
314 if let syn::Item::Use(u) = item {
315 if !matches!(u.vis, syn::Visibility::Public(_)) {
316 continue;
317 }
318 collect_use_roots(&u.tree, &mut targets);
319 }
320 }
321 targets
322}
323
324fn collect_use_roots(tree: &syn::UseTree, targets: &mut std::collections::HashSet<String>) {
325 match tree {
326 syn::UseTree::Path(p) => {
327 let name = p.ident.to_string();
328 let name = name.strip_prefix("r#").unwrap_or(&name).to_string();
329 targets.insert(name);
331 }
332 syn::UseTree::Group(g) => {
333 for item in &g.items {
334 collect_use_roots(item, targets);
335 }
336 }
337 syn::UseTree::Name(_) | syn::UseTree::Rename(_) | syn::UseTree::Glob(_) => {}
339 }
340}
341
342struct SubmoduleDecl {
343 name: String,
344 is_pub: bool,
345}
346
347fn find_submodules(file: &syn::File) -> Vec<SubmoduleDecl> {
348 let mut subs = Vec::new();
349 for item in &file.items {
350 if let syn::Item::Mod(m) = item {
351 if m.content.is_none() {
352 let is_pub = matches!(m.vis, syn::Visibility::Public(_));
353 let name = m.ident.to_string();
354 let name = name.strip_prefix("r#").unwrap_or(&name).to_string();
355 subs.push(SubmoduleDecl { name, is_pub });
356 }
357 }
358 }
359 subs
360}
361
362fn resolve_submodule(parent_dir: &Path, file_stem: &str, name: &str) -> Result<PathBuf> {
363 let candidates: Vec<PathBuf> = if file_stem == "lib" || file_stem == "mod" || file_stem == "main"
364 {
365 vec![
366 parent_dir.join(format!("{}.rs", name)),
367 parent_dir.join(name).join("mod.rs"),
368 ]
369 } else {
370 vec![
371 parent_dir.join(file_stem).join(format!("{}.rs", name)),
372 parent_dir.join(file_stem).join(name).join("mod.rs"),
373 ]
374 };
375
376 for c in &candidates {
377 if c.exists() {
378 return Ok(c.clone());
379 }
380 }
381 anyhow::bail!(
382 "could not resolve submodule `{}` from `{}/{}.rs`",
383 name,
384 parent_dir.display(),
385 file_stem,
386 )
387}
388
389struct ShapeVisitor {
394 items: Vec<String>,
395 mod_path: String,
396 file_dir: PathBuf,
397 file_stem: String,
398}
399
400impl ShapeVisitor {
401 fn is_visible(&self, vis: &syn::Visibility) -> bool {
402 matches!(vis, syn::Visibility::Public(_))
403 }
404}
405
406impl<'ast> Visit<'ast> for ShapeVisitor {
407 fn visit_item_fn(&mut self, f: &'ast syn::ItemFn) {
408 if !self.is_visible(&f.vis) {
409 return;
410 }
411 let inline = has_inline_attr(&f.attrs);
412 let generic = has_type_or_const_generics(&f.sig.generics);
413 let constfn = f.sig.constness.is_some();
414 let body_visible_downstream = inline || generic || constfn;
415 let body = if body_visible_downstream {
416 quote::quote!(#f).to_string()
417 } else {
418 String::new()
419 };
420 let text = format!(
421 "fn {} {} {}{}{}",
422 sig_text(&f.sig),
423 relevant_attrs(&f.attrs),
424 if body_visible_downstream {
425 "<<BODY: "
426 } else {
427 ""
428 },
429 body,
430 if body_visible_downstream { ">>" } else { "" }
431 );
432 self.items.push(format!("[fn] {}::{}", self.mod_path, text));
433 }
434
435 fn visit_item_struct(&mut self, s: &'ast syn::ItemStruct) {
436 if !self.is_visible(&s.vis) {
437 return;
438 }
439 let text = quote::quote!(#s).to_string();
440 self.items
441 .push(format!("[struct] {}::{}", self.mod_path, text));
442 }
443
444 fn visit_item_enum(&mut self, e: &'ast syn::ItemEnum) {
445 if !self.is_visible(&e.vis) {
446 return;
447 }
448 let text = quote::quote!(#e).to_string();
449 self.items.push(format!("[enum] {}::{}", self.mod_path, text));
450 }
451
452 fn visit_item_trait(&mut self, t: &'ast syn::ItemTrait) {
453 if !self.is_visible(&t.vis) {
454 return;
455 }
456 let text = quote::quote!(#t).to_string();
457 self.items
458 .push(format!("[trait] {}::{}", self.mod_path, text));
459 }
460
461 fn visit_item_type(&mut self, t: &'ast syn::ItemType) {
462 if !self.is_visible(&t.vis) {
463 return;
464 }
465 let text = quote::quote!(#t).to_string();
466 self.items
467 .push(format!("[type] {}::{}", self.mod_path, text));
468 }
469
470 fn visit_item_const(&mut self, c: &'ast syn::ItemConst) {
471 if !self.is_visible(&c.vis) {
472 return;
473 }
474 let text = quote::quote!(#c).to_string();
475 self.items.push(format!("[const] {}::{}", self.mod_path, text));
476 }
477
478 fn visit_item_static(&mut self, s: &'ast syn::ItemStatic) {
479 if !self.is_visible(&s.vis) {
480 return;
481 }
482 let text = quote::quote!(#s).to_string();
483 self.items
484 .push(format!("[static] {}::{}", self.mod_path, text));
485 }
486
487 fn visit_item_use(&mut self, u: &'ast syn::ItemUse) {
488 if !self.is_visible(&u.vis) {
489 return;
490 }
491 let text = quote::quote!(#u).to_string();
492 self.items.push(format!("[use] {}::{}", self.mod_path, text));
493 }
494
495 fn visit_item_macro(&mut self, m: &'ast syn::ItemMacro) {
496 let exported = m.attrs.iter().any(|a| a.path().is_ident("macro_export"));
497 if !exported {
498 return;
499 }
500 let text = quote::quote!(#m).to_string();
501 self.items
502 .push(format!("[macro] {}::{}", self.mod_path, text));
503 }
504
505 fn visit_item_impl(&mut self, i: &'ast syn::ItemImpl) {
506 let mut buf = String::from("impl");
507 let generics = &i.generics;
508 if !i.generics.params.is_empty() {
509 buf.push_str("e::quote!(#generics).to_string());
510 }
511 let self_ty = &i.self_ty;
512 if let Some((_, trait_path, _)) = &i.trait_ {
513 buf.push(' ');
514 buf.push_str("e::quote!(#trait_path).to_string());
515 buf.push_str(" for ");
516 } else {
517 buf.push(' ');
518 }
519 buf.push_str("e::quote!(#self_ty).to_string());
520
521 let is_trait_impl = i.trait_.is_some();
522 for item in &i.items {
523 match item {
524 syn::ImplItem::Fn(f) => {
525 let visible = is_trait_impl || matches!(f.vis, syn::Visibility::Public(_));
526 if !visible {
527 continue;
528 }
529 let inline = has_inline_attr(&f.attrs);
530 let generic = has_type_or_const_generics(&f.sig.generics);
531 let constfn = f.sig.constness.is_some();
532 let body_visible = inline || generic || constfn;
533 let sig = sig_text(&f.sig);
534 if body_visible {
535 let body = quote::quote!(#f).to_string();
536 buf.push_str(&format!("\n fn {} <<BODY: {}>>", sig, body));
537 } else {
538 buf.push_str(&format!("\n fn {};", sig));
539 }
540 }
541 syn::ImplItem::Const(c) => {
542 let visible = is_trait_impl || matches!(c.vis, syn::Visibility::Public(_));
543 if !visible {
544 continue;
545 }
546 buf.push_str(&format!("\n {}", quote::quote!(#c)));
547 }
548 syn::ImplItem::Type(t) => {
549 let visible = is_trait_impl || matches!(t.vis, syn::Visibility::Public(_));
550 if !visible {
551 continue;
552 }
553 buf.push_str(&format!("\n {}", quote::quote!(#t)));
554 }
555 _ => {}
556 }
557 }
558
559 self.items
560 .push(format!("[impl] {}::{}", self.mod_path, buf));
561 }
562
563 fn visit_item_mod(&mut self, m: &'ast syn::ItemMod) {
564 if m.content.is_none() {
565 return;
566 }
567 let visible = matches!(m.vis, syn::Visibility::Public(_));
568 if !visible {
569 return;
570 }
571 let new_mod_path = if self.mod_path.is_empty() {
572 m.ident.to_string()
573 } else {
574 format!("{}::{}", self.mod_path, m.ident)
575 };
576 let mut sub_visitor = ShapeVisitor {
577 items: Vec::new(),
578 mod_path: new_mod_path.clone(),
579 file_dir: self.file_dir.clone(),
580 file_stem: self.file_stem.clone(),
581 };
582 if let Some((_, items)) = &m.content {
583 for item in items {
584 sub_visitor.visit_item(item);
585 }
586 }
587 sub_visitor.items.sort();
588 self.items.push(format!(
589 "[mod] {}::{} {{\n{}\n}}",
590 self.mod_path,
591 m.ident,
592 sub_visitor.items.join("\n")
593 ));
594 }
595}
596
597fn sig_text(sig: &syn::Signature) -> String {
598 quote::quote!(#sig).to_string()
599}
600
601fn has_inline_attr(attrs: &[syn::Attribute]) -> bool {
602 attrs.iter().any(|a| a.path().is_ident("inline"))
603}
604
605fn has_type_or_const_generics(g: &syn::Generics) -> bool {
606 g.params.iter().any(|p| {
607 matches!(
608 p,
609 syn::GenericParam::Type(_) | syn::GenericParam::Const(_)
610 )
611 })
612}
613
614fn relevant_attrs(attrs: &[syn::Attribute]) -> String {
615 let mut buf = String::new();
616 for a in attrs {
617 let path = quote::quote!(#a).to_string();
618 if !path.contains("# [doc") && !path.contains("#[doc") {
619 buf.push_str(&path);
620 buf.push(' ');
621 }
622 }
623 buf
624}
625
626fn hex_encode(bytes: impl AsRef<[u8]>) -> String {
627 const HEX: &[u8; 16] = b"0123456789abcdef";
628 let bytes = bytes.as_ref();
629 let mut out = String::with_capacity(bytes.len() * 2);
630 for &b in bytes {
631 out.push(HEX[(b >> 4) as usize] as char);
632 out.push(HEX[(b & 0xf) as usize] as char);
633 }
634 out
635}