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