1use std::collections::{BTreeMap, 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 let mut surface = Surface::default();
116 let (Some(index), Some(paths)) = (doc["index"].as_object(), doc["paths"].as_object()) else {
117 return surface;
118 };
119 let mut file_cache: HashMap<String, Vec<String>> = HashMap::new();
120
121 for (id, item) in index {
122 if item["visibility"] != "public" {
123 continue;
124 }
125 let Some(inner) = item["inner"].as_object() else {
126 continue;
127 };
128 let Some(kind) = inner.keys().next().map(String::as_str) else {
129 continue;
130 };
131 if !KINDS.contains(&kind) {
132 continue;
133 }
134 let Some(full) = item_path(paths, id) else {
136 continue;
137 };
138
139 let (fingerprint, signature) =
140 item_fingerprint(index, item, kind, source_root, &mut file_cache)
141 .unwrap_or((0, String::new()));
142 let has_docs = item["docs"].as_str().is_some_and(|d| !d.trim().is_empty());
143
144 surface.items.insert(
145 full,
146 ItemInfo {
147 kind: kind.to_string(),
148 fingerprint,
149 signature,
150 has_docs,
151 },
152 );
153 }
154
155 alias_reexports(index, paths, &mut surface);
156 index_members(index, paths, source_root, &mut file_cache, &mut surface);
157 surface
158}
159
160fn index_members(
163 index: &serde_json::Map<String, Value>,
164 paths: &serde_json::Map<String, Value>,
165 source_root: &Path,
166 file_cache: &mut HashMap<String, Vec<String>>,
167 surface: &mut Surface,
168) {
169 for item in index.values() {
170 let imp = &item["inner"]["impl"];
171 if !imp.is_object() || imp["trait"].is_object() {
172 continue;
173 }
174 let Some(type_id) = imp["for"]["resolved_path"]["id"].as_u64() else {
175 continue;
176 };
177 let Some(type_path) = item_path(paths, &type_id.to_string()) else {
178 continue;
179 };
180 let Some(owner) = surface.items.get(&type_path) else {
181 continue;
182 };
183 let spellings: Vec<String> = surface
184 .items
185 .iter()
186 .filter(|(_, info)| info.kind == owner.kind && info.fingerprint == owner.fingerprint)
187 .map(|(path, _)| path.clone())
188 .collect();
189
190 let members = imp["items"].as_array().into_iter().flatten();
191 for member in members.filter_map(|id| index.get(&id.as_u64()?.to_string())) {
192 if member["visibility"] != "public" {
193 continue;
194 }
195 let (kind, name) = match (
196 member["inner"]["function"].is_object(),
197 member["inner"]["assoc_const"].is_object(),
198 member["name"].as_str(),
199 ) {
200 (true, _, Some(name)) => ("function", name),
201 (_, true, Some(name)) => ("constant", name),
202 _ => continue,
203 };
204 let (fingerprint, signature) =
205 item_fingerprint(index, member, kind, source_root, file_cache)
206 .unwrap_or((0, String::new()));
207 let info = ItemInfo {
208 kind: kind.to_string(),
209 fingerprint,
210 signature,
211 has_docs: member["docs"]
212 .as_str()
213 .is_some_and(|d| !d.trim().is_empty()),
214 };
215 for spelling in &spellings {
216 surface
217 .members
218 .insert(format!("{spelling}::{name}"), info.clone());
219 }
220 }
221 }
222}
223
224fn alias_reexports(
236 index: &serde_json::Map<String, Value>,
237 paths: &serde_json::Map<String, Value>,
238 surface: &mut Surface,
239) {
240 for (mod_id, item) in index {
241 if item["visibility"] != "public" {
242 continue;
243 }
244 let Some(children) = item["inner"]["module"]["items"].as_array() else {
245 continue;
246 };
247 let Some(mod_path) = item_path(paths, mod_id) else {
248 continue;
249 };
250
251 for child in children {
252 let Some(child_id) = child.as_u64() else {
253 continue;
254 };
255 let child_id = child_id.to_string();
256 let Some(use_) = index.get(&child_id).map(|c| &c["inner"]["use"]) else {
257 continue;
258 };
259 let Some(target_id) = use_["id"].as_u64() else {
260 continue;
261 };
262 let targets: Vec<(String, u64)> = if use_["is_glob"].as_bool().unwrap_or(false) {
268 glob_targets(index, target_id)
269 } else {
270 match use_["name"].as_str() {
271 Some(name) => vec![(name.to_string(), target_id)],
272 None => continue,
273 }
274 };
275
276 for (name, target_id) in targets {
277 alias_one(paths, surface, &mod_path, &name, target_id);
278 }
279 }
280 }
281}
282
283fn glob_targets(index: &serde_json::Map<String, Value>, module_id: u64) -> Vec<(String, u64)> {
286 let Some(children) = index
287 .get(&module_id.to_string())
288 .and_then(|m| m["inner"]["module"]["items"].as_array())
289 else {
290 return Vec::new();
291 };
292 children
293 .iter()
294 .filter_map(|c| {
295 let id = c.as_u64()?;
296 let name = index.get(&id.to_string())?["name"].as_str()?;
297 Some((name.to_string(), id))
298 })
299 .collect()
300}
301
302fn alias_one(
307 paths: &serde_json::Map<String, Value>,
308 surface: &mut Surface,
309 mod_path: &str,
310 name: &str,
311 target_id: u64,
312) {
313 let Some(target_path) = item_path(paths, &target_id.to_string()) else {
314 return;
315 };
316 let Some(info) = surface.items.get(&target_path).cloned() else {
317 return; };
319 let alias = format!("{mod_path}::{name}");
320 if alias == target_path {
321 return;
322 }
323 surface.items.entry(alias).or_insert(info);
324}
325
326fn item_path(paths: &serde_json::Map<String, Value>, id: &str) -> Option<String> {
327 let segs = paths.get(id)?["path"].as_array()?;
328 Some(
329 segs.iter()
330 .filter_map(Value::as_str)
331 .collect::<Vec<_>>()
332 .join("::"),
333 )
334}
335
336const MEMBER_KINDS: [&str; 3] = ["struct", "enum", "union"];
340
341fn item_fingerprint(
342 index: &serde_json::Map<String, Value>,
343 item: &Value,
344 kind: &str,
345 root: &Path,
346 cache: &mut HashMap<String, Vec<String>>,
347) -> Option<(u64, String)> {
348 let span_text = read_span(&item["span"], root, cache)?;
349 let bare = normalize(&crate::comments::strip_all(&span_text));
350 let name = item["name"].as_str().unwrap_or_default();
351 if !generated::is_macro_call(&bare[..declaration_end(&bare)], name, kind) {
352 return Some(text_fingerprint(&span_text, kind));
353 }
354 let declaration = generated::declaration(index, item, kind, false);
355 let docs = item["docs"].as_str().unwrap_or_default();
356 Some((
357 generated::fingerprint(&declaration, docs),
358 generated::declaration(index, item, kind, true),
359 ))
360}
361
362fn declaration_end(bare: &str) -> usize {
363 bare.find('{')
364 .or_else(|| bare.find(';'))
365 .unwrap_or(bare.len())
366}
367
368fn read_span(
369 span: &Value,
370 root: &Path,
371 cache: &mut HashMap<String, Vec<String>>,
372) -> Option<String> {
373 let filename = span["filename"].as_str()?;
374 let begin = span["begin"].as_array()?;
375 let end = span["end"].as_array()?;
376 let (bl, el) = (begin[0].as_u64()? as usize, end[0].as_u64()? as usize);
377
378 let lines = match cache.get(filename) {
379 Some(l) => l,
380 None => {
381 let abs = root.join(filename);
384 let text = std::fs::read_to_string(&abs).ok()?;
385 cache.insert(
386 filename.to_string(),
387 text.lines().map(str::to_string).collect(),
388 );
389 &cache[filename]
390 }
391 };
392 if bl == 0 || el > lines.len() || bl > el {
393 return None;
394 }
395 Some(lines[bl - 1..el].join("\n"))
396}
397
398fn text_fingerprint(span_text: &str, kind: &str) -> (u64, String) {
399 let normalized = normalize(&crate::comments::strip(span_text));
400 let bare = normalize(&crate::comments::strip_all(span_text));
403 let sig_end = declaration_end(&bare);
404 let declaration = bare[..sig_end].trim();
405 let signature = if MEMBER_KINDS.contains(&kind) {
406 member_signature(declaration, &bare[sig_end..], kind == "enum")
407 } else {
408 declaration.to_string()
409 };
410 (soothfast_registry::fnv1a(normalized.as_bytes()), signature)
411}
412
413fn normalize(source: &str) -> String {
414 source.split_whitespace().collect::<Vec<_>>().join(" ")
415}
416
417fn member_signature(declaration: &str, rest: &str, all_public: bool) -> String {
421 let Some(body) = rest
422 .strip_prefix('{')
423 .and_then(|inner| inner.trim_end().strip_suffix('}'))
424 else {
425 return declaration.to_string();
426 };
427 let members: Vec<String> = split_top_level(body)
428 .into_iter()
429 .map(|member| strip_attributes(member.trim()).to_string())
430 .filter(|member| !member.is_empty() && (all_public || member.starts_with("pub ")))
431 .collect();
432 format!("{declaration} {{ {} }}", members.join(", "))
433}
434
435fn split_top_level(text: &str) -> Vec<&str> {
438 let mut parts = Vec::new();
439 let mut depth = 0i32;
440 let mut start = 0;
441 let mut prev = ' ';
442 for (i, c) in text.char_indices() {
443 match c {
444 '<' | '(' | '[' | '{' => depth += 1,
445 '>' if prev == '-' => {}
446 '>' | ')' | ']' | '}' => depth -= 1,
447 ',' if depth == 0 => {
448 parts.push(&text[start..i]);
449 start = i + 1;
450 }
451 _ => {}
452 }
453 prev = c;
454 }
455 parts.push(&text[start..]);
456 parts
457}
458
459fn strip_attributes(member: &str) -> &str {
462 let mut rest = member;
463 while let Some(after) = rest.strip_prefix("#[") {
464 let mut depth = 1;
465 let mut end = None;
466 for (i, c) in after.char_indices() {
467 depth += match c {
468 '[' => 1,
469 ']' => -1,
470 _ => 0,
471 };
472 if depth == 0 {
473 end = Some(i + 1);
474 break;
475 }
476 }
477 match end {
478 Some(e) => rest = after[e..].trim_start(),
479 None => break,
480 }
481 }
482 rest
483}
484
485#[cfg(test)]
486mod tests {
487 use super::*;
488 use serde_json::json;
489
490 fn private_submodule_reexport_doc() -> Value {
493 json!({
494 "index": {
495 "1": {
496 "visibility": "public",
497 "inner": { "module": { "items": [2, 3] } },
498 },
499 "2": {
500 "name": "sma",
501 "visibility": "public",
502 "inner": { "function": {} },
503 "span": { "filename": "src/sma.rs", "begin": [1, 0], "end": [1, 0] },
504 "docs": "Simple moving average.",
505 },
506 "3": {
507 "visibility": "public",
508 "inner": {
509 "use": { "source": "sma::sma", "name": "sma", "id": 2, "is_glob": false },
510 },
511 },
512 },
513 "paths": {
514 "1": { "path": ["myc", "indicators"], "kind": "module" },
515 "2": { "path": ["myc", "indicators", "sma", "sma"], "kind": "function" },
516 },
517 })
518 }
519
520 #[test]
521 fn reexport_alias_resolves_alongside_canonical_path() {
522 let dir =
523 std::env::temp_dir().join(format!("soothfast-surface-test-{}", std::process::id()));
524 std::fs::create_dir_all(dir.join("src")).unwrap();
525 std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
526
527 let doc = private_submodule_reexport_doc();
528 let surface = from_rustdoc(&doc, &dir);
529
530 assert!(surface.items.contains_key("myc::indicators::sma::sma"));
531 assert!(
532 surface.items.contains_key("myc::indicators::sma"),
533 "expected the flattened re-export path to resolve too: {:?}",
534 surface.items.keys().collect::<Vec<_>>()
535 );
536 let canonical = &surface.items["myc::indicators::sma::sma"];
537 let alias = &surface.items["myc::indicators::sma"];
538 assert_eq!(canonical.fingerprint, alias.fingerprint);
539 assert_eq!(alias.kind, "function");
540
541 let _ = std::fs::remove_dir_all(&dir);
542 }
543
544 #[test]
545 fn glob_reexport_aliases_every_child_by_its_own_name() {
546 let mut doc = private_submodule_reexport_doc();
548 doc["index"]["3"]["inner"]["use"] =
549 json!({ "source": "sma", "name": "sma", "id": 7, "is_glob": true });
550 doc["index"]["7"] = json!({
551 "visibility": "public",
552 "inner": { "module": { "items": [2] } },
553 });
554
555 let dir =
556 std::env::temp_dir().join(format!("soothfast-surface-glob-{}", std::process::id()));
557 std::fs::create_dir_all(dir.join("src")).unwrap();
558 std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
559
560 let surface = from_rustdoc(&doc, &dir);
561 assert!(surface.items.contains_key("myc::indicators::sma::sma"));
562 assert!(surface.items.contains_key("myc::indicators::sma"));
563
564 let _ = std::fs::remove_dir_all(&dir);
565 }
566
567 fn impl_doc() -> Value {
568 let span =
569 |line: u64| json!({ "filename": "src/lib.rs", "begin": [line, 0], "end": [line, 0] });
570 json!({
571 "index": {
572 "1": { "visibility": "public", "inner": { "module": { "items": [2, 20] } } },
573 "2": {
574 "name": "Rewriter",
575 "visibility": "public",
576 "inner": { "struct": {} },
577 "span": span(1),
578 },
579 "3": {
580 "visibility": "default",
581 "inner": { "impl": {
582 "trait": null,
583 "for": { "resolved_path": { "id": 2 } },
584 "items": [4, 5, 6],
585 } },
586 },
587 "4": {
588 "name": "rewrite",
589 "visibility": "public",
590 "inner": { "function": {} },
591 "span": span(2),
592 },
593 "5": {
594 "name": "hidden",
595 "visibility": "default",
596 "inner": { "function": {} },
597 "span": span(3),
598 },
599 "6": {
600 "name": "LIMIT",
601 "visibility": "public",
602 "inner": { "assoc_const": {} },
603 "span": span(4),
604 },
605 "8": {
606 "visibility": "default",
607 "inner": { "impl": {
608 "trait": { "path": "Default" },
609 "for": { "resolved_path": { "id": 2 } },
610 "items": [7],
611 } },
612 },
613 "7": {
614 "name": "default",
615 "visibility": "public",
616 "inner": { "function": {} },
617 "span": span(5),
618 },
619 "20": {
620 "visibility": "public",
621 "inner": { "use": { "name": "Rewriter", "id": 2, "is_glob": false } },
622 },
623 },
624 "paths": {
625 "1": { "path": ["rw"], "kind": "module" },
626 "2": { "path": ["rw", "engine", "Rewriter"], "kind": "struct" },
627 },
628 })
629 }
630
631 #[test]
632 fn inherent_pub_members_resolve_under_the_type_path() {
633 let dir =
634 std::env::temp_dir().join(format!("soothfast-surface-impl-{}", std::process::id()));
635 std::fs::create_dir_all(dir.join("src")).unwrap();
636 std::fs::write(
637 dir.join("src/lib.rs"),
638 "pub struct Rewriter;\n pub fn rewrite() {}\n fn hidden() {}\n pub const LIMIT: u8 = 1;\n fn default() {}\n",
639 )
640 .unwrap();
641
642 let surface = from_rustdoc(&impl_doc(), &dir);
643
644 let method = surface.lookup("rw::engine::Rewriter::rewrite").unwrap();
645 assert_eq!(method.kind, "function");
646 assert_ne!(method.fingerprint, 0);
647 assert_eq!(
648 surface.lookup("rw::engine::Rewriter::LIMIT").unwrap().kind,
649 "constant"
650 );
651 assert!(surface.lookup("rw::engine::Rewriter::hidden").is_none());
652 assert!(surface.lookup("rw::engine::Rewriter::default").is_none());
653 assert!(surface.items.keys().all(|k| !k.ends_with("::rewrite")));
654 assert_eq!(
655 surface.lookup("rw::Rewriter::rewrite").unwrap().fingerprint,
656 method.fingerprint
657 );
658
659 let _ = std::fs::remove_dir_all(&dir);
660 }
661
662 fn item(kind: &str, fingerprint: u64) -> ItemInfo {
663 ItemInfo {
664 kind: kind.to_string(),
665 fingerprint,
666 signature: String::new(),
667 has_docs: false,
668 }
669 }
670
671 fn surface_of(items: Vec<(&str, ItemInfo)>) -> Surface {
672 Surface {
673 items: items.into_iter().map(|(p, i)| (p.to_string(), i)).collect(),
674 ..Surface::default()
675 }
676 }
677
678 #[test]
679 fn three_aliases_of_one_function_collapse_to_one_group() {
680 let surf = surface_of(vec![
681 ("myc::atr", item("function", 42)),
682 ("myc::indicators::atr", item("function", 42)),
683 ("myc::indicators::atr::atr", item("function", 42)),
684 ]);
685 let groups = surf.grouped();
686 assert_eq!(groups.len(), 1);
687 assert_eq!(groups[0].representative, "myc::atr");
688 assert_eq!(groups[0].aliases.len(), 3);
689 }
690
691 #[test]
692 fn covers_tag_on_a_longer_alias_still_counts_as_measured() {
693 let surf = surface_of(vec![
697 ("myc::atr", item("function", 42)),
698 ("myc::indicators::atr", item("function", 42)),
699 ]);
700 let g = &surf.grouped()[0];
701 assert!(
702 g.aliases
703 .iter()
704 .any(|a| a.as_str() == "myc::indicators::atr")
705 );
706 }
707
708 #[test]
709 fn distinct_functions_with_no_fingerprint_are_never_merged() {
710 let surf = surface_of(vec![
711 ("myc::a", item("function", 0)),
712 ("myc::b", item("function", 0)),
713 ]);
714 assert_eq!(surf.grouped().len(), 2);
715 }
716
717 #[test]
718 fn different_kinds_with_the_same_fingerprint_are_not_merged() {
719 let surf = surface_of(vec![
720 ("myc::a", item("function", 7)),
721 ("myc::A", item("struct", 7)),
722 ]);
723 assert_eq!(surf.grouped().len(), 2);
724 }
725
726 fn fingerprint_of(tag: &str, source: &str) -> (u64, String) {
727 fingerprint_of_kind(tag, "struct", source)
728 }
729
730 fn fingerprint_of_kind(tag: &str, kind: &str, source: &str) -> (u64, String) {
731 let dir = std::env::temp_dir().join(format!(
732 "soothfast-fingerprint-{}-{tag}",
733 std::process::id()
734 ));
735 std::fs::create_dir_all(&dir).unwrap();
736 std::fs::write(dir.join("lib.rs"), source).unwrap();
737 let span = json!({
738 "filename": "lib.rs",
739 "begin": [1, 0],
740 "end": [source.lines().count(), 0],
741 });
742 let text = read_span(&span, &dir, &mut HashMap::new()).unwrap();
743 let got = text_fingerprint(&text, kind);
744 let _ = std::fs::remove_dir_all(&dir);
745 got
746 }
747
748 #[test]
749 fn a_comment_only_edit_does_not_move_the_fingerprint() {
750 let plain = fingerprint_of("plain", "pub struct S {\n a: u8,\n}\n");
751 let noted = fingerprint_of(
752 "noted",
753 "pub struct S {\n // widened for the wire format\n a: u8,\n}\n",
754 );
755 assert_eq!(plain.0, noted.0);
756 }
757
758 #[test]
759 fn a_field_change_still_moves_the_fingerprint() {
760 let before = fingerprint_of("before", "pub struct S {\n a: u8,\n}\n");
761 let after = fingerprint_of("after", "pub struct S {\n a: u16,\n}\n");
762 assert_ne!(before.0, after.0);
763 }
764
765 #[test]
766 fn a_struct_field_addition_changes_the_signature() {
767 let before = fingerprint_of_kind(
768 "sig-before",
769 "struct",
770 "pub struct S {\n pub a: u8,\n}\n",
771 );
772 let after = fingerprint_of_kind(
773 "sig-after",
774 "struct",
775 "pub struct S {\n pub a: u8,\n pub b: u8,\n}\n",
776 );
777 assert_ne!(before.1, after.1);
778 assert_eq!(after.1, "pub struct S { pub a: u8, pub b: u8 }");
779 }
780
781 #[test]
782 fn a_private_field_edit_is_body_only() {
783 let before = fingerprint_of_kind(
784 "priv-before",
785 "struct",
786 "pub struct S {\n pub a: u8,\n b: u8,\n}\n",
787 );
788 let after = fingerprint_of_kind(
789 "priv-after",
790 "struct",
791 "pub struct S {\n pub a: u8,\n b: u16,\n c: u8,\n}\n",
792 );
793 assert_ne!(before.0, after.0);
794 assert_eq!(before.1, after.1);
795 assert_eq!(before.1, "pub struct S { pub a: u8 }");
796 }
797
798 #[test]
799 fn generic_fields_and_attributes_are_read_as_members() {
800 let got = fingerprint_of_kind(
801 "generic",
802 "struct",
803 "pub struct S {\n #[serde(rename = \"m\")]\n pub map: HashMap<String, Vec<u8>>,\n pub(crate) hidden: u8,\n}\n",
804 );
805 assert_eq!(got.1, "pub struct S { pub map: HashMap<String, Vec<u8>> }");
806 }
807
808 #[test]
809 fn a_documented_public_field_counts_as_signature() {
810 let before = fingerprint_of_kind(
811 "pubdoc-before",
812 "struct",
813 "pub struct S {\n /// count\n pub a: u8,\n}\n",
814 );
815 let after = fingerprint_of_kind(
816 "pubdoc-after",
817 "struct",
818 "pub struct S {\n /// count\n pub a: u8,\n /// total\n pub b: u8,\n}\n",
819 );
820 assert_ne!(before.1, after.1);
821 assert_eq!(after.1, "pub struct S { pub a: u8, pub b: u8 }");
822 }
823
824 #[test]
825 fn a_variant_doc_edit_moves_the_fingerprint_but_not_the_signature() {
826 let before = fingerprint_of_kind(
827 "vdoc-before",
828 "enum",
829 "pub enum E {\n /// first\n A,\n B,\n}\n",
830 );
831 let after = fingerprint_of_kind(
832 "vdoc-after",
833 "enum",
834 "pub enum E {\n /// the first\n A,\n B,\n}\n",
835 );
836 assert_ne!(before.0, after.0);
837 assert_eq!(before.1, after.1);
838 assert_eq!(before.1, "pub enum E { A, B }");
839 }
840
841 #[test]
842 fn a_function_pointer_field_does_not_swallow_its_neighbours() {
843 let got = fingerprint_of_kind(
844 "fnptr",
845 "struct",
846 "pub struct S {\n pub f: fn(u8) -> u8,\n pub g: u8,\n}\n",
847 );
848 assert_eq!(got.1, "pub struct S { pub f: fn(u8) -> u8, pub g: u8 }");
849 }
850
851 #[test]
852 fn an_enum_variant_addition_changes_the_signature() {
853 let before = fingerprint_of_kind("var-before", "enum", "pub enum E {\n A,\n}\n");
854 let after = fingerprint_of_kind("var-after", "enum", "pub enum E {\n A,\n B,\n}\n");
855 assert_ne!(before.1, after.1);
856 }
857
858 #[test]
859 fn a_function_body_edit_keeps_its_signature() {
860 let before = fingerprint_of_kind("fn-before", "function", "pub fn f() -> u8 {\n 1\n}\n");
861 let after = fingerprint_of_kind("fn-after", "function", "pub fn f() -> u8 {\n 2\n}\n");
862 assert_ne!(before.0, after.0);
863 assert_eq!(before.1, after.1);
864 assert_eq!(before.1, "pub fn f() -> u8");
865 }
866
867 #[test]
868 fn a_doc_comment_on_a_field_is_part_of_the_fingerprint() {
869 let before = fingerprint_of(
870 "doc-before",
871 "pub struct S {\n /// count\n a: u8,\n}\n",
872 );
873 let after = fingerprint_of(
874 "doc-after",
875 "pub struct S {\n /// total\n a: u8,\n}\n",
876 );
877 assert_ne!(before.0, after.0);
878 }
879}