use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use serde_json::Value;
mod counted;
mod generated;
#[cfg(test)]
mod generated_tests;
pub use counted::Counted;
#[derive(Debug, Clone)]
pub struct ItemInfo {
pub kind: String,
pub fingerprint: u64,
pub signature: String,
pub has_docs: bool,
pub example: bool,
pub spans: Vec<Span>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span {
pub file: String,
pub begin: u32,
pub end: u32,
}
#[derive(Debug, Default)]
pub struct Surface {
pub items: BTreeMap<String, ItemInfo>,
pub members: BTreeMap<String, ItemInfo>,
}
pub struct ItemGroup<'a> {
pub representative: &'a String,
pub aliases: Vec<&'a String>,
}
impl Surface {
pub fn lookup(&self, path: &str) -> Option<&ItemInfo> {
self.items.get(path).or_else(|| self.members.get(path))
}
pub fn grouped(&self) -> Vec<ItemGroup<'_>> {
let mut groups: HashMap<(&str, u64), Vec<&String>> = HashMap::new();
let mut unfingerprinted = Vec::new();
for (path, info) in &self.items {
if info.fingerprint == 0 {
unfingerprinted.push(path);
continue;
}
groups
.entry((info.kind.as_str(), info.fingerprint))
.or_default()
.push(path);
}
let mut out: Vec<ItemGroup<'_>> = groups
.into_values()
.map(|mut aliases| {
aliases.sort();
let representative = aliases.iter().min_by_key(|p| p.len()).copied().unwrap();
ItemGroup {
representative,
aliases,
}
})
.chain(unfingerprinted.into_iter().map(|p| ItemGroup {
representative: p,
aliases: vec![p],
}))
.collect();
out.sort_by(|a, b| a.representative.cmp(b.representative));
out
}
}
const KINDS: &[&str] = &[
"function",
"struct",
"enum",
"trait",
"constant",
"type_alias",
"module",
"static",
"union",
"macro",
"proc_macro",
];
pub fn from_rustdoc(doc: &Value, source_root: &Path) -> Surface {
from_rustdoc_with(doc, source_root, &BTreeMap::new())
}
pub fn from_rustdoc_with(
doc: &Value,
source_root: &Path,
dependencies: &BTreeMap<String, Surface>,
) -> Surface {
let mut surface = Surface::default();
let (Some(index), Some(paths)) = (doc["index"].as_object(), doc["paths"].as_object()) else {
return surface;
};
let mut file_cache: HashMap<String, Vec<String>> = HashMap::new();
let impl_spans = impl_method_spans(index);
for (id, item) in index {
if item["visibility"] != "public" {
continue;
}
let Some(inner) = item["inner"].as_object() else {
continue;
};
let Some(kind) = inner.keys().next().map(String::as_str) else {
continue;
};
if !KINDS.contains(&kind) {
continue;
}
let Some(full) = item_path(paths, id) else {
continue;
};
let (fingerprint, signature) =
item_fingerprint(index, item, kind, source_root, &mut file_cache)
.unwrap_or((0, String::new()));
let docs = item["docs"].as_str().unwrap_or_default();
let spans = item_spans(item, id, kind, &impl_spans);
surface.items.insert(
full,
ItemInfo {
kind: kind.to_string(),
fingerprint,
signature,
has_docs: !docs.trim().is_empty(),
example: has_example(docs),
spans,
},
);
}
let links = Links {
index,
paths,
crates: &doc["external_crates"],
dependencies,
};
alias_reexports(&links, &mut surface);
index_members(index, paths, source_root, &mut file_cache, &mut surface);
surface
}
fn span_of(item: &Value) -> Option<Span> {
let span = &item["span"];
Some(Span {
file: span["filename"].as_str()?.to_string(),
begin: u32::try_from(span["begin"][0].as_u64()?).ok()?,
end: u32::try_from(span["end"][0].as_u64()?).ok()?,
})
}
const IMPLEMENTED_KINDS: [&str; 4] = ["struct", "enum", "union", "trait"];
fn item_spans(
item: &Value,
id: &str,
kind: &str,
impl_spans: &HashMap<String, Vec<Span>>,
) -> Vec<Span> {
let mut spans: Vec<Span> = span_of(item).into_iter().collect();
if IMPLEMENTED_KINDS.contains(&kind) {
spans.extend(impl_spans.get(id).into_iter().flatten().cloned());
}
spans
}
fn impl_method_spans(index: &serde_json::Map<String, Value>) -> HashMap<String, Vec<Span>> {
let mut by_type: HashMap<String, Vec<Span>> = HashMap::new();
for item in index.values() {
let imp = &item["inner"]["impl"];
let Some(type_id) = imp["for"]["resolved_path"]["id"].as_u64() else {
continue;
};
let methods = imp["items"]
.as_array()
.into_iter()
.flatten()
.filter_map(|id| index.get(&id.as_u64()?.to_string()))
.filter(|member| member["inner"]["function"].is_object())
.filter_map(span_of);
by_type
.entry(type_id.to_string())
.or_default()
.extend(methods);
}
by_type
}
fn has_example(docs: &str) -> bool {
crate::markdown::scan(docs).is_ok_and(|doc| doc.blocks.iter().any(|b| b.is_rust_example()))
}
pub fn reexported_crates(doc: &Value) -> BTreeSet<String> {
let (Some(index), Some(paths)) = (doc["index"].as_object(), doc["paths"].as_object()) else {
return BTreeSet::new();
};
index
.values()
.filter(|item| item["visibility"] == "public")
.filter_map(|item| item["inner"]["use"]["id"].as_u64())
.filter(|id| !index.contains_key(&id.to_string()))
.filter_map(|id| {
let crate_id = paths.get(&id.to_string())?["crate_id"].as_u64()?;
let name = doc["external_crates"][crate_id.to_string()]["name"].as_str()?;
Some(name.to_string())
})
.collect()
}
fn index_members(
index: &serde_json::Map<String, Value>,
paths: &serde_json::Map<String, Value>,
source_root: &Path,
file_cache: &mut HashMap<String, Vec<String>>,
surface: &mut Surface,
) {
for item in index.values() {
let imp = &item["inner"]["impl"];
if !imp.is_object() || imp["trait"].is_object() {
continue;
}
let Some(type_id) = imp["for"]["resolved_path"]["id"].as_u64() else {
continue;
};
let Some(type_path) = item_path(paths, &type_id.to_string()) else {
continue;
};
let Some(owner) = surface.items.get(&type_path) else {
continue;
};
let spellings: Vec<String> = surface
.items
.iter()
.filter(|(_, info)| info.kind == owner.kind && info.fingerprint == owner.fingerprint)
.map(|(path, _)| path.clone())
.collect();
let members = imp["items"].as_array().into_iter().flatten();
for member in members.filter_map(|id| index.get(&id.as_u64()?.to_string())) {
if member["visibility"] != "public" {
continue;
}
let (kind, name) = match (
member["inner"]["function"].is_object(),
member["inner"]["assoc_const"].is_object(),
member["name"].as_str(),
) {
(true, _, Some(name)) => ("function", name),
(_, true, Some(name)) => ("constant", name),
_ => continue,
};
let (fingerprint, signature) =
item_fingerprint(index, member, kind, source_root, file_cache)
.unwrap_or((0, String::new()));
let docs = member["docs"].as_str().unwrap_or_default();
let info = ItemInfo {
kind: kind.to_string(),
fingerprint,
signature,
has_docs: !docs.trim().is_empty(),
example: has_example(docs),
spans: span_of(member).into_iter().collect(),
};
for spelling in &spellings {
surface
.members
.insert(format!("{spelling}::{name}"), info.clone());
}
}
}
}
fn alias_reexports(links: &Links<'_>, surface: &mut Surface) {
for (mod_id, item) in links.index {
if item["visibility"] != "public" {
continue;
}
let Some(children) = item["inner"]["module"]["items"].as_array() else {
continue;
};
let Some(mod_path) = item_path(links.paths, mod_id) else {
continue;
};
for child in children {
let Some(child_id) = child.as_u64() else {
continue;
};
let child_id = child_id.to_string();
let Some(use_) = links.index.get(&child_id).map(|c| &c["inner"]["use"]) else {
continue;
};
let Some(target_id) = use_["id"].as_u64() else {
continue;
};
if use_["is_glob"].as_bool().unwrap_or(false) {
links.alias_glob(surface, &mod_path, target_id);
} else if let Some(name) = use_["name"].as_str() {
links.alias(surface, &mod_path, name, target_id);
}
}
}
}
struct Links<'a> {
index: &'a serde_json::Map<String, Value>,
paths: &'a serde_json::Map<String, Value>,
crates: &'a Value,
dependencies: &'a BTreeMap<String, Surface>,
}
impl Links<'_> {
fn external(&self, id: u64) -> Option<(&Surface, String)> {
let id = id.to_string();
if self.index.contains_key(&id) {
return None;
}
let crate_id = self.paths.get(&id)?["crate_id"].as_u64()?;
let name = self.crates[crate_id.to_string()]["name"].as_str()?;
Some((self.dependencies.get(name)?, item_path(self.paths, &id)?))
}
fn alias(&self, surface: &mut Surface, mod_path: &str, name: &str, target_id: u64) {
match self.external(target_id) {
Some((dep, from)) => {
alias_external(dep, &from, &format!("{mod_path}::{name}"), false, surface)
}
None => alias_one(self.paths, surface, mod_path, name, target_id),
}
}
fn alias_glob(&self, surface: &mut Surface, mod_path: &str, module_id: u64) {
if let Some((dep, from)) = self.external(module_id) {
return alias_external(dep, &from, mod_path, true, surface);
}
let Some(children) = self
.index
.get(&module_id.to_string())
.and_then(|m| m["inner"]["module"]["items"].as_array())
else {
return;
};
for id in children.iter().filter_map(Value::as_u64) {
let Some(child) = self.index.get(&id.to_string()) else {
continue;
};
let use_ = &child["inner"]["use"];
match (use_["id"].as_u64(), use_["is_glob"].as_bool()) {
(Some(target), Some(true)) => {
if let Some((dep, from)) = self.external(target) {
alias_external(dep, &from, mod_path, true, surface);
}
}
(Some(target), _) => {
if let Some(name) = use_["name"].as_str() {
self.alias(surface, mod_path, name, target);
}
}
(None, _) => {
if let Some(name) = child["name"].as_str() {
alias_one(self.paths, surface, mod_path, name, id);
}
}
}
}
}
}
fn alias_one(
paths: &serde_json::Map<String, Value>,
surface: &mut Surface,
mod_path: &str,
name: &str,
target_id: u64,
) {
let Some(target_path) = item_path(paths, &target_id.to_string()) else {
return;
};
let Some(info) = surface.items.get(&target_path).cloned() else {
return; };
let alias = format!("{mod_path}::{name}");
if alias == target_path {
return;
}
surface.items.entry(alias).or_insert(info);
}
fn alias_external(dep: &Surface, from: &str, to: &str, glob: bool, surface: &mut Surface) {
let below = |entries: &BTreeMap<String, ItemInfo>| -> Vec<(String, ItemInfo)> {
entries
.iter()
.filter_map(|(path, info)| {
let rest = path.strip_prefix(from)?;
let taken = rest.starts_with("::") || (rest.is_empty() && !glob);
taken.then(|| (format!("{to}{rest}"), info.clone()))
})
.collect()
};
for (path, info) in below(&dep.items) {
surface.items.entry(path).or_insert(info);
}
for (path, info) in below(&dep.members) {
surface.members.entry(path).or_insert(info);
}
}
fn item_path(paths: &serde_json::Map<String, Value>, id: &str) -> Option<String> {
let segs = paths.get(id)?["path"].as_array()?;
Some(
segs.iter()
.filter_map(Value::as_str)
.collect::<Vec<_>>()
.join("::"),
)
}
const MEMBER_KINDS: [&str; 3] = ["struct", "enum", "union"];
fn item_fingerprint(
index: &serde_json::Map<String, Value>,
item: &Value,
kind: &str,
root: &Path,
cache: &mut HashMap<String, Vec<String>>,
) -> Option<(u64, String)> {
let span_text = read_span(&item["span"], root, cache)?;
let bare = normalize(&crate::comments::strip_all(&span_text));
let name = item["name"].as_str().unwrap_or_default();
if !generated::is_macro_call(&bare[..declaration_end(&bare)], name, kind) {
return Some(text_fingerprint(&span_text, kind));
}
let declaration = generated::declaration(index, item, kind, false);
let docs = item["docs"].as_str().unwrap_or_default();
Some((
generated::fingerprint(&declaration, docs),
generated::declaration(index, item, kind, true),
))
}
fn declaration_end(bare: &str) -> usize {
bare.find('{')
.or_else(|| bare.find(';'))
.unwrap_or(bare.len())
}
fn read_span(
span: &Value,
root: &Path,
cache: &mut HashMap<String, Vec<String>>,
) -> Option<String> {
let filename = span["filename"].as_str()?;
let begin = span["begin"].as_array()?;
let end = span["end"].as_array()?;
let (bl, el) = (begin[0].as_u64()? as usize, end[0].as_u64()? as usize);
let lines = match cache.get(filename) {
Some(l) => l,
None => {
let abs = root.join(filename);
let text = std::fs::read_to_string(&abs).ok()?;
cache.insert(
filename.to_string(),
text.lines().map(str::to_string).collect(),
);
&cache[filename]
}
};
if bl == 0 || el > lines.len() || bl > el {
return None;
}
Some(lines[bl - 1..el].join("\n"))
}
fn text_fingerprint(span_text: &str, kind: &str) -> (u64, String) {
let normalized = normalize(&crate::comments::strip(span_text));
let bare = normalize(&crate::comments::strip_all(span_text));
let sig_end = declaration_end(&bare);
let declaration = bare[..sig_end].trim();
let signature = if MEMBER_KINDS.contains(&kind) {
member_signature(declaration, &bare[sig_end..], kind == "enum")
} else {
declaration.to_string()
};
(soothfast_registry::fnv1a(normalized.as_bytes()), signature)
}
fn normalize(source: &str) -> String {
source.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn member_signature(declaration: &str, rest: &str, all_public: bool) -> String {
let Some(body) = rest
.strip_prefix('{')
.and_then(|inner| inner.trim_end().strip_suffix('}'))
else {
return declaration.to_string();
};
let members: Vec<String> = split_top_level(body)
.into_iter()
.map(|member| strip_attributes(member.trim()).to_string())
.filter(|member| !member.is_empty() && (all_public || member.starts_with("pub ")))
.collect();
format!("{declaration} {{ {} }}", members.join(", "))
}
fn split_top_level(text: &str) -> Vec<&str> {
let mut parts = Vec::new();
let mut depth = 0i32;
let mut start = 0;
let mut prev = ' ';
for (i, c) in text.char_indices() {
match c {
'<' | '(' | '[' | '{' => depth += 1,
'>' if prev == '-' => {}
'>' | ')' | ']' | '}' => depth -= 1,
',' if depth == 0 => {
parts.push(&text[start..i]);
start = i + 1;
}
_ => {}
}
prev = c;
}
parts.push(&text[start..]);
parts
}
fn strip_attributes(member: &str) -> &str {
let mut rest = member;
while let Some(after) = rest.strip_prefix("#[") {
let mut depth = 1;
let mut end = None;
for (i, c) in after.char_indices() {
depth += match c {
'[' => 1,
']' => -1,
_ => 0,
};
if depth == 0 {
end = Some(i + 1);
break;
}
}
match end {
Some(e) => rest = after[e..].trim_start(),
None => break,
}
}
rest
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn private_submodule_reexport_doc() -> Value {
json!({
"index": {
"1": {
"visibility": "public",
"inner": { "module": { "items": [2, 3] } },
},
"2": {
"name": "sma",
"visibility": "public",
"inner": { "function": {} },
"span": { "filename": "src/sma.rs", "begin": [1, 0], "end": [1, 0] },
"docs": "Simple moving average.",
},
"3": {
"visibility": "public",
"inner": {
"use": { "source": "sma::sma", "name": "sma", "id": 2, "is_glob": false },
},
},
},
"paths": {
"1": { "path": ["myc", "indicators"], "kind": "module" },
"2": { "path": ["myc", "indicators", "sma", "sma"], "kind": "function" },
},
})
}
#[test]
fn reexport_alias_resolves_alongside_canonical_path() {
let dir =
std::env::temp_dir().join(format!("soothfast-surface-test-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
let doc = private_submodule_reexport_doc();
let surface = from_rustdoc(&doc, &dir);
assert!(surface.items.contains_key("myc::indicators::sma::sma"));
assert!(
surface.items.contains_key("myc::indicators::sma"),
"expected the flattened re-export path to resolve too: {:?}",
surface.items.keys().collect::<Vec<_>>()
);
let canonical = &surface.items["myc::indicators::sma::sma"];
let alias = &surface.items["myc::indicators::sma"];
assert_eq!(canonical.fingerprint, alias.fingerprint);
assert_eq!(alias.kind, "function");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn glob_reexport_aliases_every_child_by_its_own_name() {
let mut doc = private_submodule_reexport_doc();
doc["index"]["3"]["inner"]["use"] =
json!({ "source": "sma", "name": "sma", "id": 7, "is_glob": true });
doc["index"]["7"] = json!({
"visibility": "public",
"inner": { "module": { "items": [2] } },
});
let dir =
std::env::temp_dir().join(format!("soothfast-surface-glob-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
let surface = from_rustdoc(&doc, &dir);
assert!(surface.items.contains_key("myc::indicators::sma::sma"));
assert!(surface.items.contains_key("myc::indicators::sma"));
let _ = std::fs::remove_dir_all(&dir);
}
fn impl_doc() -> Value {
let span =
|line: u64| json!({ "filename": "src/lib.rs", "begin": [line, 0], "end": [line, 0] });
json!({
"index": {
"1": { "visibility": "public", "inner": { "module": { "items": [2, 20] } } },
"2": {
"name": "Rewriter",
"visibility": "public",
"inner": { "struct": {} },
"span": span(1),
},
"3": {
"visibility": "default",
"inner": { "impl": {
"trait": null,
"for": { "resolved_path": { "id": 2 } },
"items": [4, 5, 6],
} },
},
"4": {
"name": "rewrite",
"visibility": "public",
"inner": { "function": {} },
"span": span(2),
},
"5": {
"name": "hidden",
"visibility": "default",
"inner": { "function": {} },
"span": span(3),
},
"6": {
"name": "LIMIT",
"visibility": "public",
"inner": { "assoc_const": {} },
"span": span(4),
},
"8": {
"visibility": "default",
"inner": { "impl": {
"trait": { "path": "Default" },
"for": { "resolved_path": { "id": 2 } },
"items": [7],
} },
},
"7": {
"name": "default",
"visibility": "public",
"inner": { "function": {} },
"span": span(5),
},
"20": {
"visibility": "public",
"inner": { "use": { "name": "Rewriter", "id": 2, "is_glob": false } },
},
},
"paths": {
"1": { "path": ["rw"], "kind": "module" },
"2": { "path": ["rw", "engine", "Rewriter"], "kind": "struct" },
},
})
}
#[test]
fn inherent_pub_members_resolve_under_the_type_path() {
let dir =
std::env::temp_dir().join(format!("soothfast-surface-impl-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
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();
let surface = from_rustdoc(&impl_doc(), &dir);
let method = surface.lookup("rw::engine::Rewriter::rewrite").unwrap();
assert_eq!(method.kind, "function");
assert_ne!(method.fingerprint, 0);
assert_eq!(
surface.lookup("rw::engine::Rewriter::LIMIT").unwrap().kind,
"constant"
);
assert!(surface.lookup("rw::engine::Rewriter::hidden").is_none());
assert!(surface.lookup("rw::engine::Rewriter::default").is_none());
assert!(surface.items.keys().all(|k| !k.ends_with("::rewrite")));
assert_eq!(
surface.lookup("rw::Rewriter::rewrite").unwrap().fingerprint,
method.fingerprint
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_fenced_rust_example_in_the_docs_is_recorded() {
let doc = |docs: &str| {
json!({
"index": { "1": {
"name": "f",
"visibility": "public",
"docs": docs,
"inner": { "function": {} },
} },
"paths": { "1": { "path": ["a", "f"], "kind": "function" } },
})
};
let at = Path::new(".");
let with = from_rustdoc(&doc("Runs.\n\n```\nf();\n```\n"), at);
let without = from_rustdoc(&doc("Runs.\n\n```text\nf()\n```\n"), at);
assert!(with.items["a::f"].example && with.items["a::f"].has_docs);
assert!(!without.items["a::f"].example && without.items["a::f"].has_docs);
}
#[test]
fn counted_takes_inherent_methods_and_leaves_trait_impls_and_private_ones() {
let dir =
std::env::temp_dir().join(format!("soothfast-surface-counted-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
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();
let surface = from_rustdoc(&impl_doc(), &dir);
let paths: Vec<_> = surface.counted().into_iter().map(|c| c.path).collect();
assert_eq!(paths, ["rw", "rw::Rewriter", "rw::Rewriter::rewrite"]);
let _ = std::fs::remove_dir_all(&dir);
}
fn item(kind: &str, fingerprint: u64) -> ItemInfo {
ItemInfo {
kind: kind.to_string(),
fingerprint,
signature: String::new(),
has_docs: false,
spans: Vec::new(),
example: false,
}
}
fn surface_of(items: Vec<(&str, ItemInfo)>) -> Surface {
Surface {
items: items.into_iter().map(|(p, i)| (p.to_string(), i)).collect(),
..Surface::default()
}
}
fn facade_doc() -> Value {
let use_ = |name: &str, id: u64, is_glob: bool| {
json!({
"visibility": "public",
"inner": { "use": { "name": name, "id": id, "is_glob": is_glob } },
})
};
json!({
"index": {
"1": { "visibility": "public", "inner": { "module": { "items": [2, 3, 4, 5, 8, 9, 10] } } },
"2": use_("named", 20, false),
"3": use_("indicators", 21, false),
"4": use_("prelude", 22, true),
"5": use_("Counter", 23, false),
"6": { "visibility": "default", "inner": { "module": { "items": [7] } } },
"7": use_("Two", 24, false),
"8": use_("inner", 6, true),
"9": use_("fmt", 30, false),
"10": use_("renamed", 25, false),
},
"paths": {
"1": { "crate_id": 0, "path": ["a"], "kind": "module" },
"6": { "crate_id": 0, "path": ["a", "inner"], "kind": "module" },
"20": { "crate_id": 1, "path": ["b", "named"], "kind": "function" },
"21": { "crate_id": 1, "path": ["b", "indicators"], "kind": "module" },
"22": { "crate_id": 1, "path": ["b", "prelude"], "kind": "module" },
"23": { "crate_id": 1, "path": ["b", "Counter"], "kind": "struct" },
"24": { "crate_id": 1, "path": ["b", "Two"], "kind": "struct" },
"25": { "crate_id": 1, "path": ["b"], "kind": "module" },
"30": { "crate_id": 2, "path": ["std", "fmt"], "kind": "module" },
},
"external_crates": { "1": { "name": "b" }, "2": { "name": "std" } },
})
}
fn documented(kind: &str, fingerprint: u64) -> ItemInfo {
ItemInfo {
has_docs: true,
..item(kind, fingerprint)
}
}
fn dependency_b() -> BTreeMap<String, Surface> {
let mut b = surface_of(vec![
("b", item("module", 1)),
("b::named", documented("function", 2)),
("b::indicators", item("module", 3)),
("b::indicators::sma", documented("function", 4)),
("b::prelude", item("module", 5)),
("b::prelude::one", documented("function", 6)),
("b::Counter", documented("struct", 7)),
("b::Two", item("struct", 8)),
]);
b.members
.insert("b::Counter::new".to_string(), documented("function", 9));
BTreeMap::from([("b".to_string(), b)])
}
#[test]
fn a_reexport_from_another_crate_takes_the_defining_crates_info() {
let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
let named = &surface.items["a::named"];
assert_eq!((named.kind.as_str(), named.fingerprint), ("function", 2));
assert!(named.has_docs);
assert_eq!(surface.items["a::Counter"].fingerprint, 7);
assert_eq!(surface.members["a::Counter::new"].fingerprint, 9);
assert!(surface.lookup("a::Counter::new").unwrap().has_docs);
assert!(surface.items.keys().all(|k| !k.starts_with("b::")));
assert!(surface.members.keys().all(|k| !k.starts_with("b::")));
}
#[test]
fn a_reexported_module_brings_what_is_below_it() {
let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
assert_eq!(surface.items["a::indicators"].kind, "module");
assert_eq!(surface.items["a::indicators::sma"].fingerprint, 4);
}
#[test]
fn a_renamed_crate_reexport_brings_everything_below_the_crate() {
let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
assert_eq!(surface.items["a::renamed"].kind, "module");
assert_eq!(surface.items["a::renamed::named"].fingerprint, 2);
assert_eq!(surface.items["a::renamed::indicators::sma"].fingerprint, 4);
assert_eq!(surface.members["a::renamed::Counter::new"].fingerprint, 9);
}
#[test]
fn a_glob_of_another_crates_module_takes_its_children_not_the_module() {
let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
assert_eq!(surface.items["a::one"].fingerprint, 6);
assert!(!surface.items.contains_key("a::prelude"));
}
#[test]
fn a_glob_of_a_local_module_takes_its_named_reexports() {
let surface = from_rustdoc_with(&facade_doc(), Path::new("."), &dependency_b());
assert_eq!(surface.items["a::Two"].fingerprint, 8);
}
#[test]
fn a_glob_of_a_local_module_takes_a_local_named_reexport_once() {
let mut doc = private_submodule_reexport_doc();
doc["index"]["1"]["inner"]["module"]["items"] = json!([2, 3, 8]);
doc["index"]["7"] = json!({
"visibility": "default",
"inner": { "module": { "items": [9] } },
});
doc["index"]["8"] = json!({
"visibility": "public",
"inner": { "use": { "name": "inner", "id": 7, "is_glob": true } },
});
doc["index"]["9"] = json!({
"visibility": "public",
"inner": { "use": { "name": "average", "id": 2, "is_glob": false } },
});
let dir =
std::env::temp_dir().join(format!("soothfast-surface-inner-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(dir.join("src/sma.rs"), "pub fn sma() {}\n").unwrap();
let surface = from_rustdoc(&doc, &dir);
let alias = &surface.items["myc::indicators::average"];
assert_eq!(
alias.fingerprint,
surface.items["myc::indicators::sma"].fingerprint
);
let functions: Vec<_> = surface
.grouped()
.into_iter()
.filter(|g| surface.items[g.representative].kind == "function")
.collect();
assert_eq!(functions.len(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_crate_without_a_known_surface_stays_unresolved() {
let surface = from_rustdoc(&facade_doc(), Path::new("."));
assert_eq!(surface.items.keys().collect::<Vec<_>>(), ["a"]);
}
#[test]
fn reexported_crates_names_each_crate_a_pub_use_reaches() {
let crates = reexported_crates(&facade_doc());
assert_eq!(crates.into_iter().collect::<Vec<_>>(), ["b", "std"]);
assert!(reexported_crates(&impl_doc()).is_empty());
}
#[test]
fn three_aliases_of_one_function_collapse_to_one_group() {
let surf = surface_of(vec![
("myc::atr", item("function", 42)),
("myc::indicators::atr", item("function", 42)),
("myc::indicators::atr::atr", item("function", 42)),
]);
let groups = surf.grouped();
assert_eq!(groups.len(), 1);
assert_eq!(groups[0].representative, "myc::atr");
assert_eq!(groups[0].aliases.len(), 3);
}
#[test]
fn covers_tag_on_a_longer_alias_still_counts_as_measured() {
let surf = surface_of(vec![
("myc::atr", item("function", 42)),
("myc::indicators::atr", item("function", 42)),
]);
let g = &surf.grouped()[0];
assert!(
g.aliases
.iter()
.any(|a| a.as_str() == "myc::indicators::atr")
);
}
#[test]
fn distinct_functions_with_no_fingerprint_are_never_merged() {
let surf = surface_of(vec![
("myc::a", item("function", 0)),
("myc::b", item("function", 0)),
]);
assert_eq!(surf.grouped().len(), 2);
}
#[test]
fn different_kinds_with_the_same_fingerprint_are_not_merged() {
let surf = surface_of(vec![
("myc::a", item("function", 7)),
("myc::A", item("struct", 7)),
]);
assert_eq!(surf.grouped().len(), 2);
}
fn fingerprint_of(tag: &str, source: &str) -> (u64, String) {
fingerprint_of_kind(tag, "struct", source)
}
fn fingerprint_of_kind(tag: &str, kind: &str, source: &str) -> (u64, String) {
let dir = std::env::temp_dir().join(format!(
"soothfast-fingerprint-{}-{tag}",
std::process::id()
));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("lib.rs"), source).unwrap();
let span = json!({
"filename": "lib.rs",
"begin": [1, 0],
"end": [source.lines().count(), 0],
});
let text = read_span(&span, &dir, &mut HashMap::new()).unwrap();
let got = text_fingerprint(&text, kind);
let _ = std::fs::remove_dir_all(&dir);
got
}
#[test]
fn a_comment_only_edit_does_not_move_the_fingerprint() {
let plain = fingerprint_of("plain", "pub struct S {\n a: u8,\n}\n");
let noted = fingerprint_of(
"noted",
"pub struct S {\n // widened for the wire format\n a: u8,\n}\n",
);
assert_eq!(plain.0, noted.0);
}
#[test]
fn a_field_change_still_moves_the_fingerprint() {
let before = fingerprint_of("before", "pub struct S {\n a: u8,\n}\n");
let after = fingerprint_of("after", "pub struct S {\n a: u16,\n}\n");
assert_ne!(before.0, after.0);
}
#[test]
fn a_struct_field_addition_changes_the_signature() {
let before = fingerprint_of_kind(
"sig-before",
"struct",
"pub struct S {\n pub a: u8,\n}\n",
);
let after = fingerprint_of_kind(
"sig-after",
"struct",
"pub struct S {\n pub a: u8,\n pub b: u8,\n}\n",
);
assert_ne!(before.1, after.1);
assert_eq!(after.1, "pub struct S { pub a: u8, pub b: u8 }");
}
#[test]
fn a_private_field_edit_is_body_only() {
let before = fingerprint_of_kind(
"priv-before",
"struct",
"pub struct S {\n pub a: u8,\n b: u8,\n}\n",
);
let after = fingerprint_of_kind(
"priv-after",
"struct",
"pub struct S {\n pub a: u8,\n b: u16,\n c: u8,\n}\n",
);
assert_ne!(before.0, after.0);
assert_eq!(before.1, after.1);
assert_eq!(before.1, "pub struct S { pub a: u8 }");
}
#[test]
fn generic_fields_and_attributes_are_read_as_members() {
let got = fingerprint_of_kind(
"generic",
"struct",
"pub struct S {\n #[serde(rename = \"m\")]\n pub map: HashMap<String, Vec<u8>>,\n pub(crate) hidden: u8,\n}\n",
);
assert_eq!(got.1, "pub struct S { pub map: HashMap<String, Vec<u8>> }");
}
#[test]
fn a_documented_public_field_counts_as_signature() {
let before = fingerprint_of_kind(
"pubdoc-before",
"struct",
"pub struct S {\n /// count\n pub a: u8,\n}\n",
);
let after = fingerprint_of_kind(
"pubdoc-after",
"struct",
"pub struct S {\n /// count\n pub a: u8,\n /// total\n pub b: u8,\n}\n",
);
assert_ne!(before.1, after.1);
assert_eq!(after.1, "pub struct S { pub a: u8, pub b: u8 }");
}
#[test]
fn a_variant_doc_edit_moves_the_fingerprint_but_not_the_signature() {
let before = fingerprint_of_kind(
"vdoc-before",
"enum",
"pub enum E {\n /// first\n A,\n B,\n}\n",
);
let after = fingerprint_of_kind(
"vdoc-after",
"enum",
"pub enum E {\n /// the first\n A,\n B,\n}\n",
);
assert_ne!(before.0, after.0);
assert_eq!(before.1, after.1);
assert_eq!(before.1, "pub enum E { A, B }");
}
#[test]
fn a_function_pointer_field_does_not_swallow_its_neighbours() {
let got = fingerprint_of_kind(
"fnptr",
"struct",
"pub struct S {\n pub f: fn(u8) -> u8,\n pub g: u8,\n}\n",
);
assert_eq!(got.1, "pub struct S { pub f: fn(u8) -> u8, pub g: u8 }");
}
#[test]
fn an_enum_variant_addition_changes_the_signature() {
let before = fingerprint_of_kind("var-before", "enum", "pub enum E {\n A,\n}\n");
let after = fingerprint_of_kind("var-after", "enum", "pub enum E {\n A,\n B,\n}\n");
assert_ne!(before.1, after.1);
}
#[test]
fn a_function_body_edit_keeps_its_signature() {
let before = fingerprint_of_kind("fn-before", "function", "pub fn f() -> u8 {\n 1\n}\n");
let after = fingerprint_of_kind("fn-after", "function", "pub fn f() -> u8 {\n 2\n}\n");
assert_ne!(before.0, after.0);
assert_eq!(before.1, after.1);
assert_eq!(before.1, "pub fn f() -> u8");
}
#[test]
fn a_doc_comment_on_a_field_is_part_of_the_fingerprint() {
let before = fingerprint_of(
"doc-before",
"pub struct S {\n /// count\n a: u8,\n}\n",
);
let after = fingerprint_of(
"doc-after",
"pub struct S {\n /// total\n a: u8,\n}\n",
);
assert_ne!(before.0, after.0);
}
fn span(file: &str, begin: u32, end: u32) -> Span {
Span {
file: file.into(),
begin,
end,
}
}
fn spans_doc() -> Value {
let at = |begin: u32, end: u32| json!({ "filename": "src/lib.rs", "begin": [begin, 0], "end": [end, 1] });
let method = |name: &str, begin: u32, end: u32| {
json!({
"name": name,
"visibility": "public",
"inner": { "function": {} },
"span": at(begin, end),
})
};
json!({
"index": {
"1": { "name": "run", "visibility": "public", "inner": { "function": {} }, "span": at(1, 3) },
"2": { "name": "Meter", "visibility": "public", "inner": { "struct": {} }, "span": at(5, 5) },
"3": { "inner": { "impl": { "for": { "resolved_path": { "id": 2 } }, "items": [4] } } },
"4": method("read", 8, 10),
"5": { "inner": { "impl": { "trait": { "id": 9 }, "for": { "resolved_path": { "id": 2 } }, "items": [6] } } },
"6": method("fmt", 14, 16),
"7": { "inner": { "impl": { "for": { "generic": "T" }, "items": [8] } } },
"8": method("blanket", 20, 22),
},
"paths": {
"1": { "path": ["demo", "run"], "kind": "function" },
"2": { "path": ["demo", "Meter"], "kind": "struct" },
},
})
}
#[test]
fn a_function_carries_its_own_span() {
let surface = from_rustdoc(&spans_doc(), Path::new("/nowhere"));
assert_eq!(surface.items["demo::run"].spans, [span("src/lib.rs", 1, 3)]);
}
#[test]
fn a_struct_carries_the_spans_of_its_inherent_and_trait_methods() {
let surface = from_rustdoc(&spans_doc(), Path::new("/nowhere"));
let spans = &surface.items["demo::Meter"].spans;
assert_eq!(
spans,
&[
span("src/lib.rs", 5, 5),
span("src/lib.rs", 8, 10),
span("src/lib.rs", 14, 16),
]
);
}
#[test]
fn an_inherent_member_carries_its_own_span() {
let surface = from_rustdoc(&spans_doc(), Path::new("/nowhere"));
assert_eq!(
surface.members["demo::Meter::read"].spans,
[span("src/lib.rs", 8, 10)]
);
}
}