1use std::collections::{BTreeMap, BTreeSet, HashMap};
12use std::path::Path;
13
14use serde_json::Value;
15
16mod counted;
17mod generated;
18#[cfg(test)]
19mod generated_tests;
20
21pub use counted::Counted;
22
23#[derive(Debug, Clone)]
27pub struct ItemInfo {
28 pub kind: String,
30 pub fingerprint: u64,
32 pub signature: String,
36 pub has_docs: bool,
38 pub example: bool,
40 pub spans: Vec<Span>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Span {
49 pub file: String,
51 pub begin: u32,
53 pub end: u32,
55}
56
57#[derive(Debug, Default)]
59pub struct Surface {
60 pub items: BTreeMap<String, ItemInfo>,
61 pub members: BTreeMap<String, ItemInfo>,
66}
67
68pub struct ItemGroup<'a> {
74 pub representative: &'a String,
75 pub aliases: Vec<&'a String>,
76}
77
78impl Surface {
79 pub fn lookup(&self, path: &str) -> Option<&ItemInfo> {
81 self.items.get(path).or_else(|| self.members.get(path))
82 }
83
84 pub fn grouped(&self) -> Vec<ItemGroup<'_>> {
86 let mut groups: HashMap<(&str, u64), Vec<&String>> = HashMap::new();
87 let mut unfingerprinted = Vec::new();
88 for (path, info) in &self.items {
89 if info.fingerprint == 0 {
90 unfingerprinted.push(path);
91 continue;
92 }
93 groups
94 .entry((info.kind.as_str(), info.fingerprint))
95 .or_default()
96 .push(path);
97 }
98 let mut out: Vec<ItemGroup<'_>> = groups
99 .into_values()
100 .map(|mut aliases| {
101 aliases.sort();
102 let representative = aliases.iter().min_by_key(|p| p.len()).copied().unwrap();
103 ItemGroup {
104 representative,
105 aliases,
106 }
107 })
108 .chain(unfingerprinted.into_iter().map(|p| ItemGroup {
109 representative: p,
110 aliases: vec![p],
111 }))
112 .collect();
113 out.sort_by(|a, b| a.representative.cmp(b.representative));
114 out
115 }
116}
117
118const KINDS: &[&str] = &[
120 "function",
121 "struct",
122 "enum",
123 "trait",
124 "constant",
125 "type_alias",
126 "module",
127 "static",
128 "union",
129 "macro",
130 "proc_macro",
131];
132
133pub fn from_rustdoc(doc: &Value, source_root: &Path) -> Surface {
136 from_rustdoc_with(doc, source_root, &BTreeMap::new())
137}
138
139pub fn from_rustdoc_with(
149 doc: &Value,
150 source_root: &Path,
151 dependencies: &BTreeMap<String, Surface>,
152) -> Surface {
153 let mut surface = Surface::default();
154 let (Some(index), Some(paths)) = (doc["index"].as_object(), doc["paths"].as_object()) else {
155 return surface;
156 };
157 let mut file_cache: HashMap<String, Vec<String>> = HashMap::new();
158 let impl_spans = impl_method_spans(index);
159
160 for (id, item) in index {
161 if item["visibility"] != "public" {
162 continue;
163 }
164 let Some(inner) = item["inner"].as_object() else {
165 continue;
166 };
167 let Some(kind) = inner.keys().next().map(String::as_str) else {
168 continue;
169 };
170 if !KINDS.contains(&kind) {
171 continue;
172 }
173 let Some(full) = item_path(paths, id) else {
175 continue;
176 };
177
178 let (fingerprint, signature) =
179 item_fingerprint(index, item, kind, source_root, &mut file_cache)
180 .unwrap_or((0, String::new()));
181 let docs = item["docs"].as_str().unwrap_or_default();
182 let spans = item_spans(item, id, kind, &impl_spans);
183
184 surface.items.insert(
185 full,
186 ItemInfo {
187 kind: kind.to_string(),
188 fingerprint,
189 signature,
190 has_docs: !docs.trim().is_empty(),
191 example: has_example(docs),
192 spans,
193 },
194 );
195 }
196
197 let links = Links {
198 index,
199 paths,
200 crates: &doc["external_crates"],
201 dependencies,
202 };
203 alias_reexports(&links, &mut surface);
204 index_members(index, paths, source_root, &mut file_cache, &mut surface);
205 surface
206}
207
208fn span_of(item: &Value) -> Option<Span> {
209 let span = &item["span"];
210 Some(Span {
211 file: span["filename"].as_str()?.to_string(),
212 begin: u32::try_from(span["begin"][0].as_u64()?).ok()?,
213 end: u32::try_from(span["end"][0].as_u64()?).ok()?,
214 })
215}
216
217const IMPLEMENTED_KINDS: [&str; 4] = ["struct", "enum", "union", "trait"];
219
220fn item_spans(
221 item: &Value,
222 id: &str,
223 kind: &str,
224 impl_spans: &HashMap<String, Vec<Span>>,
225) -> Vec<Span> {
226 let mut spans: Vec<Span> = span_of(item).into_iter().collect();
227 if IMPLEMENTED_KINDS.contains(&kind) {
228 spans.extend(impl_spans.get(id).into_iter().flatten().cloned());
229 }
230 spans
231}
232
233fn impl_method_spans(index: &serde_json::Map<String, Value>) -> HashMap<String, Vec<Span>> {
236 let mut by_type: HashMap<String, Vec<Span>> = HashMap::new();
237 for item in index.values() {
238 let imp = &item["inner"]["impl"];
239 let Some(type_id) = imp["for"]["resolved_path"]["id"].as_u64() else {
240 continue;
241 };
242 let methods = imp["items"]
243 .as_array()
244 .into_iter()
245 .flatten()
246 .filter_map(|id| index.get(&id.as_u64()?.to_string()))
247 .filter(|member| member["inner"]["function"].is_object())
248 .filter_map(span_of);
249 by_type
250 .entry(type_id.to_string())
251 .or_default()
252 .extend(methods);
253 }
254 by_type
255}
256
257fn has_example(docs: &str) -> bool {
258 crate::markdown::scan(docs).is_ok_and(|doc| doc.blocks.iter().any(|b| b.is_rust_example()))
259}
260
261pub fn reexported_crates(doc: &Value) -> BTreeSet<String> {
264 let (Some(index), Some(paths)) = (doc["index"].as_object(), doc["paths"].as_object()) else {
265 return BTreeSet::new();
266 };
267 index
268 .values()
269 .filter(|item| item["visibility"] == "public")
270 .filter_map(|item| item["inner"]["use"]["id"].as_u64())
271 .filter(|id| !index.contains_key(&id.to_string()))
272 .filter_map(|id| {
273 let crate_id = paths.get(&id.to_string())?["crate_id"].as_u64()?;
274 let name = doc["external_crates"][crate_id.to_string()]["name"].as_str()?;
275 Some(name.to_string())
276 })
277 .collect()
278}
279
280fn index_members(
283 index: &serde_json::Map<String, Value>,
284 paths: &serde_json::Map<String, Value>,
285 source_root: &Path,
286 file_cache: &mut HashMap<String, Vec<String>>,
287 surface: &mut Surface,
288) {
289 for item in index.values() {
290 let imp = &item["inner"]["impl"];
291 if !imp.is_object() || imp["trait"].is_object() {
292 continue;
293 }
294 let Some(type_id) = imp["for"]["resolved_path"]["id"].as_u64() else {
295 continue;
296 };
297 let Some(type_path) = item_path(paths, &type_id.to_string()) else {
298 continue;
299 };
300 let Some(owner) = surface.items.get(&type_path) else {
301 continue;
302 };
303 let spellings: Vec<String> = surface
304 .items
305 .iter()
306 .filter(|(_, info)| info.kind == owner.kind && info.fingerprint == owner.fingerprint)
307 .map(|(path, _)| path.clone())
308 .collect();
309
310 let members = imp["items"].as_array().into_iter().flatten();
311 for member in members.filter_map(|id| index.get(&id.as_u64()?.to_string())) {
312 if member["visibility"] != "public" {
313 continue;
314 }
315 let (kind, name) = match (
316 member["inner"]["function"].is_object(),
317 member["inner"]["assoc_const"].is_object(),
318 member["name"].as_str(),
319 ) {
320 (true, _, Some(name)) => ("function", name),
321 (_, true, Some(name)) => ("constant", name),
322 _ => continue,
323 };
324 let (fingerprint, signature) =
325 item_fingerprint(index, member, kind, source_root, file_cache)
326 .unwrap_or((0, String::new()));
327 let docs = member["docs"].as_str().unwrap_or_default();
328 let info = ItemInfo {
329 kind: kind.to_string(),
330 fingerprint,
331 signature,
332 has_docs: !docs.trim().is_empty(),
333 example: has_example(docs),
334 spans: span_of(member).into_iter().collect(),
335 };
336 for spelling in &spellings {
337 surface
338 .members
339 .insert(format!("{spelling}::{name}"), info.clone());
340 }
341 }
342 }
343}
344
345fn alias_reexports(links: &Links<'_>, surface: &mut Surface) {
357 for (mod_id, item) in links.index {
358 if item["visibility"] != "public" {
359 continue;
360 }
361 let Some(children) = item["inner"]["module"]["items"].as_array() else {
362 continue;
363 };
364 let Some(mod_path) = item_path(links.paths, mod_id) else {
365 continue;
366 };
367
368 for child in children {
369 let Some(child_id) = child.as_u64() else {
370 continue;
371 };
372 let child_id = child_id.to_string();
373 let Some(use_) = links.index.get(&child_id).map(|c| &c["inner"]["use"]) else {
374 continue;
375 };
376 let Some(target_id) = use_["id"].as_u64() else {
377 continue;
378 };
379 if use_["is_glob"].as_bool().unwrap_or(false) {
385 links.alias_glob(surface, &mod_path, target_id);
386 } else if let Some(name) = use_["name"].as_str() {
387 links.alias(surface, &mod_path, name, target_id);
388 }
389 }
390 }
391}
392
393struct Links<'a> {
396 index: &'a serde_json::Map<String, Value>,
397 paths: &'a serde_json::Map<String, Value>,
398 crates: &'a Value,
399 dependencies: &'a BTreeMap<String, Surface>,
400}
401
402impl Links<'_> {
403 fn external(&self, id: u64) -> Option<(&Surface, String)> {
406 let id = id.to_string();
407 if self.index.contains_key(&id) {
408 return None;
409 }
410 let crate_id = self.paths.get(&id)?["crate_id"].as_u64()?;
411 let name = self.crates[crate_id.to_string()]["name"].as_str()?;
412 Some((self.dependencies.get(name)?, item_path(self.paths, &id)?))
413 }
414
415 fn alias(&self, surface: &mut Surface, mod_path: &str, name: &str, target_id: u64) {
416 match self.external(target_id) {
417 Some((dep, from)) => {
418 alias_external(dep, &from, &format!("{mod_path}::{name}"), false, surface)
419 }
420 None => alias_one(self.paths, surface, mod_path, name, target_id),
421 }
422 }
423
424 fn alias_glob(&self, surface: &mut Surface, mod_path: &str, module_id: u64) {
427 if let Some((dep, from)) = self.external(module_id) {
428 return alias_external(dep, &from, mod_path, true, surface);
429 }
430 let Some(children) = self
431 .index
432 .get(&module_id.to_string())
433 .and_then(|m| m["inner"]["module"]["items"].as_array())
434 else {
435 return;
436 };
437 for id in children.iter().filter_map(Value::as_u64) {
438 let Some(child) = self.index.get(&id.to_string()) else {
439 continue;
440 };
441 let use_ = &child["inner"]["use"];
442 match (use_["id"].as_u64(), use_["is_glob"].as_bool()) {
443 (Some(target), Some(true)) => {
445 if let Some((dep, from)) = self.external(target) {
446 alias_external(dep, &from, mod_path, true, surface);
447 }
448 }
449 (Some(target), _) => {
450 if let Some(name) = use_["name"].as_str() {
451 self.alias(surface, mod_path, name, target);
452 }
453 }
454 (None, _) => {
455 if let Some(name) = child["name"].as_str() {
456 alias_one(self.paths, surface, mod_path, name, id);
457 }
458 }
459 }
460 }
461 }
462}
463
464fn alias_one(
469 paths: &serde_json::Map<String, Value>,
470 surface: &mut Surface,
471 mod_path: &str,
472 name: &str,
473 target_id: u64,
474) {
475 let Some(target_path) = item_path(paths, &target_id.to_string()) else {
476 return;
477 };
478 let Some(info) = surface.items.get(&target_path).cloned() else {
479 return; };
481 let alias = format!("{mod_path}::{name}");
482 if alias == target_path {
483 return;
484 }
485 surface.items.entry(alias).or_insert(info);
486}
487
488fn alias_external(dep: &Surface, from: &str, to: &str, glob: bool, surface: &mut Surface) {
492 let below = |entries: &BTreeMap<String, ItemInfo>| -> Vec<(String, ItemInfo)> {
493 entries
494 .iter()
495 .filter_map(|(path, info)| {
496 let rest = path.strip_prefix(from)?;
497 let taken = rest.starts_with("::") || (rest.is_empty() && !glob);
498 taken.then(|| (format!("{to}{rest}"), info.clone()))
499 })
500 .collect()
501 };
502 for (path, info) in below(&dep.items) {
503 surface.items.entry(path).or_insert(info);
504 }
505 for (path, info) in below(&dep.members) {
506 surface.members.entry(path).or_insert(info);
507 }
508}
509
510fn item_path(paths: &serde_json::Map<String, Value>, id: &str) -> Option<String> {
511 let segs = paths.get(id)?["path"].as_array()?;
512 Some(
513 segs.iter()
514 .filter_map(Value::as_str)
515 .collect::<Vec<_>>()
516 .join("::"),
517 )
518}
519
520const MEMBER_KINDS: [&str; 3] = ["struct", "enum", "union"];
524
525fn item_fingerprint(
526 index: &serde_json::Map<String, Value>,
527 item: &Value,
528 kind: &str,
529 root: &Path,
530 cache: &mut HashMap<String, Vec<String>>,
531) -> Option<(u64, String)> {
532 let span_text = read_span(&item["span"], root, cache)?;
533 let bare = normalize(&crate::comments::strip_all(&span_text));
534 let name = item["name"].as_str().unwrap_or_default();
535 if !generated::is_macro_call(&bare[..declaration_end(&bare)], name, kind) {
536 return Some(text_fingerprint(&span_text, kind));
537 }
538 let declaration = generated::declaration(index, item, kind, false);
539 let docs = item["docs"].as_str().unwrap_or_default();
540 Some((
541 generated::fingerprint(&declaration, docs),
542 generated::declaration(index, item, kind, true),
543 ))
544}
545
546fn declaration_end(bare: &str) -> usize {
547 bare.find('{')
548 .or_else(|| bare.find(';'))
549 .unwrap_or(bare.len())
550}
551
552fn read_span(
553 span: &Value,
554 root: &Path,
555 cache: &mut HashMap<String, Vec<String>>,
556) -> Option<String> {
557 let filename = span["filename"].as_str()?;
558 let begin = span["begin"].as_array()?;
559 let end = span["end"].as_array()?;
560 let (bl, el) = (begin[0].as_u64()? as usize, end[0].as_u64()? as usize);
561
562 let lines = match cache.get(filename) {
563 Some(l) => l,
564 None => {
565 let abs = root.join(filename);
568 let text = std::fs::read_to_string(&abs).ok()?;
569 cache.insert(
570 filename.to_string(),
571 text.lines().map(str::to_string).collect(),
572 );
573 &cache[filename]
574 }
575 };
576 if bl == 0 || el > lines.len() || bl > el {
577 return None;
578 }
579 Some(lines[bl - 1..el].join("\n"))
580}
581
582fn text_fingerprint(span_text: &str, kind: &str) -> (u64, String) {
583 let normalized = normalize(&crate::comments::strip(span_text));
584 let bare = normalize(&crate::comments::strip_all(span_text));
587 let sig_end = declaration_end(&bare);
588 let declaration = bare[..sig_end].trim();
589 let signature = if MEMBER_KINDS.contains(&kind) {
590 member_signature(declaration, &bare[sig_end..], kind == "enum")
591 } else {
592 declaration.to_string()
593 };
594 (soothfast_registry::fnv1a(normalized.as_bytes()), signature)
595}
596
597fn normalize(source: &str) -> String {
598 source.split_whitespace().collect::<Vec<_>>().join(" ")
599}
600
601fn member_signature(declaration: &str, rest: &str, all_public: bool) -> String {
605 let Some(body) = rest
606 .strip_prefix('{')
607 .and_then(|inner| inner.trim_end().strip_suffix('}'))
608 else {
609 return declaration.to_string();
610 };
611 let members: Vec<String> = split_top_level(body)
612 .into_iter()
613 .map(|member| strip_attributes(member.trim()).to_string())
614 .filter(|member| !member.is_empty() && (all_public || member.starts_with("pub ")))
615 .collect();
616 format!("{declaration} {{ {} }}", members.join(", "))
617}
618
619fn split_top_level(text: &str) -> Vec<&str> {
622 let mut parts = Vec::new();
623 let mut depth = 0i32;
624 let mut start = 0;
625 let mut prev = ' ';
626 for (i, c) in text.char_indices() {
627 match c {
628 '<' | '(' | '[' | '{' => depth += 1,
629 '>' if prev == '-' => {}
630 '>' | ')' | ']' | '}' => depth -= 1,
631 ',' if depth == 0 => {
632 parts.push(&text[start..i]);
633 start = i + 1;
634 }
635 _ => {}
636 }
637 prev = c;
638 }
639 parts.push(&text[start..]);
640 parts
641}
642
643fn strip_attributes(member: &str) -> &str {
646 let mut rest = member;
647 while let Some(after) = rest.strip_prefix("#[") {
648 let mut depth = 1;
649 let mut end = None;
650 for (i, c) in after.char_indices() {
651 depth += match c {
652 '[' => 1,
653 ']' => -1,
654 _ => 0,
655 };
656 if depth == 0 {
657 end = Some(i + 1);
658 break;
659 }
660 }
661 match end {
662 Some(e) => rest = after[e..].trim_start(),
663 None => break,
664 }
665 }
666 rest
667}
668
669#[cfg(test)]
670mod tests {
671 use super::*;
672 use serde_json::json;
673
674 fn private_submodule_reexport_doc() -> Value {
677 json!({
678 "index": {
679 "1": {
680 "visibility": "public",
681 "inner": { "module": { "items": [2, 3] } },
682 },
683 "2": {
684 "name": "sma",
685 "visibility": "public",
686 "inner": { "function": {} },
687 "span": { "filename": "src/sma.rs", "begin": [1, 0], "end": [1, 0] },
688 "docs": "Simple moving average.",
689 },
690 "3": {
691 "visibility": "public",
692 "inner": {
693 "use": { "source": "sma::sma", "name": "sma", "id": 2, "is_glob": false },
694 },
695 },
696 },
697 "paths": {
698 "1": { "path": ["myc", "indicators"], "kind": "module" },
699 "2": { "path": ["myc", "indicators", "sma", "sma"], "kind": "function" },
700 },
701 })
702 }
703
704 #[test]
705 fn reexport_alias_resolves_alongside_canonical_path() {
706 let dir =
707 std::env::temp_dir().join(format!("soothfast-surface-test-{}", std::process::id()));
708 std::fs::create_dir_all(dir.join("src")).unwrap();
709 std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
710
711 let doc = private_submodule_reexport_doc();
712 let surface = from_rustdoc(&doc, &dir);
713
714 assert!(surface.items.contains_key("myc::indicators::sma::sma"));
715 assert!(
716 surface.items.contains_key("myc::indicators::sma"),
717 "expected the flattened re-export path to resolve too: {:?}",
718 surface.items.keys().collect::<Vec<_>>()
719 );
720 let canonical = &surface.items["myc::indicators::sma::sma"];
721 let alias = &surface.items["myc::indicators::sma"];
722 assert_eq!(canonical.fingerprint, alias.fingerprint);
723 assert_eq!(alias.kind, "function");
724
725 let _ = std::fs::remove_dir_all(&dir);
726 }
727
728 #[test]
729 fn glob_reexport_aliases_every_child_by_its_own_name() {
730 let mut doc = private_submodule_reexport_doc();
732 doc["index"]["3"]["inner"]["use"] =
733 json!({ "source": "sma", "name": "sma", "id": 7, "is_glob": true });
734 doc["index"]["7"] = json!({
735 "visibility": "public",
736 "inner": { "module": { "items": [2] } },
737 });
738
739 let dir =
740 std::env::temp_dir().join(format!("soothfast-surface-glob-{}", std::process::id()));
741 std::fs::create_dir_all(dir.join("src")).unwrap();
742 std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
743
744 let surface = from_rustdoc(&doc, &dir);
745 assert!(surface.items.contains_key("myc::indicators::sma::sma"));
746 assert!(surface.items.contains_key("myc::indicators::sma"));
747
748 let _ = std::fs::remove_dir_all(&dir);
749 }
750
751 fn impl_doc() -> Value {
752 let span =
753 |line: u64| json!({ "filename": "src/lib.rs", "begin": [line, 0], "end": [line, 0] });
754 json!({
755 "index": {
756 "1": { "visibility": "public", "inner": { "module": { "items": [2, 20] } } },
757 "2": {
758 "name": "Rewriter",
759 "visibility": "public",
760 "inner": { "struct": {} },
761 "span": span(1),
762 },
763 "3": {
764 "visibility": "default",
765 "inner": { "impl": {
766 "trait": null,
767 "for": { "resolved_path": { "id": 2 } },
768 "items": [4, 5, 6],
769 } },
770 },
771 "4": {
772 "name": "rewrite",
773 "visibility": "public",
774 "inner": { "function": {} },
775 "span": span(2),
776 },
777 "5": {
778 "name": "hidden",
779 "visibility": "default",
780 "inner": { "function": {} },
781 "span": span(3),
782 },
783 "6": {
784 "name": "LIMIT",
785 "visibility": "public",
786 "inner": { "assoc_const": {} },
787 "span": span(4),
788 },
789 "8": {
790 "visibility": "default",
791 "inner": { "impl": {
792 "trait": { "path": "Default" },
793 "for": { "resolved_path": { "id": 2 } },
794 "items": [7],
795 } },
796 },
797 "7": {
798 "name": "default",
799 "visibility": "public",
800 "inner": { "function": {} },
801 "span": span(5),
802 },
803 "20": {
804 "visibility": "public",
805 "inner": { "use": { "name": "Rewriter", "id": 2, "is_glob": false } },
806 },
807 },
808 "paths": {
809 "1": { "path": ["rw"], "kind": "module" },
810 "2": { "path": ["rw", "engine", "Rewriter"], "kind": "struct" },
811 },
812 })
813 }
814
815 #[test]
816 fn inherent_pub_members_resolve_under_the_type_path() {
817 let dir =
818 std::env::temp_dir().join(format!("soothfast-surface-impl-{}", std::process::id()));
819 std::fs::create_dir_all(dir.join("src")).unwrap();
820 std::fs::write(
821 dir.join("src/lib.rs"),
822 "pub struct Rewriter;\n pub fn rewrite() {}\n fn hidden() {}\n pub const LIMIT: u8 = 1;\n fn default() {}\n",
823 )
824 .unwrap();
825
826 let surface = from_rustdoc(&impl_doc(), &dir);
827
828 let method = surface.lookup("rw::engine::Rewriter::rewrite").unwrap();
829 assert_eq!(method.kind, "function");
830 assert_ne!(method.fingerprint, 0);
831 assert_eq!(
832 surface.lookup("rw::engine::Rewriter::LIMIT").unwrap().kind,
833 "constant"
834 );
835 assert!(surface.lookup("rw::engine::Rewriter::hidden").is_none());
836 assert!(surface.lookup("rw::engine::Rewriter::default").is_none());
837 assert!(surface.items.keys().all(|k| !k.ends_with("::rewrite")));
838 assert_eq!(
839 surface.lookup("rw::Rewriter::rewrite").unwrap().fingerprint,
840 method.fingerprint
841 );
842
843 let _ = std::fs::remove_dir_all(&dir);
844 }
845
846 #[test]
847 fn a_fenced_rust_example_in_the_docs_is_recorded() {
848 let doc = |docs: &str| {
849 json!({
850 "index": { "1": {
851 "name": "f",
852 "visibility": "public",
853 "docs": docs,
854 "inner": { "function": {} },
855 } },
856 "paths": { "1": { "path": ["a", "f"], "kind": "function" } },
857 })
858 };
859 let at = Path::new(".");
860 let with = from_rustdoc(&doc("Runs.\n\n```\nf();\n```\n"), at);
861 let without = from_rustdoc(&doc("Runs.\n\n```text\nf()\n```\n"), at);
862 assert!(with.items["a::f"].example && with.items["a::f"].has_docs);
863 assert!(!without.items["a::f"].example && without.items["a::f"].has_docs);
864 }
865
866 #[test]
867 fn counted_takes_inherent_methods_and_leaves_trait_impls_and_private_ones() {
868 let dir =
869 std::env::temp_dir().join(format!("soothfast-surface-counted-{}", std::process::id()));
870 std::fs::create_dir_all(dir.join("src")).unwrap();
871 std::fs::write(dir.join("src/lib.rs"), "pub struct Rewriter;\n pub fn rewrite() {}\n fn hidden() {}\n pub const LIMIT: u8 = 1;\n fn default() {}\n").unwrap();
872
873 let surface = from_rustdoc(&impl_doc(), &dir);
874 let paths: Vec<_> = surface.counted().into_iter().map(|c| c.path).collect();
875 assert_eq!(paths, ["rw", "rw::Rewriter", "rw::Rewriter::rewrite"]);
876
877 let _ = std::fs::remove_dir_all(&dir);
878 }
879
880 fn item(kind: &str, fingerprint: u64) -> ItemInfo {
881 ItemInfo {
882 kind: kind.to_string(),
883 fingerprint,
884 signature: String::new(),
885 has_docs: false,
886 spans: Vec::new(),
887 example: false,
888 }
889 }
890
891 fn surface_of(items: Vec<(&str, ItemInfo)>) -> Surface {
892 Surface {
893 items: items.into_iter().map(|(p, i)| (p.to_string(), i)).collect(),
894 ..Surface::default()
895 }
896 }
897
898 fn facade_doc() -> Value {
899 let use_ = |name: &str, id: u64, is_glob: bool| {
900 json!({
901 "visibility": "public",
902 "inner": { "use": { "name": name, "id": id, "is_glob": is_glob } },
903 })
904 };
905 json!({
906 "index": {
907 "1": { "visibility": "public", "inner": { "module": { "items": [2, 3, 4, 5, 8, 9, 10] } } },
908 "2": use_("named", 20, false),
909 "3": use_("indicators", 21, false),
910 "4": use_("prelude", 22, true),
911 "5": use_("Counter", 23, false),
912 "6": { "visibility": "default", "inner": { "module": { "items": [7] } } },
913 "7": use_("Two", 24, false),
914 "8": use_("inner", 6, true),
915 "9": use_("fmt", 30, false),
916 "10": use_("renamed", 25, false),
917 },
918 "paths": {
919 "1": { "crate_id": 0, "path": ["a"], "kind": "module" },
920 "6": { "crate_id": 0, "path": ["a", "inner"], "kind": "module" },
921 "20": { "crate_id": 1, "path": ["b", "named"], "kind": "function" },
922 "21": { "crate_id": 1, "path": ["b", "indicators"], "kind": "module" },
923 "22": { "crate_id": 1, "path": ["b", "prelude"], "kind": "module" },
924 "23": { "crate_id": 1, "path": ["b", "Counter"], "kind": "struct" },
925 "24": { "crate_id": 1, "path": ["b", "Two"], "kind": "struct" },
926 "25": { "crate_id": 1, "path": ["b"], "kind": "module" },
927 "30": { "crate_id": 2, "path": ["std", "fmt"], "kind": "module" },
928 },
929 "external_crates": { "1": { "name": "b" }, "2": { "name": "std" } },
930 })
931 }
932
933 fn documented(kind: &str, fingerprint: u64) -> ItemInfo {
934 ItemInfo {
935 has_docs: true,
936 ..item(kind, fingerprint)
937 }
938 }
939
940 fn dependency_b() -> BTreeMap<String, Surface> {
941 let mut b = surface_of(vec![
942 ("b", item("module", 1)),
943 ("b::named", documented("function", 2)),
944 ("b::indicators", item("module", 3)),
945 ("b::indicators::sma", documented("function", 4)),
946 ("b::prelude", item("module", 5)),
947 ("b::prelude::one", documented("function", 6)),
948 ("b::Counter", documented("struct", 7)),
949 ("b::Two", item("struct", 8)),
950 ]);
951 b.members
952 .insert("b::Counter::new".to_string(), documented("function", 9));
953 BTreeMap::from([("b".to_string(), b)])
954 }
955
956 #[test]
957 fn a_reexport_from_another_crate_takes_the_defining_crates_info() {
958 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
959
960 let named = &surface.items["a::named"];
961 assert_eq!((named.kind.as_str(), named.fingerprint), ("function", 2));
962 assert!(named.has_docs);
963 assert_eq!(surface.items["a::Counter"].fingerprint, 7);
964 assert_eq!(surface.members["a::Counter::new"].fingerprint, 9);
965 assert!(surface.lookup("a::Counter::new").unwrap().has_docs);
966 assert!(surface.items.keys().all(|k| !k.starts_with("b::")));
967 assert!(surface.members.keys().all(|k| !k.starts_with("b::")));
968 }
969
970 #[test]
971 fn a_reexported_module_brings_what_is_below_it() {
972 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
973 assert_eq!(surface.items["a::indicators"].kind, "module");
974 assert_eq!(surface.items["a::indicators::sma"].fingerprint, 4);
975 }
976
977 #[test]
978 fn a_renamed_crate_reexport_brings_everything_below_the_crate() {
979 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
980 assert_eq!(surface.items["a::renamed"].kind, "module");
981 assert_eq!(surface.items["a::renamed::named"].fingerprint, 2);
982 assert_eq!(surface.items["a::renamed::indicators::sma"].fingerprint, 4);
983 assert_eq!(surface.members["a::renamed::Counter::new"].fingerprint, 9);
984 }
985
986 #[test]
987 fn a_glob_of_another_crates_module_takes_its_children_not_the_module() {
988 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
989 assert_eq!(surface.items["a::one"].fingerprint, 6);
990 assert!(!surface.items.contains_key("a::prelude"));
991 }
992
993 #[test]
994 fn a_glob_of_a_local_module_takes_its_named_reexports() {
995 let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
996 assert_eq!(surface.items["a::Two"].fingerprint, 8);
997 }
998
999 #[test]
1000 fn a_glob_of_a_local_module_takes_a_local_named_reexport_once() {
1001 let mut doc = private_submodule_reexport_doc();
1003 doc["index"]["1"]["inner"]["module"]["items"] = json!([2, 3, 8]);
1004 doc["index"]["7"] = json!({
1005 "visibility": "default",
1006 "inner": { "module": { "items": [9] } },
1007 });
1008 doc["index"]["8"] = json!({
1009 "visibility": "public",
1010 "inner": { "use": { "name": "inner", "id": 7, "is_glob": true } },
1011 });
1012 doc["index"]["9"] = json!({
1013 "visibility": "public",
1014 "inner": { "use": { "name": "average", "id": 2, "is_glob": false } },
1015 });
1016 let dir =
1017 std::env::temp_dir().join(format!("soothfast-surface-inner-{}", std::process::id()));
1018 std::fs::create_dir_all(dir.join("src")).unwrap();
1019 std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
1020
1021 let surface = from_rustdoc(&doc, &dir);
1022 let alias = &surface.items["myc::indicators::average"];
1023 assert_eq!(
1024 alias.fingerprint,
1025 surface.items["myc::indicators::sma"].fingerprint
1026 );
1027 let functions: Vec<_> = surface
1028 .grouped()
1029 .into_iter()
1030 .filter(|g| surface.items[g.representative].kind == "function")
1031 .collect();
1032 assert_eq!(functions.len(), 1);
1033
1034 let _ = std::fs::remove_dir_all(&dir);
1035 }
1036
1037 #[test]
1038 fn a_crate_without_a_known_surface_stays_unresolved() {
1039 let surface = from_rustdoc(&facade_doc(), Path::new("."));
1040 assert_eq!(surface.items.keys().collect::<Vec<_>>(), ["a"]);
1041 }
1042
1043 #[test]
1044 fn reexported_crates_names_each_crate_a_pub_use_reaches() {
1045 let crates = reexported_crates(&facade_doc());
1046 assert_eq!(crates.into_iter().collect::<Vec<_>>(), ["b", "std"]);
1047 assert!(reexported_crates(&impl_doc()).is_empty());
1048 }
1049
1050 #[test]
1051 fn three_aliases_of_one_function_collapse_to_one_group() {
1052 let surf = surface_of(vec![
1053 ("myc::atr", item("function", 42)),
1054 ("myc::indicators::atr", item("function", 42)),
1055 ("myc::indicators::atr::atr", item("function", 42)),
1056 ]);
1057 let groups = surf.grouped();
1058 assert_eq!(groups.len(), 1);
1059 assert_eq!(groups[0].representative, "myc::atr");
1060 assert_eq!(groups[0].aliases.len(), 3);
1061 }
1062
1063 #[test]
1064 fn covers_tag_on_a_longer_alias_still_counts_as_measured() {
1065 let surf = surface_of(vec![
1069 ("myc::atr", item("function", 42)),
1070 ("myc::indicators::atr", item("function", 42)),
1071 ]);
1072 let g = &surf.grouped()[0];
1073 assert!(
1074 g.aliases
1075 .iter()
1076 .any(|a| a.as_str() == "myc::indicators::atr")
1077 );
1078 }
1079
1080 #[test]
1081 fn distinct_functions_with_no_fingerprint_are_never_merged() {
1082 let surf = surface_of(vec![
1083 ("myc::a", item("function", 0)),
1084 ("myc::b", item("function", 0)),
1085 ]);
1086 assert_eq!(surf.grouped().len(), 2);
1087 }
1088
1089 #[test]
1090 fn different_kinds_with_the_same_fingerprint_are_not_merged() {
1091 let surf = surface_of(vec![
1092 ("myc::a", item("function", 7)),
1093 ("myc::A", item("struct", 7)),
1094 ]);
1095 assert_eq!(surf.grouped().len(), 2);
1096 }
1097
1098 fn fingerprint_of(tag: &str, source: &str) -> (u64, String) {
1099 fingerprint_of_kind(tag, "struct", source)
1100 }
1101
1102 fn fingerprint_of_kind(tag: &str, kind: &str, source: &str) -> (u64, String) {
1103 let dir = std::env::temp_dir().join(format!(
1104 "soothfast-fingerprint-{}-{tag}",
1105 std::process::id()
1106 ));
1107 std::fs::create_dir_all(&dir).unwrap();
1108 std::fs::write(dir.join("lib.rs"), source).unwrap();
1109 let span = json!({
1110 "filename": "lib.rs",
1111 "begin": [1, 0],
1112 "end": [source.lines().count(), 0],
1113 });
1114 let text = read_span(&span, &dir, &mut HashMap::new()).unwrap();
1115 let got = text_fingerprint(&text, kind);
1116 let _ = std::fs::remove_dir_all(&dir);
1117 got
1118 }
1119
1120 #[test]
1121 fn a_comment_only_edit_does_not_move_the_fingerprint() {
1122 let plain = fingerprint_of("plain", "pub struct S {\n a: u8,\n}\n");
1123 let noted = fingerprint_of(
1124 "noted",
1125 "pub struct S {\n // widened for the wire format\n a: u8,\n}\n",
1126 );
1127 assert_eq!(plain.0, noted.0);
1128 }
1129
1130 #[test]
1131 fn a_field_change_still_moves_the_fingerprint() {
1132 let before = fingerprint_of("before", "pub struct S {\n a: u8,\n}\n");
1133 let after = fingerprint_of("after", "pub struct S {\n a: u16,\n}\n");
1134 assert_ne!(before.0, after.0);
1135 }
1136
1137 #[test]
1138 fn a_struct_field_addition_changes_the_signature() {
1139 let before = fingerprint_of_kind(
1140 "sig-before",
1141 "struct",
1142 "pub struct S {\n pub a: u8,\n}\n",
1143 );
1144 let after = fingerprint_of_kind(
1145 "sig-after",
1146 "struct",
1147 "pub struct S {\n pub a: u8,\n pub b: u8,\n}\n",
1148 );
1149 assert_ne!(before.1, after.1);
1150 assert_eq!(after.1, "pub struct S { pub a: u8, pub b: u8 }");
1151 }
1152
1153 #[test]
1154 fn a_private_field_edit_is_body_only() {
1155 let before = fingerprint_of_kind(
1156 "priv-before",
1157 "struct",
1158 "pub struct S {\n pub a: u8,\n b: u8,\n}\n",
1159 );
1160 let after = fingerprint_of_kind(
1161 "priv-after",
1162 "struct",
1163 "pub struct S {\n pub a: u8,\n b: u16,\n c: u8,\n}\n",
1164 );
1165 assert_ne!(before.0, after.0);
1166 assert_eq!(before.1, after.1);
1167 assert_eq!(before.1, "pub struct S { pub a: u8 }");
1168 }
1169
1170 #[test]
1171 fn generic_fields_and_attributes_are_read_as_members() {
1172 let got = fingerprint_of_kind(
1173 "generic",
1174 "struct",
1175 "pub struct S {\n #[serde(rename = \"m\")]\n pub map: HashMap<String, Vec<u8>>,\n pub(crate) hidden: u8,\n}\n",
1176 );
1177 assert_eq!(got.1, "pub struct S { pub map: HashMap<String, Vec<u8>> }");
1178 }
1179
1180 #[test]
1181 fn a_documented_public_field_counts_as_signature() {
1182 let before = fingerprint_of_kind(
1183 "pubdoc-before",
1184 "struct",
1185 "pub struct S {\n /// count\n pub a: u8,\n}\n",
1186 );
1187 let after = fingerprint_of_kind(
1188 "pubdoc-after",
1189 "struct",
1190 "pub struct S {\n /// count\n pub a: u8,\n /// total\n pub b: u8,\n}\n",
1191 );
1192 assert_ne!(before.1, after.1);
1193 assert_eq!(after.1, "pub struct S { pub a: u8, pub b: u8 }");
1194 }
1195
1196 #[test]
1197 fn a_variant_doc_edit_moves_the_fingerprint_but_not_the_signature() {
1198 let before = fingerprint_of_kind(
1199 "vdoc-before",
1200 "enum",
1201 "pub enum E {\n /// first\n A,\n B,\n}\n",
1202 );
1203 let after = fingerprint_of_kind(
1204 "vdoc-after",
1205 "enum",
1206 "pub enum E {\n /// the first\n A,\n B,\n}\n",
1207 );
1208 assert_ne!(before.0, after.0);
1209 assert_eq!(before.1, after.1);
1210 assert_eq!(before.1, "pub enum E { A, B }");
1211 }
1212
1213 #[test]
1214 fn a_function_pointer_field_does_not_swallow_its_neighbours() {
1215 let got = fingerprint_of_kind(
1216 "fnptr",
1217 "struct",
1218 "pub struct S {\n pub f: fn(u8) -> u8,\n pub g: u8,\n}\n",
1219 );
1220 assert_eq!(got.1, "pub struct S { pub f: fn(u8) -> u8, pub g: u8 }");
1221 }
1222
1223 #[test]
1224 fn an_enum_variant_addition_changes_the_signature() {
1225 let before = fingerprint_of_kind("var-before", "enum", "pub enum E {\n A,\n}\n");
1226 let after = fingerprint_of_kind("var-after", "enum", "pub enum E {\n A,\n B,\n}\n");
1227 assert_ne!(before.1, after.1);
1228 }
1229
1230 #[test]
1231 fn a_function_body_edit_keeps_its_signature() {
1232 let before = fingerprint_of_kind("fn-before", "function", "pub fn f() -> u8 {\n 1\n}\n");
1233 let after = fingerprint_of_kind("fn-after", "function", "pub fn f() -> u8 {\n 2\n}\n");
1234 assert_ne!(before.0, after.0);
1235 assert_eq!(before.1, after.1);
1236 assert_eq!(before.1, "pub fn f() -> u8");
1237 }
1238
1239 #[test]
1240 fn a_doc_comment_on_a_field_is_part_of_the_fingerprint() {
1241 let before = fingerprint_of(
1242 "doc-before",
1243 "pub struct S {\n /// count\n a: u8,\n}\n",
1244 );
1245 let after = fingerprint_of(
1246 "doc-after",
1247 "pub struct S {\n /// total\n a: u8,\n}\n",
1248 );
1249 assert_ne!(before.0, after.0);
1250 }
1251
1252 fn span(file: &str, begin: u32, end: u32) -> Span {
1253 Span {
1254 file: file.into(),
1255 begin,
1256 end,
1257 }
1258 }
1259
1260 fn spans_doc() -> Value {
1261 let at = |begin: u32, end: u32| json!({ "filename": "src/lib.rs", "begin": [begin, 0], "end": [end, 1] });
1262 let method = |name: &str, begin: u32, end: u32| {
1263 json!({
1264 "name": name,
1265 "visibility": "public",
1266 "inner": { "function": {} },
1267 "span": at(begin, end),
1268 })
1269 };
1270 json!({
1271 "index": {
1272 "1": { "name": "run", "visibility": "public", "inner": { "function": {} }, "span": at(1, 3) },
1273 "2": { "name": "Meter", "visibility": "public", "inner": { "struct": {} }, "span": at(5, 5) },
1274 "3": { "inner": { "impl": { "for": { "resolved_path": { "id": 2 } }, "items": [4] } } },
1275 "4": method("read", 8, 10),
1276 "5": { "inner": { "impl": { "trait": { "id": 9 }, "for": { "resolved_path": { "id": 2 } }, "items": [6] } } },
1277 "6": method("fmt", 14, 16),
1278 "7": { "inner": { "impl": { "for": { "generic": "T" }, "items": [8] } } },
1279 "8": method("blanket", 20, 22),
1280 },
1281 "paths": {
1282 "1": { "path": ["demo", "run"], "kind": "function" },
1283 "2": { "path": ["demo", "Meter"], "kind": "struct" },
1284 },
1285 })
1286 }
1287
1288 #[test]
1289 fn a_function_carries_its_own_span() {
1290 let surface = from_rustdoc(&spans_doc(), Path::new("/nowhere"));
1291 assert_eq!(surface.items["demo::run"].spans, [span("src/lib.rs", 1, 3)]);
1292 }
1293
1294 #[test]
1295 fn a_struct_carries_the_spans_of_its_inherent_and_trait_methods() {
1296 let surface = from_rustdoc(&spans_doc(), Path::new("/nowhere"));
1297 let spans = &surface.items["demo::Meter"].spans;
1298 assert_eq!(
1299 spans,
1300 &[
1301 span("src/lib.rs", 5, 5),
1302 span("src/lib.rs", 8, 10),
1303 span("src/lib.rs", 14, 16),
1304 ]
1305 );
1306 }
1307
1308 #[test]
1309 fn an_inherent_member_carries_its_own_span() {
1310 let surface = from_rustdoc(&spans_doc(), Path::new("/nowhere"));
1311 assert_eq!(
1312 surface.members["demo::Meter::read"].spans,
1313 [span("src/lib.rs", 8, 10)]
1314 );
1315 }
1316}