//! Groundwork slice 5a-ii: every delete of a synced row names which of the five//! kinds it is. A Retract (a relation, a verb on `RETRACT_VERBS`, a machine//! reason on `MACHINE_RETRACTS`), an Erase, a Source-erase and a Revocation//! each mean something different on arrival, and a delete that names none//! leaves every device to guess. The writer has no plain `delete`, so the//! compiler holds the call sites; this scan holds the rest: nothing outside//! the sinks on `SINKS` builds a delete change by hand, and every retract//! names a verb or reason its list carries, and every listed one is used.//!//! It lives in cotton-tools, not beside the store's scans, because it reads//! the writer's two lists and cotton-store cannot depend on cotton-tools.use std::collections::BTreeSet;use std::path::{Path, PathBuf};use cotton_tools::mcp::writer::{MACHINE_RETRACTS, RETRACT_VERBS};/// The only production files that build a delete change themselves, each with/// why it may. The store's own machinery (`cotton-store/src`) is out of scope.const SINKS: &[(&str, &str)] = &[ ("cotton-tools/src/mcp/writer.rs","the writer's kind-named methods: retract, erase and source_erase each build their one change", ), ("cotton-rules/src/change.rs","a rule's planned Change has one delete constructor, retract, which names its kind (a Retract, the only delete a rule plans); the rule plans, its host writes", ), ("cotton-rules/src/import/message_changes.rs","an imported chat's emptied reaction retracts its one relation row (Delete::Retract), built where the import's other changes are", ),];fn crates_root() -> PathBuf { cotton_store::manifest_dir() .parent() .expect("cotton-store sits in the crates directory") .to_path_buf()}/// Every production source file under `crates/*/src` outside the store, as/// (path from `crates/`, text with any trailing `#[cfg(test)] mod …` cut off/// and comments blanked).fn sources() -> Vec<(String, String)> {let root = crates_root();letmut found = Vec::new();letmut crates: Vec<PathBuf> = std::fs::read_dir(&root) .expect("the crates directory") .filter_map(Result::ok) .map(|entry| entry.path().join("src")) .filter(|src| src.is_dir()) .collect(); crates.sort();for src in crates { walk(&src, &root, &mut found); } assert!( !found.is_empty(),"the scan found no production source files" ); found.retain(|(path, _)| !path.starts_with("cotton-store/src/")); found}fn walk(dir: &Path, root: &Path, found: &mutVec<(String, String)>) {letOk(entries) = std::fs::read_dir(dir) else {return; };letmut paths: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect(); paths.sort();for path in paths {if path.is_dir() { walk(&path, root, found);continue; }let name = path .file_name() .and_then(|n| n.to_str()) .unwrap_or_default();if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "tests.rs" {continue; }letOk(text) = std::fs::read_to_string(&path) else {continue; };let relative = path .strip_prefix(root) .unwrap_or(&path) .to_string_lossy() .replace('\\', "/"); found.push((relative, production_text(&text))); }}fn production_text(text: &str) -> String {let lines: Vec<&str> = text.lines().collect();letmut end = lines.len();for (index, line) in lines.iter().enumerate() {if line.trim() != "#[cfg(test)]" {continue; }let next = lines[index + 1..].iter().find(|l| !l.trim().is_empty());if next.is_some_and(|l| l.trim_start().starts_with("mod ") && l.trim_end().ends_with('{')) { end = index;break; } } lines[..end] .iter() .map(|line| match line.find("//") {Some(at) => &line[..at],None => line, }) .collect::<Vec<_>>() .join("\n")}/// Every place a delete change is BUILT: (file, line). A `Change::retract(`,/// a `LocalChange::delete(`, or `OpKind::Delete` / `Kind::Retract` used as a value — a struct field, an/// assignment, an argument. A match arm (`… =>`, `… |`, `matches!`) or a/// comparison (`==`, `!=`) only reads a kind and is not a site.fn builders(sources: &[(String, String)]) -> Vec<(String, usize)> {letmut found = Vec::new();for (path, text) in sources {for (index, line) in text.lines().enumerate() {if line.contains("Change::retract(") || line.contains("LocalChange::delete(") { found.push((path.clone(), index + 1));continue; }for token in ["OpKind::Delete", "Kind::Retract"] {letmut from = 0;whileletSome(at) = line[from..].find(token).map(|at| at + from) { from = at + token.len();// `OpKind::Delete` holds no `Kind::Retract`, but// `Kind::Retract` is found inside `canonical::Kind::Retract`// too, which is the same token; skip a match inside a// longer identifier only.let before_char = line[..at].chars().last();if before_char.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') {continue; }let before = line[..at] .trim_end_matches(|c: char| { c.is_ascii_alphanumeric() || c == '_' || c == ':' }) .trim_end();let after = line[from..].trim_start();let read = before.ends_with("==") || before.ends_with("!=") || before.ends_with('|') || before.contains("matches!(") || after.starts_with("=>") || after.starts_with('|') || after.starts_with("if ");if !read { found.push((path.clone(), index + 1)); } } } } } found}/// Every `Retract::<variant>(` in the sources: (file, line, the quoted name, or/// None when the argument is not a string literal).fn named(sources: &[(String, String)], variant: &str) -> Vec<(String, usize, Option<String>)> {let needle = format!("Retract::{variant}(");letmut found = Vec::new();for (path, text) in sources {for (index, line) in text.lines().enumerate() {letmut from = 0;whileletSome(at) = line[from..].find(&needle).map(|at| at + from) { from = at + needle.len();let rest = line[from..].trim_start();let name = rest .strip_prefix('"') .and_then(|quoted| quoted.split_once('"')) .map(|(name, _)| name.to_string()); found.push((path.clone(), index + 1, name)); } } } found}/// Checks one retract list against the literals the sources name: every name/// is a literal on the list, and every entry is named somewhere.fn check_list( sources: &[(String, String)], variant: &str, list_name: &str, list: &[&str], problems: &mutVec<String>,) {letmut used = BTreeSet::new();for (path, line, name) in named(sources, variant) {// The writer's own check reads the variant through a binding.if path == "cotton-tools/src/mcp/writer.rs" && name.is_none() {continue; }match name {None => problems.push(format!("{path}:{line} names `Retract::{variant}` with no string literal — name it in place" )),Some(name) if !list.contains(&name.as_str()) => problems.push(format!("{path}:{line} retracts as `Retract::{variant}(\"{name}\")`, which is not on {list_name}" )),Some(name) => { used.insert(name); } } }for entry in list {if !used.contains(*entry) { problems.push(format!("{list_name} lists \"{entry}\", which no site names — drop it" )); } }let unique: BTreeSet<&&str> = list.iter().collect();if unique.len() != list.len() { problems.push(format!("{list_name} names an entry twice")); }}/// RULE: Every place that deletes a synced row names its kind — a retract (relation, a listed verb, a listed machine reason), an erase, a source-erase or a revocation — and there is no delete that names none.#[test]fn every_delete_call_site_is_classified() {let sources = sources();letmut problems = Vec::new();let built = builders(&sources);for (path, line) in &built {if !SINKS.iter().any(|(file, _)| file == path) { problems.push(format!("{path}:{line} builds a delete change by hand — call the writer's retract, erase, \ source_erase or revoke, which name the kind" )); } }for (file, why) in SINKS { assert!(!why.trim().is_empty(), "{file} gives no reason");if !built.iter().any(|(path, _)| path == file) { problems.push(format!("SINKS lists {file}, which builds no delete change — drop it" )); } } check_list( &sources,"Verb","RETRACT_VERBS", RETRACT_VERBS, &mut problems, );letmut sorted = RETRACT_VERBS.to_vec(); sorted.sort_unstable();if sorted != RETRACT_VERBS { problems.push("RETRACT_VERBS is not sorted".to_string()); }let reasons: Vec<&str> = MACHINE_RETRACTS.iter().map(|(reason, _)| *reason).collect(); check_list( &sources,"Machine","MACHINE_RETRACTS", &reasons, &mut problems, );for (reason, what) in MACHINE_RETRACTS {if what.trim().is_empty() { problems.push(format!("MACHINE_RETRACTS gives \"{reason}\" no description" )); } } assert!( problems.is_empty(),"a delete that does not name its kind:\n{}", problems.join("\n") );}