1use std::collections::{BTreeMap, BTreeSet, HashMap};
12use std::path::Path;
13
14use serde_json::Value;
15
16mod generated;
17#[cfg(test)]
18mod generated_tests;
19
20#[derive(Debug, Clone)]
24pub struct ItemInfo {
25 pub kind: String,
27 pub fingerprint: u64,
29 pub signature: String,
33 pub has_docs: bool,
35}
36
37#[derive(Debug, Default)]
39pub struct Surface {
40 pub items: BTreeMap<String, ItemInfo>,
41 pub members: BTreeMap<String, ItemInfo>,
45}
46
47pub struct ItemGroup<'a> {
53 pub representative: &'a String,
54 pub aliases: Vec<&'a String>,
55}
56
57impl Surface {
58 pub fn lookup(&self, path: &str) -> Option<&ItemInfo> {
60 self.items.get(path).or_else(|| self.members.get(path))
61 }
62
63 pub fn grouped(&self) -> Vec<ItemGroup<'_>> {
65 let mut groups: HashMap<(&str, u64), Vec<&String>> = HashMap::new();
66 let mut unfingerprinted = Vec::new();
67 for (path, info) in &self.items {
68 if info.fingerprint == 0 {
69 unfingerprinted.push(path);
70 continue;
71 }
72 groups
73 .entry((info.kind.as_str(), info.fingerprint))
74 .or_default()
75 .push(path);
76 }
77 let mut out: Vec<ItemGroup<'_>> = groups
78 .into_values()
79 .map(|mut aliases| {
80 aliases.sort();
81 let representative = aliases.iter().min_by_key(|p| p.len()).copied().unwrap();
82 ItemGroup {
83 representative,
84 aliases,
85 }
86 })
87 .chain(unfingerprinted.into_iter().map(|p| ItemGroup {
88 representative: p,
89 aliases: vec![p],
90 }))
91 .collect();
92 out.sort_by(|a, b| a.representative.cmp(b.representative));
93 out
94 }
95}
96
97const KINDS: &[&str] = &[
99 "function",
100 "struct",
101 "enum",
102 "trait",
103 "constant",
104 "type_alias",
105 "module",
106 "static",
107 "union",
108 "macro",
109 "proc_macro",
110];
111
112pub fn from_rustdoc(doc: &Value, source_root: &Path) -> Surface {
115 from_rustdoc_with(doc, source_root, &BTreeMap::new())
116}
117
118pub fn from_rustdoc_with(
128 doc: &Value,
129 source_root: &Path,
130 dependencies: &BTreeMap<String, Surface>,
131) -> Surface {
132 let mut surface = Surface::default();
133 let (Some(index), Some(paths)) = (doc["index"].as_object(), doc["paths"].as_object()) else {
134 return surface;
135 };
136 let mut file_cache: HashMap<String, Vec<String>> = HashMap::new();
137
138 for (id, item) in index {
139 if item["visibility"] != "public" {
140 continue;
141 }
142 let Some(inner) = item["inner"].as_object() else {
143 continue;
144 };
145 let Some(kind) = inner.keys().next().map(String::as_str) else {
146 continue;
147 };
148 if !KINDS.contains(&kind) {
149 continue;
150 }
151 let Some(full) = item_path(paths, id) else {
153 continue;
154 };
155
156 let (fingerprint, signature) =
157 item_fingerprint(index, item, kind, source_root, &mut file_cache)
158 .unwrap_or((0, String::new()));
159 let has_docs = item["docs"].as_str().is_some_and(|d| !d.trim().is_empty());
160
161 surface.items.insert(
162 full,
163 ItemInfo {
164 kind: kind.to_string(),
165 fingerprint,
166 signature,
167 has_docs,
168 },
169 );
170 }
171
172 let links = Links {
173 index,
174 paths,
175 crates: &doc["external_crates"],
176 dependencies,
177 };
178 alias_reexports(&links, &mut surface);
179 index_members(index, paths, source_root, &mut file_cache, &mut surface);
180 surface
181}
182
183pub fn reexported_crates(doc: &Value) -> BTreeSet<String> {
186 let (Some(index), Some(paths)) = (doc["index"].as_object(), doc["paths"].as_object()) else {
187 return BTreeSet::new();
188 };
189 index
190 .values()
191 .filter(|item| item["visibility"] == "public")
192 .filter_map(|item| item["inner"]["use"]["id"].as_u64())
193 .filter(|id| !index.contains_key(&id.to_string()))
194 .filter_map(|id| {
195 let crate_id = paths.get(&id.to_string())?["crate_id"].as_u64()?;
196 let name = doc["external_crates"][crate_id.to_string()]["name"].as_str()?;
197 Some(name.to_string())
198 })
199 .collect()
200}
201
202fn index_members(
205 index: &serde_json::Map<String, Value>,
206 paths: &serde_json::Map<String, Value>,
207 source_root: &Path,
208 file_cache: &mut HashMap<String, Vec<String>>,
209 surface: &mut Surface,
210) {
211 for item in index.values() {
212 let imp = &item["inner"]["impl"];
213 if !imp.is_object() || imp["trait"].is_object() {
214 continue;
215 }
216 let Some(type_id) = imp["for"]["resolved_path"]["id"].as_u64() else {
217 continue;
218 };
219 let Some(type_path) = item_path(paths, &type_id.to_string()) else {
220 continue;
221 };
222 let Some(owner) = surface.items.get(&type_path) else {
223 continue;
224 };
225 let spellings: Vec<String> = surface
226 .items
227 .iter()
228 .filter(|(_, info)| info.kind == owner.kind && info.fingerprint == owner.fingerprint)
229 .map(|(path, _)| path.clone())
230 .collect();
231
232 let members = imp["items"].as_array().into_iter().flatten();
233 for member in members.filter_map(|id| index.get(&id.as_u64()?.to_string())) {
234 if member["visibility"] != "public" {
235 continue;
236 }
237 let (kind, name) = match (
238 member["inner"]["function"].is_object(),
239 member["inner"]["assoc_const"].is_object(),
240 member["name"].as_str(),
241 ) {
242 (true, _, Some(name)) => ("function", name),
243 (_, true, Some(name)) => ("constant", name),
244 _ => continue,
245 };
246 let (fingerprint, signature) =
247 item_fingerprint(index, member, kind, source_root, file_cache)
248 .unwrap_or((0, String::new()));
249 let info = ItemInfo {
250 kind: kind.to_string(),
251 fingerprint,
252 signature,
253 has_docs: member["docs"]
254 .as_str()
255 .is_some_and(|d| !d.trim().is_empty()),
256 };
257 for spelling in &spellings {
258 surface
259 .members
260 .insert(format!("{spelling}::{name}"), info.clone());
261 }
262 }
263 }
264}
265
266fn alias_reexports(links: &Links<'_>, surface: &mut Surface) {
278 for (mod_id, item) in links.index {
279 if item["visibility"] != "public" {
280 continue;
281 }
282 let Some(children) = item["inner"]["module"]["items"].as_array() else {
283 continue;
284 };
285 let Some(mod_path) = item_path(links.paths, mod_id) else {
286 continue;
287 };
288
289 for child in children {
290 let Some(child_id) = child.as_u64() else {
291 continue;
292 };
293 let child_id = child_id.to_string();
294 let Some(use_) = links.index.get(&child_id).map(|c| &c["inner"]["use"]) else {
295 continue;
296 };
297 let Some(target_id) = use_["id"].as_u64() else {
298 continue;
299 };
300 if use_["is_glob"].as_bool().unwrap_or(false) {
306 links.alias_glob(surface, &mod_path, target_id);
307 } else if let Some(name) = use_["name"].as_str() {
308 links.alias(surface, &mod_path, name, target_id);
309 }
310 }
311 }
312}
313
314struct Links<'a> {
317 index: &'a serde_json::Map<String, Value>,
318 paths: &'a serde_json::Map<String, Value>,
319 crates: &'a Value,
320 dependencies: &'a BTreeMap<String, Surface>,
321}
322
323impl Links<'_> {
324 fn external(&self, id: u64) -> Option<(&Surface, String)> {
327 let id = id.to_string();
328 if self.index.contains_key(&id) {
329 return None;
330 }
331 let crate_id = self.paths.get(&id)?["crate_id"].as_u64()?;
332 let name = self.crates[crate_id.to_string()]["name"].as_str()?;
333 Some((self.dependencies.get(name)?, item_path(self.paths, &id)?))
334 }
335
336 fn alias(&self, surface: &mut Surface, mod_path: &str, name: &str, target_id: u64) {
337 match self.external(target_id) {
338 Some((dep, from)) => {
339 alias_external(dep, &from, &format!("{mod_path}::{name}"), false, surface)
340 }
341 None => alias_one(self.paths, surface, mod_path, name, target_id),
342 }
343 }
344
345 fn alias_glob(&self, surface: &mut Surface, mod_path: &str, module_id: u64) {
348 if let Some((dep, from)) = self.external(module_id) {
349 return alias_external(dep, &from, mod_path, true, surface);
350 }
351 let Some(children) = self
352 .index
353 .get(&module_id.to_string())
354 .and_then(|m| m["inner"]["module"]["items"].as_array())
355 else {
356 return;
357 };
358 for id in children.iter().filter_map(Value::as_u64) {
359 let Some(child) = self.index.get(&id.to_string()) else {
360 continue;
361 };
362 let use_ = &child["inner"]["use"];
363 match (use_["id"].as_u64(), use_["is_glob"].as_bool()) {
364 (Some(target), Some(true)) => {
366 if let Some((dep, from)) = self.external(target) {
367 alias_external(dep, &from, mod_path, true, surface);
368 }
369 }
370 (Some(target), _) => {
371 if let Some(name) = use_["name"].as_str() {
372 self.alias(surface, mod_path, name, target);
373 }
374 }
375 (None, _) => {
376 if let Some(name) = child["name"].as_str() {
377 alias_one(self.paths, surface, mod_path, name, id);
378 }
379 }
380 }
381 }
382 }
383}
384
385fn alias_one(
390 paths: &serde_json::Map<String, Value>,
391 surface: &mut Surface,
392 mod_path: &str,
393 name: &str,
394 target_id: u64,
395) {
396 let Some(target_path) = item_path(paths, &target_id.to_string()) else {
397 return;
398 };
399 let Some(info) = surface.items.get(&target_path).cloned() else {
400 return; };
402 let alias = format!("{mod_path}::{name}");
403 if alias == target_path {
404 return;
405 }
406 surface.items.entry(alias).or_insert(info);
407}
408
409fn alias_external(dep: &Surface, from: &str, to: &str, glob: bool, surface: &mut Surface) {
413 let below = |entries: &BTreeMap<String, ItemInfo>| -> Vec<(String, ItemInfo)> {
414 entries
415 .iter()
416 .filter_map(|(path, info)| {
417 let rest = path.strip_prefix(from)?;
418 let taken = rest.starts_with("::") || (rest.is_empty() && !glob);
419 taken.then(|| (format!("{to}{rest}"), info.clone()))
420 })
421 .collect()
422 };
423 for (path, info) in below(&dep.items) {
424 surface.items.entry(path).or_insert(info);
425 }
426 for (path, info) in below(&dep.members) {
427 surface.members.entry(path).or_insert(info);
428 }
429}
430
431fn item_path(paths: &serde_json::Map<String, Value>, id: &str) -> Option<String> {
432 let segs = paths.get(id)?["path"].as_array()?;
433 Some(
434 segs.iter()
435 .filter_map(Value::as_str)
436 .collect::<Vec<_>>()
437 .join("::"),
438 )
439}
440
441const MEMBER_KINDS: [&str; 3] = ["struct", "enum", "union"];
445
446fn item_fingerprint(
447 index: &serde_json::Map<String, Value>,
448 item: &Value,
449 kind: &str,
450 root: &Path,
451 cache: &mut HashMap<String, Vec<String>>,
452) -> Option<(u64, String)> {
453 let span_text = read_span(&item["span"], root, cache)?;
454 let bare = normalize(&crate::comments::strip_all(&span_text));
455 let name = item["name"].as_str().unwrap_or_default();
456 if !generated::is_macro_call(&bare[..declaration_end(&bare)], name, kind) {
457 return Some(text_fingerprint(&span_text, kind));
458 }
459 let declaration = generated::declaration(index, item, kind, false);
460 let docs = item["docs"].as_str().unwrap_or_default();
461 Some((
462 generated::fingerprint(&declaration, docs),
463 generated::declaration(index, item, kind, true),
464 ))
465}
466
467fn declaration_end(bare: &str) -> usize {
468 bare.find('{')
469 .or_else(|| bare.find(';'))
470 .unwrap_or(bare.len())
471}
472
473fn read_span(
474 span: &Value,
475 root: &Path,
476 cache: &mut HashMap<String, Vec<String>>,
477) -> Option<String> {
478 let filename = span["filename"].as_str()?;
479 let begin = span["begin"].as_array()?;
480 let end = span["end"].as_array()?;
481 let (bl, el) = (begin[0].as_u64()? as usize, end[0].as_u64()? as usize);
482
483 let lines = match cache.get(filename) {
484 Some(l) => l,
485 None => {
486 let abs = root.join(filename);
489 let text = std::fs::read_to_string(&abs).ok()?;
490 cache.insert(
491 filename.to_string(),
492 text.lines().map(str::to_string).collect(),
493 );
494 &cache[filename]
495 }
496 };
497 if bl == 0 || el > lines.len() || bl > el {
498 return None;
499 }
500 Some(lines[bl - 1..el].join("\n"))
501}
502
503fn text_fingerprint(span_text: &str, kind: &str) -> (u64, String) {
504 let normalized = normalize(&crate::comments::strip(span_text));
505 let bare = normalize(&crate::comments::strip_all(span_text));
508 let sig_end = declaration_end(&bare);
509 let declaration = bare[..sig_end].trim();
510 let signature = if MEMBER_KINDS.contains(&kind) {
511 member_signature(declaration, &bare[sig_end..], kind == "enum")
512 } else {
513 declaration.to_string()
514 };
515 (soothfast_registry::fnv1a(normalized.as_bytes()), signature)
516}
517
518fn normalize(source: &str) -> String {
519 source.split_whitespace().collect::<Vec<_>>().join(" ")
520}
521
522fn member_signature(declaration: &str, rest: &str, all_public: bool) -> String {
526 let Some(body) = rest
527 .strip_prefix('{')
528 .and_then(|inner| inner.trim_end().strip_suffix('}'))
529 else {
530 return declaration.to_string();
531 };
532 let members: Vec<String> = split_top_level(body)
533 .into_iter()
534 .map(|member| strip_attributes(member.trim()).to_string())
535 .filter(|member| !member.is_empty() && (all_public || member.starts_with("pub ")))
536 .collect();
537 format!("{declaration} {{ {} }}", members.join(", "))
538}
539
540fn split_top_level(text: &str) -> Vec<&str> {
543 let mut parts = Vec::new();
544 let mut depth = 0i32;
545 let mut start = 0;
546 let mut prev = ' ';
547 for (i, c) in text.char_indices() {
548 match c {
549 '<' | '(' | '[' | '{' => depth += 1,
550 '>' if prev == '-' => {}
551 '>' | ')' | ']' | '}' => depth -= 1,
552 ',' if depth == 0 => {
553 parts.push(&text[start..i]);
554 start = i + 1;
555 }
556 _ => {}
557 }
558 prev = c;
559 }
560 parts.push(&text[start..]);
561 parts
562}
563
564fn strip_attributes(member: &str) -> &str {
567 let mut rest = member;
568 while let Some(after) = rest.strip_prefix("#[") {
569 let mut depth = 1;
570 let mut end = None;
571 for (i, c) in after.char_indices() {
572 depth += match c {
573 '[' => 1,
574 ']' => -1,
575 _ => 0,
576 };
577 if depth == 0 {
578 end = Some(i + 1);
579 break;
580 }
581 }
582 match end {
583 Some(e) => rest = after[e..].trim_start(),
584 None => break,
585 }
586 }
587 rest
588}
589
590#[cfg(test)]
591mod tests {
592 use super::*;
593 use serde_json::json;
594
595 fn private_submodule_reexport_doc() -> Value {
598 json!({
599 "index": {
600 "1": {
601 "visibility": "public",
602 "inner": { "module": { "items": [2, 3] } },
603 },
604 "2": {
605 "name": "sma",
606 "visibility": "public",
607 "inner": { "function": {} },
608 "span": { "filename": "src/sma.rs", "begin": [1, 0], "end": [1, 0] },
609 "docs": "Simple moving average.",
610 },
611 "3": {
612 "visibility": "public",
613 "inner": {
614 "use": { "source": "sma::sma", "name": "sma", "id": 2, "is_glob": false },
615 },
616 },
617 },
618 "paths": {
619 "1": { "path": ["myc", "indicators"], "kind": "module" },
620 "2": { "path": ["myc", "indicators", "sma", "sma"], "kind": "function" },
621 },
622 })
623 }
624
625 #[test]
626 fn reexport_alias_resolves_alongside_canonical_path() {
627 let dir =
628 std::env::temp_dir().join(format!("soothfast-surface-test-{}", std::process::id()));
629 std::fs::create_dir_all(dir.join("src")).unwrap();
630 std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
631
632 let doc = private_submodule_reexport_doc();
633 let surface = from_rustdoc(&doc, &dir);
634
635 assert!(surface.items.contains_key("myc::indicators::sma::sma"));
636 assert!(
637 surface.items.contains_key("myc::indicators::sma"),
638 "expected the flattened re-export path to resolve too: {:?}",
639 surface.items.keys().collect::<Vec<_>>()
640 );
641 let canonical = &surface.items["myc::indicators::sma::sma"];
642 let alias = &surface.items["myc::indicators::sma"];
643 assert_eq!(canonical.fingerprint, alias.fingerprint);
644 assert_eq!(alias.kind, "function");
645
646 let _ = std::fs::remove_dir_all(&dir);
647 }
648
649 #[test]
650 fn glob_reexport_aliases_every_child_by_its_own_name() {
651 let mut doc = private_submodule_reexport_doc();
653 doc["index"]["3"]["inner"]["use"] =
654 json!({ "source": "sma", "name": "sma", "id": 7, "is_glob": true });
655 doc["index"]["7"] = json!({
656 "visibility": "public",
657 "inner": { "module": { "items": [2] } },
658 });
659
660 let dir =
661 std::env::temp_dir().join(format!("soothfast-surface-glob-{}", std::process::id()));
662 std::fs::create_dir_all(dir.join("src")).unwrap();
663 std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
664
665 let surface = from_rustdoc(&doc, &dir);
666 assert!(surface.items.contains_key("myc::indicators::sma::sma"));
667 assert!(surface.items.contains_key("myc::indicators::sma"));
668
669 let _ = std::fs::remove_dir_all(&dir);
670 }
671
672 fn impl_doc() -> Value {
673 let span =
674 |line: u64| json!({ "filename": "src/lib.rs", "begin": [line, 0], "end": [line, 0] });
675 json!({
676 "index": {
677 "1": { "visibility": "public", "inner": { "module": { "items": [2, 20] } } },
678 "2": {
679 "name": "Rewriter",
680 "visibility": "public",
681 "inner": { "struct": {} },
682 "span": span(1),
683 },
684 "3": {
685 "visibility": "default",
686 "inner": { "impl": {
687 "trait": null,
688 "for": { "resolved_path": { "id": 2 } },
689 "items": [4, 5, 6],
690 } },
691 },
692 "4": {
693 "name": "rewrite",
694 "visibility": "public",
695 "inner": { "function": {} },
696 "span": span(2),
697 },
698 "5": {
699 "name": "hidden",
700 "visibility": "default",
701 "inner": { "function": {} },
702 "span": span(3),
703 },
704 "6": {
705 "name": "LIMIT",
706 "visibility": "public",
707 "inner": { "assoc_const": {} },
708 "span": span(4),
709 },
710 "8": {
711 "visibility": "default",
712 "inner": { "impl": {
713 "trait": { "path": "Default" },
714 "for": { "resolved_path": { "id": 2 } },
715 "items": [7],
716 } },
717 },
718 "7": {
719 "name": "default",
720 "visibility": "public",
721 "inner": { "function": {} },
722 "span": span(5),
723 },
724 "20": {
725 "visibility": "public",
726 "inner": { "use": { "name": "Rewriter", "id": 2, "is_glob": false } },
727 },
728 },
729 "paths": {
730 "1": { "path": ["rw"], "kind": "module" },
731 "2": { "path": ["rw", "engine", "Rewriter"], "kind": "struct" },
732 },
733 })
734 }
735
736 #[test]
737 fn inherent_pub_members_resolve_under_the_type_path() {
738 let dir =
739 std::env::temp_dir().join(format!("soothfast-surface-impl-{}", std::process::id()));
740 std::fs::create_dir_all(dir.join("src")).unwrap();
741 std::fs::write(
742 dir.join("src/lib.rs"),
743 "pub struct Rewriter;\n pub fn rewrite() {}\n fn hidden() {}\n pub const LIMIT: u8 = 1;\n fn default() {}\n",
744 )
745 .unwrap();
746
747 let surface = from_rustdoc(&impl_doc(), &dir);
748
749 let method = surface.lookup("rw::engine::Rewriter::rewrite").unwrap();
750 assert_eq!(method.kind, "function");
751 assert_ne!(method.fingerprint, 0);
752 assert_eq!(
753 surface.lookup("rw::engine::Rewriter::LIMIT").unwrap().kind,
754 "constant"
755 );
756 assert!(surface.lookup("rw::engine::Rewriter::hidden").is_none());
757 assert!(surface.lookup("rw::engine::Rewriter::default").is_none());
758 assert!(surface.items.keys().all(|k| !k.ends_with("::rewrite")));
759 assert_eq!(
760 surface.lookup("rw::Rewriter::rewrite").unwrap().fingerprint,
761 method.fingerprint
762 );
763
764 let _ = std::fs::remove_dir_all(&dir);
765 }
766
767 fn item(kind: &str, fingerprint: u64) -> ItemInfo {
768 ItemInfo {
769 kind: kind.to_string(),
770 fingerprint,
771 signature: String::new(),
772 has_docs: false,
773 }
774 }
775
776 fn surface_of(items: Vec<(&str, ItemInfo)>) -> Surface {
777 Surface {
778 items: items.into_iter().map(|(p, i)| (p.to_string(), i)).collect(),
779 ..Surface::default()
780 }
781 }
782
783 fn facade_doc() -> Value {
784 let use_ = |name: &str, id: u64, is_glob: bool| {
785 json!({
786 "visibility": "public",
787 "inner": { "use": { "name": name, "id": id, "is_glob": is_glob } },
788 })
789 };
790 json!({
791 "index": {
792 "1": { "visibility": "public", "inner": { "module": { "items": [2, 3, 4, 5, 8, 9] } } },
793 "2": use_("named", 20, false),
794 "3": use_("indicators", 21, false),
795 "4": use_("prelude", 22, true),
796 "5": use_("Counter", 23, false),
797 "6": { "visibility": "default", "inner": { "module": { "items": [7] } } },
798 "7": use_("Two", 24, false),
799 "8": use_("inner", 6, true),
800 "9": use_("fmt", 30, false),
801 },
802 "paths": {
803 "1": { "crate_id": 0, "path": ["a"], "kind": "module" },
804 "6": { "crate_id": 0, "path": ["a", "inner"], "kind": "module" },
805 "20": { "crate_id": 1, "path": ["b", "named"], "kind": "function" },
806 "21": { "crate_id": 1, "path": ["b", "indicators"], "kind": "module" },
807 "22": { "crate_id": 1, "path": ["b", "prelude"], "kind": "module" },
808 "23": { "crate_id": 1, "path": ["b", "Counter"], "kind": "struct" },
809 "24": { "crate_id": 1, "path": ["b", "Two"], "kind": "struct" },
810 "30": { "crate_id": 2, "path": ["std", "fmt"], "kind": "module" },
811 },
812 "external_crates": { "1": { "name": "b" }, "2": { "name": "std" } },
813 })
814 }
815
816 fn documented(kind: &str, fingerprint: u64) -> ItemInfo {
817 ItemInfo {
818 has_docs: true,
819 ..item(kind, fingerprint)
820 }
821 }
822
823 fn dependency_b() -> BTreeMap<String, Surface> {
824 let mut b = surface_of(vec![
825 ("b", item("module", 1)),
826 ("b::named", documented("function", 2)),
827 ("b::indicators", item("module", 3)),
828 ("b::indicators::sma", documented("function", 4)),
829 ("b::prelude", item("module", 5)),
830 ("b::prelude::one", documented("function", 6)),
831 ("b::Counter", documented("struct", 7)),
832 ("b::Two", item("struct", 8)),
833 ]);
834 b.members
835 .insert("b::Counter::new".to_string(), documented("function", 9));
836 BTreeMap::from([("b".to_string(), b)])
837 }
838
839 #[test]
840 fn a_reexport_from_another_crate_takes_the_defining_crates_info() {
841 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
842
843 let named = &surface.items["a::named"];
844 assert_eq!((named.kind.as_str(), named.fingerprint), ("function", 2));
845 assert!(named.has_docs);
846 assert_eq!(surface.items["a::Counter"].fingerprint, 7);
847 assert_eq!(surface.members["a::Counter::new"].fingerprint, 9);
848 assert!(surface.lookup("a::Counter::new").unwrap().has_docs);
849 assert!(surface.items.keys().all(|k| !k.starts_with("b::")));
850 assert!(surface.members.keys().all(|k| !k.starts_with("b::")));
851 }
852
853 #[test]
854 fn a_reexported_module_brings_what_is_below_it() {
855 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
856 assert_eq!(surface.items["a::indicators"].kind, "module");
857 assert_eq!(surface.items["a::indicators::sma"].fingerprint, 4);
858 }
859
860 #[test]
861 fn a_glob_of_another_crates_module_takes_its_children_not_the_module() {
862 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
863 assert_eq!(surface.items["a::one"].fingerprint, 6);
864 assert!(!surface.items.contains_key("a::prelude"));
865 }
866
867 #[test]
868 fn a_glob_of_a_local_module_takes_its_named_reexports() {
869 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
870 assert_eq!(surface.items["a::Two"].fingerprint, 8);
871 }
872
873 #[test]
874 fn a_glob_of_a_local_module_takes_a_local_named_reexport_once() {
875 let mut doc = private_submodule_reexport_doc();
877 doc["index"]["1"]["inner"]["module"]["items"] = json!([2, 3, 8]);
878 doc["index"]["7"] = json!({
879 "visibility": "default",
880 "inner": { "module": { "items": [9] } },
881 });
882 doc["index"]["8"] = json!({
883 "visibility": "public",
884 "inner": { "use": { "name": "inner", "id": 7, "is_glob": true } },
885 });
886 doc["index"]["9"] = json!({
887 "visibility": "public",
888 "inner": { "use": { "name": "average", "id": 2, "is_glob": false } },
889 });
890 let dir =
891 std::env::temp_dir().join(format!("soothfast-surface-inner-{}", std::process::id()));
892 std::fs::create_dir_all(dir.join("src")).unwrap();
893 std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
894
895 let surface = from_rustdoc(&doc, &dir);
896 let alias = &surface.items["myc::indicators::average"];
897 assert_eq!(
898 alias.fingerprint,
899 surface.items["myc::indicators::sma"].fingerprint
900 );
901 let functions: Vec<_> = surface
902 .grouped()
903 .into_iter()
904 .filter(|g| surface.items[g.representative].kind == "function")
905 .collect();
906 assert_eq!(functions.len(), 1);
907
908 let _ = std::fs::remove_dir_all(&dir);
909 }
910
911 #[test]
912 fn a_crate_without_a_known_surface_stays_unresolved() {
913 let surface = from_rustdoc(&facade_doc(), Path::new("."));
914 assert_eq!(surface.items.keys().collect::<Vec<_>>(), ["a"]);
915 }
916
917 #[test]
918 fn reexported_crates_names_each_crate_a_pub_use_reaches() {
919 let crates = reexported_crates(&facade_doc());
920 assert_eq!(crates.into_iter().collect::<Vec<_>>(), ["b", "std"]);
921 assert!(reexported_crates(&impl_doc()).is_empty());
922 }
923
924 #[test]
925 fn three_aliases_of_one_function_collapse_to_one_group() {
926 let surf = surface_of(vec![
927 ("myc::atr", item("function", 42)),
928 ("myc::indicators::atr", item("function", 42)),
929 ("myc::indicators::atr::atr", item("function", 42)),
930 ]);
931 let groups = surf.grouped();
932 assert_eq!(groups.len(), 1);
933 assert_eq!(groups[0].representative, "myc::atr");
934 assert_eq!(groups[0].aliases.len(), 3);
935 }
936
937 #[test]
938 fn covers_tag_on_a_longer_alias_still_counts_as_measured() {
939 let surf = surface_of(vec![
943 ("myc::atr", item("function", 42)),
944 ("myc::indicators::atr", item("function", 42)),
945 ]);
946 let g = &surf.grouped()[0];
947 assert!(
948 g.aliases
949 .iter()
950 .any(|a| a.as_str() == "myc::indicators::atr")
951 );
952 }
953
954 #[test]
955 fn distinct_functions_with_no_fingerprint_are_never_merged() {
956 let surf = surface_of(vec![
957 ("myc::a", item("function", 0)),
958 ("myc::b", item("function", 0)),
959 ]);
960 assert_eq!(surf.grouped().len(), 2);
961 }
962
963 #[test]
964 fn different_kinds_with_the_same_fingerprint_are_not_merged() {
965 let surf = surface_of(vec![
966 ("myc::a", item("function", 7)),
967 ("myc::A", item("struct", 7)),
968 ]);
969 assert_eq!(surf.grouped().len(), 2);
970 }
971
972 fn fingerprint_of(tag: &str, source: &str) -> (u64, String) {
973 fingerprint_of_kind(tag, "struct", source)
974 }
975
976 fn fingerprint_of_kind(tag: &str, kind: &str, source: &str) -> (u64, String) {
977 let dir = std::env::temp_dir().join(format!(
978 "soothfast-fingerprint-{}-{tag}",
979 std::process::id()
980 ));
981 std::fs::create_dir_all(&dir).unwrap();
982 std::fs::write(dir.join("lib.rs"), source).unwrap();
983 let span = json!({
984 "filename": "lib.rs",
985 "begin": [1, 0],
986 "end": [source.lines().count(), 0],
987 });
988 let text = read_span(&span, &dir, &mut HashMap::new()).unwrap();
989 let got = text_fingerprint(&text, kind);
990 let _ = std::fs::remove_dir_all(&dir);
991 got
992 }
993
994 #[test]
995 fn a_comment_only_edit_does_not_move_the_fingerprint() {
996 let plain = fingerprint_of("plain", "pub struct S {\n a: u8,\n}\n");
997 let noted = fingerprint_of(
998 "noted",
999 "pub struct S {\n // widened for the wire format\n a: u8,\n}\n",
1000 );
1001 assert_eq!(plain.0, noted.0);
1002 }
1003
1004 #[test]
1005 fn a_field_change_still_moves_the_fingerprint() {
1006 let before = fingerprint_of("before", "pub struct S {\n a: u8,\n}\n");
1007 let after = fingerprint_of("after", "pub struct S {\n a: u16,\n}\n");
1008 assert_ne!(before.0, after.0);
1009 }
1010
1011 #[test]
1012 fn a_struct_field_addition_changes_the_signature() {
1013 let before = fingerprint_of_kind(
1014 "sig-before",
1015 "struct",
1016 "pub struct S {\n pub a: u8,\n}\n",
1017 );
1018 let after = fingerprint_of_kind(
1019 "sig-after",
1020 "struct",
1021 "pub struct S {\n pub a: u8,\n pub b: u8,\n}\n",
1022 );
1023 assert_ne!(before.1, after.1);
1024 assert_eq!(after.1, "pub struct S { pub a: u8, pub b: u8 }");
1025 }
1026
1027 #[test]
1028 fn a_private_field_edit_is_body_only() {
1029 let before = fingerprint_of_kind(
1030 "priv-before",
1031 "struct",
1032 "pub struct S {\n pub a: u8,\n b: u8,\n}\n",
1033 );
1034 let after = fingerprint_of_kind(
1035 "priv-after",
1036 "struct",
1037 "pub struct S {\n pub a: u8,\n b: u16,\n c: u8,\n}\n",
1038 );
1039 assert_ne!(before.0, after.0);
1040 assert_eq!(before.1, after.1);
1041 assert_eq!(before.1, "pub struct S { pub a: u8 }");
1042 }
1043
1044 #[test]
1045 fn generic_fields_and_attributes_are_read_as_members() {
1046 let got = fingerprint_of_kind(
1047 "generic",
1048 "struct",
1049 "pub struct S {\n #[serde(rename = \"m\")]\n pub map: HashMap<String, Vec<u8>>,\n pub(crate) hidden: u8,\n}\n",
1050 );
1051 assert_eq!(got.1, "pub struct S { pub map: HashMap<String, Vec<u8>> }");
1052 }
1053
1054 #[test]
1055 fn a_documented_public_field_counts_as_signature() {
1056 let before = fingerprint_of_kind(
1057 "pubdoc-before",
1058 "struct",
1059 "pub struct S {\n /// count\n pub a: u8,\n}\n",
1060 );
1061 let after = fingerprint_of_kind(
1062 "pubdoc-after",
1063 "struct",
1064 "pub struct S {\n /// count\n pub a: u8,\n /// total\n pub b: u8,\n}\n",
1065 );
1066 assert_ne!(before.1, after.1);
1067 assert_eq!(after.1, "pub struct S { pub a: u8, pub b: u8 }");
1068 }
1069
1070 #[test]
1071 fn a_variant_doc_edit_moves_the_fingerprint_but_not_the_signature() {
1072 let before = fingerprint_of_kind(
1073 "vdoc-before",
1074 "enum",
1075 "pub enum E {\n /// first\n A,\n B,\n}\n",
1076 );
1077 let after = fingerprint_of_kind(
1078 "vdoc-after",
1079 "enum",
1080 "pub enum E {\n /// the first\n A,\n B,\n}\n",
1081 );
1082 assert_ne!(before.0, after.0);
1083 assert_eq!(before.1, after.1);
1084 assert_eq!(before.1, "pub enum E { A, B }");
1085 }
1086
1087 #[test]
1088 fn a_function_pointer_field_does_not_swallow_its_neighbours() {
1089 let got = fingerprint_of_kind(
1090 "fnptr",
1091 "struct",
1092 "pub struct S {\n pub f: fn(u8) -> u8,\n pub g: u8,\n}\n",
1093 );
1094 assert_eq!(got.1, "pub struct S { pub f: fn(u8) -> u8, pub g: u8 }");
1095 }
1096
1097 #[test]
1098 fn an_enum_variant_addition_changes_the_signature() {
1099 let before = fingerprint_of_kind("var-before", "enum", "pub enum E {\n A,\n}\n");
1100 let after = fingerprint_of_kind("var-after", "enum", "pub enum E {\n A,\n B,\n}\n");
1101 assert_ne!(before.1, after.1);
1102 }
1103
1104 #[test]
1105 fn a_function_body_edit_keeps_its_signature() {
1106 let before = fingerprint_of_kind("fn-before", "function", "pub fn f() -> u8 {\n 1\n}\n");
1107 let after = fingerprint_of_kind("fn-after", "function", "pub fn f() -> u8 {\n 2\n}\n");
1108 assert_ne!(before.0, after.0);
1109 assert_eq!(before.1, after.1);
1110 assert_eq!(before.1, "pub fn f() -> u8");
1111 }
1112
1113 #[test]
1114 fn a_doc_comment_on_a_field_is_part_of_the_fingerprint() {
1115 let before = fingerprint_of(
1116 "doc-before",
1117 "pub struct S {\n /// count\n a: u8,\n}\n",
1118 );
1119 let after = fingerprint_of(
1120 "doc-after",
1121 "pub struct S {\n /// total\n a: u8,\n}\n",
1122 );
1123 assert_ne!(before.0, after.0);
1124 }
1125}