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, "", &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, 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 mut visitor = ShapeVisitor {
263 items: Vec::new(),
264 mod_path: mod_path.to_string(),
265 file_dir: file_path.parent().map(Path::to_path_buf).unwrap_or_default(),
266 file_stem: file_path
267 .file_stem()
268 .and_then(|s| s.to_str())
269 .unwrap_or("")
270 .to_string(),
271 };
272 visitor.visit_file(&file);
273
274 let mut items = visitor.items;
275 items.sort();
276
277 out.push_str(&format!("=== mod {} ===\n", mod_path));
278 for item_text in &items {
279 out.push_str(item_text);
280 out.push('\n');
281 }
282
283 let reexport_targets = find_reexport_targets(&file);
285
286 for sub in find_submodules(&file) {
287 let sub_path = resolve_submodule(&visitor.file_dir, &visitor.file_stem, &sub.name)?;
288 let new_mod_path = if mod_path.is_empty() {
289 sub.name.clone()
290 } else {
291 format!("{}::{}", mod_path, sub.name)
292 };
293 if sub.is_pub {
294 walk_module(&sub_path, &new_mod_path, out)?;
295 } else if reexport_targets.contains(&sub.name) {
296 walk_module(&sub_path, &new_mod_path, out)?;
300 }
301 }
302
303 Ok(())
304}
305
306fn find_reexport_targets(file: &syn::File) -> std::collections::HashSet<String> {
313 let mut targets = std::collections::HashSet::new();
314 for item in &file.items {
315 if let syn::Item::Use(u) = item {
316 if !matches!(u.vis, syn::Visibility::Public(_)) {
317 continue;
318 }
319 collect_use_roots(&u.tree, &mut targets);
320 }
321 }
322 targets
323}
324
325fn collect_use_roots(tree: &syn::UseTree, targets: &mut std::collections::HashSet<String>) {
326 match tree {
327 syn::UseTree::Path(p) => {
328 let name = p.ident.to_string();
329 let name = name.strip_prefix("r#").unwrap_or(&name).to_string();
330 targets.insert(name);
332 }
333 syn::UseTree::Group(g) => {
334 for item in &g.items {
335 collect_use_roots(item, targets);
336 }
337 }
338 syn::UseTree::Name(_) | syn::UseTree::Rename(_) | syn::UseTree::Glob(_) => {}
340 }
341}
342
343struct SubmoduleDecl {
344 name: String,
345 is_pub: bool,
346}
347
348fn find_submodules(file: &syn::File) -> Vec<SubmoduleDecl> {
349 let mut subs = Vec::new();
350 for item in &file.items {
351 if let syn::Item::Mod(m) = item {
352 if m.content.is_none() {
353 let is_pub = matches!(m.vis, syn::Visibility::Public(_));
354 let name = m.ident.to_string();
355 let name = name.strip_prefix("r#").unwrap_or(&name).to_string();
356 subs.push(SubmoduleDecl { name, is_pub });
357 }
358 }
359 }
360 subs
361}
362
363fn resolve_submodule(parent_dir: &Path, file_stem: &str, name: &str) -> Result<PathBuf> {
364 let candidates: Vec<PathBuf> = if file_stem == "lib" || file_stem == "mod" || file_stem == "main"
365 {
366 vec![
367 parent_dir.join(format!("{}.rs", name)),
368 parent_dir.join(name).join("mod.rs"),
369 ]
370 } else {
371 vec![
372 parent_dir.join(file_stem).join(format!("{}.rs", name)),
373 parent_dir.join(file_stem).join(name).join("mod.rs"),
374 ]
375 };
376
377 for c in &candidates {
378 if c.exists() {
379 return Ok(c.clone());
380 }
381 }
382 anyhow::bail!(
383 "could not resolve submodule `{}` from `{}/{}.rs`",
384 name,
385 parent_dir.display(),
386 file_stem,
387 )
388}
389
390struct ShapeVisitor {
395 items: Vec<String>,
396 mod_path: String,
397 file_dir: PathBuf,
398 file_stem: String,
399}
400
401impl ShapeVisitor {
402 fn is_visible(&self, vis: &syn::Visibility) -> bool {
403 matches!(vis, syn::Visibility::Public(_))
404 }
405}
406
407impl<'ast> Visit<'ast> for ShapeVisitor {
408 fn visit_item_fn(&mut self, f: &'ast syn::ItemFn) {
409 if !self.is_visible(&f.vis) {
410 return;
411 }
412 let inline = has_inline_attr(&f.attrs);
413 let generic = has_type_or_const_generics(&f.sig.generics);
414 let constfn = f.sig.constness.is_some();
415 let body_visible_downstream = inline || generic || constfn;
416 let body = if body_visible_downstream {
417 quote::quote!(#f).to_string()
418 } else {
419 String::new()
420 };
421 let text = format!(
422 "fn {} {} {}{}{}",
423 sig_text(&f.sig),
424 relevant_attrs(&f.attrs),
425 if body_visible_downstream {
426 "<<BODY: "
427 } else {
428 ""
429 },
430 body,
431 if body_visible_downstream { ">>" } else { "" }
432 );
433 self.items.push(format!("[fn] {}::{}", self.mod_path, text));
434 }
435
436 fn visit_item_struct(&mut self, s: &'ast syn::ItemStruct) {
437 if !self.is_visible(&s.vis) {
438 return;
439 }
440 let text = quote::quote!(#s).to_string();
441 self.items
442 .push(format!("[struct] {}::{}", self.mod_path, text));
443 }
444
445 fn visit_item_enum(&mut self, e: &'ast syn::ItemEnum) {
446 if !self.is_visible(&e.vis) {
447 return;
448 }
449 let text = quote::quote!(#e).to_string();
450 self.items.push(format!("[enum] {}::{}", self.mod_path, text));
451 }
452
453 fn visit_item_trait(&mut self, t: &'ast syn::ItemTrait) {
454 if !self.is_visible(&t.vis) {
455 return;
456 }
457 let text = quote::quote!(#t).to_string();
458 self.items
459 .push(format!("[trait] {}::{}", self.mod_path, text));
460 }
461
462 fn visit_item_type(&mut self, t: &'ast syn::ItemType) {
463 if !self.is_visible(&t.vis) {
464 return;
465 }
466 let text = quote::quote!(#t).to_string();
467 self.items
468 .push(format!("[type] {}::{}", self.mod_path, text));
469 }
470
471 fn visit_item_const(&mut self, c: &'ast syn::ItemConst) {
472 if !self.is_visible(&c.vis) {
473 return;
474 }
475 let text = quote::quote!(#c).to_string();
476 self.items.push(format!("[const] {}::{}", self.mod_path, text));
477 }
478
479 fn visit_item_static(&mut self, s: &'ast syn::ItemStatic) {
480 if !self.is_visible(&s.vis) {
481 return;
482 }
483 let text = quote::quote!(#s).to_string();
484 self.items
485 .push(format!("[static] {}::{}", self.mod_path, text));
486 }
487
488 fn visit_item_use(&mut self, u: &'ast syn::ItemUse) {
489 if !self.is_visible(&u.vis) {
490 return;
491 }
492 let text = quote::quote!(#u).to_string();
493 self.items.push(format!("[use] {}::{}", self.mod_path, text));
494 }
495
496 fn visit_item_macro(&mut self, m: &'ast syn::ItemMacro) {
497 let exported = m.attrs.iter().any(|a| a.path().is_ident("macro_export"));
498 if !exported {
499 return;
500 }
501 let text = quote::quote!(#m).to_string();
502 self.items
503 .push(format!("[macro] {}::{}", self.mod_path, text));
504 }
505
506 fn visit_item_impl(&mut self, i: &'ast syn::ItemImpl) {
507 let mut buf = String::from("impl");
508 let generics = &i.generics;
509 if !i.generics.params.is_empty() {
510 buf.push_str("e::quote!(#generics).to_string());
511 }
512 let self_ty = &i.self_ty;
513 if let Some((_, trait_path, _)) = &i.trait_ {
514 buf.push(' ');
515 buf.push_str("e::quote!(#trait_path).to_string());
516 buf.push_str(" for ");
517 } else {
518 buf.push(' ');
519 }
520 buf.push_str("e::quote!(#self_ty).to_string());
521
522 let is_trait_impl = i.trait_.is_some();
523 for item in &i.items {
524 match item {
525 syn::ImplItem::Fn(f) => {
526 let visible = is_trait_impl || matches!(f.vis, syn::Visibility::Public(_));
527 if !visible {
528 continue;
529 }
530 let inline = has_inline_attr(&f.attrs);
531 let generic = has_type_or_const_generics(&f.sig.generics);
532 let constfn = f.sig.constness.is_some();
533 let body_visible = inline || generic || constfn;
534 let sig = sig_text(&f.sig);
535 if body_visible {
536 let body = quote::quote!(#f).to_string();
537 buf.push_str(&format!("\n fn {} <<BODY: {}>>", sig, body));
538 } else {
539 buf.push_str(&format!("\n fn {};", sig));
540 }
541 }
542 syn::ImplItem::Const(c) => {
543 let visible = is_trait_impl || matches!(c.vis, syn::Visibility::Public(_));
544 if !visible {
545 continue;
546 }
547 buf.push_str(&format!("\n {}", quote::quote!(#c)));
548 }
549 syn::ImplItem::Type(t) => {
550 let visible = is_trait_impl || matches!(t.vis, syn::Visibility::Public(_));
551 if !visible {
552 continue;
553 }
554 buf.push_str(&format!("\n {}", quote::quote!(#t)));
555 }
556 _ => {}
557 }
558 }
559
560 self.items
561 .push(format!("[impl] {}::{}", self.mod_path, buf));
562 }
563
564 fn visit_item_mod(&mut self, m: &'ast syn::ItemMod) {
565 if m.content.is_none() {
566 return;
567 }
568 let visible = matches!(m.vis, syn::Visibility::Public(_));
569 if !visible {
570 return;
571 }
572 let new_mod_path = if self.mod_path.is_empty() {
573 m.ident.to_string()
574 } else {
575 format!("{}::{}", self.mod_path, m.ident)
576 };
577 let mut sub_visitor = ShapeVisitor {
578 items: Vec::new(),
579 mod_path: new_mod_path.clone(),
580 file_dir: self.file_dir.clone(),
581 file_stem: self.file_stem.clone(),
582 };
583 if let Some((_, items)) = &m.content {
584 for item in items {
585 sub_visitor.visit_item(item);
586 }
587 }
588 sub_visitor.items.sort();
589 self.items.push(format!(
590 "[mod] {}::{} {{\n{}\n}}",
591 self.mod_path,
592 m.ident,
593 sub_visitor.items.join("\n")
594 ));
595 }
596}
597
598fn sig_text(sig: &syn::Signature) -> String {
599 quote::quote!(#sig).to_string()
600}
601
602fn has_inline_attr(attrs: &[syn::Attribute]) -> bool {
603 attrs.iter().any(|a| a.path().is_ident("inline"))
604}
605
606fn has_type_or_const_generics(g: &syn::Generics) -> bool {
607 g.params.iter().any(|p| {
608 matches!(
609 p,
610 syn::GenericParam::Type(_) | syn::GenericParam::Const(_)
611 )
612 })
613}
614
615fn relevant_attrs(attrs: &[syn::Attribute]) -> String {
616 let mut buf = String::new();
617 for a in attrs {
618 let path = quote::quote!(#a).to_string();
619 if !path.contains("# [doc") && !path.contains("#[doc") {
620 buf.push_str(&path);
621 buf.push(' ');
622 }
623 }
624 buf
625}
626
627fn hex_encode(bytes: impl AsRef<[u8]>) -> String {
628 const HEX: &[u8; 16] = b"0123456789abcdef";
629 let bytes = bytes.as_ref();
630 let mut out = String::with_capacity(bytes.len() * 2);
631 for &b in bytes {
632 out.push(HEX[(b >> 4) as usize] as char);
633 out.push(HEX[(b & 0xf) as usize] as char);
634 }
635 out
636}