use serde::{Deserialize, Serialize};
use crate::anchor::{AnchorGrain, AnchorHashStability, prepared_content_hash};
use crate::entity::Entity;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Touchpoint {
PreparedForm,
DeliveryUnits,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Preparation {
pub id: &'static str,
pub touchpoint: Touchpoint,
pub grains: &'static [AnchorGrain],
pub description: &'static str,
}
pub const ENTITY_LOAD_BEARING: &str = "entity-load-bearing";
pub const DATED_ENTRIES: &str = "dated-entries";
pub const WHOLE_FILE_UNIT: &str = "whole";
pub const CODE_MAP: &str = "code-map";
pub const QUOTED_PHRASE: &str = "quoted-phrase";
pub const REGISTRY: &[Preparation] = &[
Preparation {
id: ENTITY_LOAD_BEARING,
touchpoint: Touchpoint::PreparedForm,
grains: &[AnchorGrain::Entity],
description: "an entity's prepared form is the stable serialization of its type's \
load-bearing sections (explicitly declared, else the required sections, \
else every section) — notes-only edits keep dependents' anchors resolving",
},
Preparation {
id: DATED_ENTRIES,
touchpoint: Touchpoint::DeliveryUnits,
grains: &[AnchorGrain::Span],
description: "a file is a sequence of entries opening with an ISO date or date-time; \
each entry is one delivery unit `<path>#<stamp>`, and a source's units \
deliver in stamp order, identical on every pass — a chronological corpus \
(logs, transcripts, journals, mail threads) is never shuffled",
},
Preparation {
id: CODE_MAP,
touchpoint: Touchpoint::PreparedForm,
grains: &[AnchorGrain::File, AnchorGrain::Span, AnchorGrain::Tree],
description: "a scoped code file's prepared form is its interface digest (imports, \
exports, declarations and their signatures; comments, formatting and \
bodies invisible), and a tree's is the digest of every scoped file under \
it — an anchor drifts when an interface changes and stays quiet when \
only an implementation does",
},
Preparation {
id: QUOTED_PHRASE,
touchpoint: Touchpoint::PreparedForm,
grains: &[AnchorGrain::Span, AnchorGrain::Url, AnchorGrain::Entity],
description: "an artifact `<path-or-url-or-entity>#<phrase>` addresses the occurrence of \
a literal phrase in a text and its prepared form is the phrase itself — the \
anchor resolves while the file, the observed page or the entity still says \
those words and reads orphaned once they are gone, whatever else changed",
},
];
pub fn registry() -> &'static [Preparation] {
REGISTRY
}
pub fn lookup(id: &str) -> Option<&'static Preparation> {
REGISTRY.iter().find(|p| p.id == id)
}
pub fn is_registered(id: &str) -> bool {
lookup(id).is_some()
}
pub fn registered_identifiers() -> Vec<&'static str> {
REGISTRY.iter().map(|p| p.id).collect()
}
pub fn delivery_preparation(declared: Option<&str>) -> Option<&'static Preparation> {
lookup(declared?).filter(|p| p.touchpoint == Touchpoint::DeliveryUnits)
}
pub fn applies_to_namespace(preparation: &Preparation, anchor_namespace: &str) -> bool {
preparation
.grains
.iter()
.any(|g| g.supported_by_namespace(anchor_namespace))
}
pub fn default_hash_stability(grain: AnchorGrain) -> AnchorHashStability {
match grain {
AnchorGrain::Url => AnchorHashStability::Unstable,
AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree | AnchorGrain::Entity => {
AnchorHashStability::Stable
}
}
}
pub fn url_prepared_hash(content: &[u8]) -> String {
prepared_content_hash(content)
}
pub fn supplied_content_hash(grain: AnchorGrain, content: &[u8]) -> Option<String> {
match grain {
AnchorGrain::Span | AnchorGrain::File => Some(prepared_content_hash(content)),
AnchorGrain::Url => Some(url_prepared_hash(content)),
AnchorGrain::Tree | AnchorGrain::Entity => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathPrepared {
Hash(String),
NoHash,
UnitAbsent,
}
pub fn path_prepared_hash(
preparation: Option<&str>,
artifact: &str,
grain: AnchorGrain,
bytes: &[u8],
) -> PathPrepared {
let (path, locator) = split_unit_id(artifact);
match (preparation, grain) {
(Some(QUOTED_PHRASE), AnchorGrain::Span | AnchorGrain::Url) if locator.is_some() => {
quoted_phrase_prepared(locator.unwrap_or_default(), &String::from_utf8_lossy(bytes))
}
(_, AnchorGrain::Url | AnchorGrain::Entity | AnchorGrain::Tree) => PathPrepared::NoHash,
(Some(DATED_ENTRIES), AnchorGrain::Span) if locator.is_some() => {
let text = String::from_utf8_lossy(bytes);
match unitize(DATED_ENTRIES, &text)
.and_then(|units| units.into_iter().find(|u| Some(u.key.as_str()) == locator))
{
Some(unit) => PathPrepared::Hash(unit.hash),
None => PathPrepared::UnitAbsent,
}
}
(Some(CODE_MAP), AnchorGrain::File | AnchorGrain::Span) => {
let text = String::from_utf8_lossy(bytes);
PathPrepared::Hash(prepared_content_hash(
code_map_digest(path, &text).as_bytes(),
))
}
(_, AnchorGrain::File | AnchorGrain::Span) => {
PathPrepared::Hash(prepared_content_hash(bytes))
}
}
}
pub fn quoted_phrase_prepared(phrase: &str, text: &str) -> PathPrepared {
let phrase = phrase.trim();
if phrase.is_empty() {
return PathPrepared::UnitAbsent;
}
let canonical_text = canonical_text(text);
let canonical_phrase = canonical_text_owned(phrase);
if canonical_text.contains(canonical_phrase.as_str()) {
PathPrepared::Hash(prepared_content_hash(canonical_phrase.as_bytes()))
} else {
PathPrepared::UnitAbsent
}
}
fn canonical_text(text: &str) -> String {
canonical_text_owned(text)
}
fn canonical_text_owned(text: &str) -> String {
text.strip_prefix('\u{feff}')
.unwrap_or(text)
.replace("\r\n", "\n")
}
pub fn canonical_span_form(text: &str) -> String {
canonical_form(text, LineEndHyphen::Join)
}
pub fn canonical_text_forms(text: &str) -> Vec<String> {
let joined = canonical_form(text, LineEndHyphen::Join);
let kept = canonical_form(text, LineEndHyphen::Keep);
if kept == joined {
vec![joined]
} else {
vec![joined, kept]
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum LineEndHyphen {
Join,
Keep,
}
fn canonical_form(text: &str, line_end_hyphen: LineEndHyphen) -> String {
use unicode_normalization::UnicodeNormalization;
let composed: String = text.nfc().collect();
let mut mapped = String::with_capacity(composed.len());
for c in composed.chars() {
match c {
'\u{00AD}' => {}
'\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}' | '\u{2039}' | '\u{203A}' => {
mapped.push('\'');
}
'\u{201C}' | '\u{201D}' | '\u{201E}' | '\u{201F}' | '\u{00AB}' | '\u{00BB}' => {
mapped.push('"');
}
'\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' | '\u{2014}' | '\u{2015}'
| '\u{2212}' => mapped.push('-'),
'\u{FB00}' => mapped.push_str("ff"),
'\u{FB01}' => mapped.push_str("fi"),
'\u{FB02}' => mapped.push_str("fl"),
'\u{FB03}' => mapped.push_str("ffi"),
'\u{FB04}' => mapped.push_str("ffl"),
'\u{FB05}' | '\u{FB06}' => mapped.push_str("st"),
other => mapped.push(other),
}
}
let mut joined = String::with_capacity(mapped.len());
let mut chars = mapped.chars().peekable();
while let Some(c) = chars.next() {
if c == '-' {
let mut ahead = chars.clone();
let mut consumed = 0usize;
if ahead.peek() == Some(&'\r') {
ahead.next();
consumed += 1;
}
if ahead.peek() == Some(&'\n') {
ahead.next();
consumed += 1;
while matches!(ahead.peek(), Some(' ') | Some('\t')) {
ahead.next();
consumed += 1;
}
for _ in 0..consumed {
chars.next();
}
if line_end_hyphen == LineEndHyphen::Keep {
joined.push('-');
}
continue;
}
}
joined.push(c);
}
let mut out = String::with_capacity(joined.len());
let mut pending_space = false;
for c in joined.chars() {
if c.is_whitespace() {
pending_space = !out.is_empty();
} else {
if pending_space {
let after_opener = out.ends_with(['(', '[', '{']);
let before_closer = matches!(c, ')' | ']' | '}');
if !after_opener && !before_closer {
out.push(' ');
}
pending_space = false;
}
out.push(c);
}
}
out
}
pub fn span_occurs(span: &str, text: &str) -> bool {
let span = canonical_span_form(span);
if span.is_empty() {
return false;
}
canonical_text_forms(text)
.iter()
.any(|form| form.contains(span.as_str()))
}
pub fn span_hash(span: &str) -> String {
prepared_content_hash(canonical_span_form(span).as_bytes())
}
pub fn code_map_tree_digest(files: &[(String, String)]) -> String {
let mut rows: Vec<(&str, &str)> = files
.iter()
.map(|(path, text)| (path.as_str(), text.as_str()))
.collect();
rows.sort();
rows.iter()
.map(|(path, text)| {
format!(
"{} {path}",
prepared_content_hash(code_map_digest(path, text).as_bytes())
)
})
.collect::<Vec<_>>()
.join("\n")
}
pub fn plain_tree_digest(files: &[(String, Vec<u8>)]) -> String {
let mut rows: Vec<(&str, &[u8])> = files
.iter()
.map(|(path, bytes)| (path.as_str(), bytes.as_slice()))
.collect();
rows.sort();
rows.iter()
.map(|(path, bytes)| format!("{} {path}", prepared_content_hash(bytes)))
.collect::<Vec<_>>()
.join("\n")
}
pub fn code_map_digest(path: &str, text: &str) -> String {
match family_of(path) {
Family::Text => text.to_string(),
Family::Json => serde_json::from_str::<serde_json::Value>(text)
.map(|v| v.to_string())
.unwrap_or_else(|_| text.to_string()),
Family::Vue => {
declaration_lines(&strip_c_comments(&vue_script_blocks(text)), Family::CLike)
}
Family::CLike => declaration_lines(&strip_c_comments(text), Family::CLike),
Family::Rust => declaration_lines(&strip_c_comments(text), Family::Rust),
Family::Python => declaration_lines(&strip_python_comments(text), Family::Python),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Family {
CLike,
Rust,
Python,
Json,
Vue,
Text,
}
fn family_of(path: &str) -> Family {
let name = path.rsplit('/').next().unwrap_or(path);
let ext = match name.rsplit_once('.') {
Some((_, ext)) => ext.to_ascii_lowercase(),
None => return Family::Text,
};
match ext.as_str() {
"rs" => Family::Rust,
"js" | "mjs" | "cjs" | "jsx" | "ts" | "tsx" | "mts" | "cts" | "go" | "java" | "kt"
| "kts" | "swift" | "cs" | "c" | "h" | "cc" | "cpp" | "hpp" | "m" | "mm" | "php"
| "dart" | "scala" => Family::CLike,
"py" | "pyi" => Family::Python,
"json" => Family::Json,
"vue" | "svelte" => Family::Vue,
_ => Family::Text,
}
}
fn vue_script_blocks(text: &str) -> String {
let lower = text.to_ascii_lowercase();
let mut out = String::new();
let mut from = 0;
while let Some(open) = lower[from..].find("<script") {
let open = from + open;
let Some(tag_end) = lower[open..].find('>') else {
break;
};
let body_start = open + tag_end + 1;
let Some(close) = lower[body_start..].find("</script") else {
out.push_str(&text[body_start..]);
break;
};
out.push_str(&text[body_start..body_start + close]);
out.push('\n');
from = body_start + close + 8;
}
out
}
fn strip_c_comments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
let mut in_str: Option<char> = None;
let mut escape = false;
while let Some(c) = chars.next() {
if let Some(q) = in_str {
out.push(c);
if escape {
escape = false;
} else if c == '\\' {
escape = true;
} else if c == q || (c == '\n' && q != '`') {
in_str = None;
}
continue;
}
match c {
'"' | '\'' | '`' => {
in_str = Some(c);
out.push(c);
}
'/' => match chars.peek() {
Some('/') => {
for n in chars.by_ref() {
if n == '\n' {
out.push('\n');
break;
}
}
}
Some('*') => {
chars.next();
let mut prev = '\0';
for n in chars.by_ref() {
if n == '\n' {
out.push('\n');
}
if prev == '*' && n == '/' {
break;
}
prev = n;
}
}
_ => out.push(c),
},
_ => out.push(c),
}
}
out
}
fn strip_python_comments(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let bytes: Vec<char> = text.chars().collect();
let mut i = 0;
let mut in_str: Option<char> = None;
let mut triple: Option<char> = None;
while i < bytes.len() {
let c = bytes[i];
if let Some(q) = triple {
if c == q && i + 2 < bytes.len() && bytes[i + 1] == q && bytes[i + 2] == q {
triple = None;
i += 3;
continue;
}
if c == '\n' {
out.push('\n');
}
i += 1;
continue;
}
if let Some(q) = in_str {
out.push(c);
if c == '\\' && i + 1 < bytes.len() {
out.push(bytes[i + 1]);
i += 2;
continue;
}
if c == q || c == '\n' {
in_str = None;
}
i += 1;
continue;
}
match c {
'"' | '\'' => {
if i + 2 < bytes.len() && bytes[i + 1] == c && bytes[i + 2] == c {
triple = Some(c);
i += 3;
continue;
}
in_str = Some(c);
out.push(c);
}
'#' => {
while i < bytes.len() && bytes[i] != '\n' {
i += 1;
}
continue;
}
_ => out.push(c),
}
i += 1;
}
out
}
const C_LIKE_TOP_LEVEL: &[&str] = &[
"import ",
"export ",
"module.exports",
"exports.",
"function ",
"async function ",
"class ",
"interface ",
"type ",
"enum ",
"declare ",
"const ",
"let ",
"var ",
"pub ",
"fn ",
"struct ",
"trait ",
"impl ",
"impl<",
"mod ",
"use ",
"static ",
"macro_rules!",
"package ",
"func ",
"namespace ",
"using ",
"#include",
"#[",
"@",
"public ",
"private ",
"protected ",
"abstract ",
"final ",
"override ",
"typedef ",
"extern ",
"template",
"def ",
];
const C_LIKE_MEMBER: &[&str] = &[
"pub ",
"fn ",
"public ",
"private ",
"protected ",
"static ",
"abstract ",
"override ",
"readonly ",
"async ",
"get ",
"set ",
"constructor",
"#[",
"@",
];
fn method_re() -> &'static regex::Regex {
static METHOD: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
METHOD.get_or_init(|| {
regex::Regex::new(r"^(?:(?:async|static|get|set|public|private|protected|override)\s+)*[A-Za-z_$][\w$]*\s*(?:<[^>]*>)?\s*\(").unwrap()
})
}
fn property_re() -> &'static regex::Regex {
static PROPERTY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
PROPERTY.get_or_init(|| {
regex::Regex::new(r#"^(?:readonly\s+)?(?:['"]?)[A-Za-z_$][\w$]*(?:['"]?)\??\s*:"#).unwrap()
})
}
fn typed_member_re() -> &'static regex::Regex {
static TYPED_MEMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
TYPED_MEMBER.get_or_init(|| {
regex::Regex::new(
r"^(?:readonly\s+)?[A-Za-z_$][\w$]*\??\s*(?:<[^>]*>)?\s*\(.*\)\s*:\s*[^{;]+[;,]?$",
)
.unwrap()
})
}
fn typed_member(line: &str) -> bool {
typed_member_re().is_match(line) && !line.contains("? ")
}
fn enum_member_re() -> &'static regex::Regex {
static ENUM_MEMBER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
ENUM_MEMBER
.get_or_init(|| regex::Regex::new(r"^[A-Z][A-Za-z0-9_]*(?:\s*=\s*[^,]+)?,?$").unwrap())
}
fn member_signature_only(line: &str, depth: i32) -> bool {
depth >= 1
&& !C_LIKE_MEMBER.iter().any(|p| line.starts_with(p))
&& !property_re().is_match(line)
&& !typed_member(line)
&& method_re().is_match(line)
}
fn c_like_keeps(line: &str, depth: i32, next_opens_body: bool, properties: bool) -> bool {
let method = method_re();
let property = property_re();
let signature_shaped = |line: &str| {
method.is_match(line)
&& !line.starts_with("if ")
&& !line.starts_with("for ")
&& !line.starts_with("while ")
&& !line.starts_with("switch ")
&& !line.starts_with("return ")
&& !line.starts_with("catch ")
&& (line.ends_with('{')
|| line.ends_with('(')
|| line.ends_with(',')
|| (line.ends_with(')') && next_opens_body))
};
match depth {
0 => C_LIKE_TOP_LEVEL.iter().any(|p| line.starts_with(p)),
1 => {
C_LIKE_MEMBER.iter().any(|p| line.starts_with(p))
|| signature_shaped(line)
|| (properties && (property.is_match(line) || typed_member(line)))
|| enum_member_re().is_match(line)
}
2 => signature_shaped(line),
_ => false,
}
}
fn python_keeps(line: &str, indent: usize) -> bool {
static CONSTANT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let constant = CONSTANT
.get_or_init(|| regex::Regex::new(r"^(?:[A-Z_][A-Z0-9_]*|__all__)\s*[:=]").unwrap());
let decl = line.starts_with("def ")
|| line.starts_with("async def ")
|| line.starts_with("class ")
|| line.starts_with('@');
if indent == 0 {
decl || line.starts_with("import ") || line.starts_with("from ") || constant.is_match(line)
} else {
indent <= 4 && decl
}
}
fn python_constant_cut(line: &str) -> Option<usize> {
static CONSTANT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let constant = CONSTANT.get_or_init(|| {
regex::Regex::new(r"^(?:[A-Z_][A-Z0-9_]*|__all__)(?:\s*:\s*[^=]+?)?\s*=").unwrap()
});
constant.find(line).map(|m| m.end())
}
fn paren_balance(s: &str) -> i32 {
s.chars()
.map(|c| match c {
'(' => 1,
')' => -1,
_ => 0,
})
.sum()
}
fn brace_delta(s: &str) -> i32 {
s.chars()
.map(|c| match c {
'{' => 1,
'}' => -1,
_ => 0,
})
.sum()
}
fn cut_at_body(sig: &str, family: Family) -> String {
match family {
Family::Python => sig.trim_end_matches(':').trim_end().to_string(),
_ if sig.starts_with("import ")
|| sig.starts_with("use ")
|| sig.starts_with("export {")
|| sig.starts_with("export type {")
|| sig.starts_with("export * ") =>
{
sig.trim_end().to_string()
}
_ => {
let mut depth = 0i32;
let mut cut = sig.len();
let bytes = sig.as_bytes();
for (i, c) in sig.char_indices() {
match c {
'(' | '[' => depth += 1,
')' | ']' => depth -= 1,
'{' if depth <= 0 => {
cut = i;
break;
}
'=' if depth <= 0 && bytes.get(i + 1) == Some(&b'>') => {
let rest = sig[i + 2..].trim_start();
if !rest.starts_with('{') {
cut = i + 2;
break;
}
}
_ => {}
}
}
sig[..cut].trim_end().to_string()
}
}
}
fn normalize_signature(sig: &str) -> String {
let collapsed: Vec<&str> = sig
.trim()
.trim_end_matches(';')
.split_whitespace()
.collect();
let joined = collapsed.join(" ").replace('"', "'");
let is_punct = |c: char| "()[]{},;:=<>|&?!-+*/.".contains(c);
let mut out = String::with_capacity(joined.len());
let chars: Vec<char> = joined.chars().collect();
for (i, &c) in chars.iter().enumerate() {
if c == ' ' {
let before = chars[..i].iter().rev().find(|x| **x != ' ').copied();
let after = chars[i + 1..].iter().find(|x| **x != ' ').copied();
if before.is_some_and(is_punct) || after.is_some_and(is_punct) {
continue;
}
}
out.push(c);
}
let out = out
.replace(",)", ")")
.replace(",]", "]")
.replace(",}", "}")
.replace(",>", ">");
let out = out.trim_end_matches(',').to_string();
let out = out.replace("=|", "=");
let out = out.trim_end_matches('{').trim_end().to_string();
static QUOTED_KEY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
static ARROW_PARENS: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let quoted_key =
QUOTED_KEY.get_or_init(|| regex::Regex::new(r"^'([A-Za-z_$][\w$]*)':").unwrap());
let arrow_parens =
ARROW_PARENS.get_or_init(|| regex::Regex::new(r"\(([A-Za-z_$][\w$]*)\)=>").unwrap());
let out = quoted_key.replace(&out, "$1:").into_owned();
let out = arrow_parens.replace_all(&out, "$1=>").into_owned();
static SCALAR_PROPERTY: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let scalar = SCALAR_PROPERTY
.get_or_init(|| regex::Regex::new(r#"^([A-Za-z_$][\w$]*:)(?:'|`|-?\d)"#).unwrap());
let out = match scalar.captures(&out) {
Some(caps) => caps[1].to_string(),
None => out,
};
if out.starts_with("from ") || out.starts_with("import ") {
return out
.replace('(', " ")
.replace(')', "")
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
}
out
}
fn cut_value_binding(line: &str) -> Option<String> {
static BINDING: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
static DEFAULT: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let binding = BINDING.get_or_init(|| {
regex::Regex::new(
r"^((?:(?:export\s+)?(?:pub(?:\([^)]*\))?\s+)?(?:(?:static|readonly|private|public|protected|declare|override|const|let|var)\s+)*(?:[A-Za-z_$][\w$]*|\{[^}]*\}|\[[^\]]*\])(?:\s*:\s*[^=]+?)?|(?:module\.)?exports(?:\.[A-Za-z_$][\w$]*)?)\s*=)\s*(.*)$",
)
.unwrap()
});
let default =
DEFAULT.get_or_init(|| regex::Regex::new(r"^(export\s+default)\s+(.*)$").unwrap());
let function_like = |value: &str| {
static ARROW: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let arrow = ARROW
.get_or_init(|| regex::Regex::new(r"^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>").unwrap());
value.starts_with('(')
|| value.starts_with("async ")
|| value.starts_with("async(")
|| value.starts_with("function")
|| value.starts_with("class")
|| arrow.is_match(value)
};
if let Some(caps) = binding.captures(line) {
let value = caps[2].trim();
if value.starts_with('>') {
return None;
}
let module_export = caps[1].starts_with("exports") || caps[1].starts_with("module.exports");
if function_like(value) || (module_export && value.starts_with('{')) {
return None;
}
return Some(caps[1].to_string());
}
if let Some(caps) = default.captures(line) {
let value = caps[2].trim();
if value.is_empty() || value.starts_with('{') || function_like(value) {
return None;
}
return Some(caps[1].to_string());
}
None
}
fn angle_balance(s: &str) -> i32 {
let s = s.replace("->", " ").replace("=>", " ");
s.chars()
.map(|c| match c {
'<' => 1,
'>' => -1,
_ => 0,
})
.sum::<i32>()
.max(0)
}
fn bracket_balance(s: &str) -> i32 {
s.chars()
.map(|c| match c {
'[' => 1,
']' => -1,
_ => 0,
})
.sum()
}
fn opens_destructure(line: &str) -> bool {
static DESTRUCTURE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let re = DESTRUCTURE
.get_or_init(|| regex::Regex::new(r"^(?:export\s+)?(?:const|let|var)\s+[\{\[]").unwrap());
re.is_match(line) && brace_delta(line) + bracket_balance(line) > 0
}
fn is_list_declaration(sig: &str) -> bool {
sig.starts_with("import ")
|| sig.starts_with("use ")
|| sig.starts_with("export {")
|| sig.starts_with("export type {")
}
fn declaration_lines(stripped: &str, family: Family) -> String {
let lines: Vec<&str> = stripped.lines().collect();
let mut out: Vec<String> = Vec::new();
let mut depth: i32 = 0;
let mut body_skip: Option<(i32, i32, i32)> = None;
let mut i = 0;
while i < lines.len() {
let raw = lines[i];
let line = raw.trim();
if line.is_empty() {
i += 1;
continue;
}
if let Some((braces, brackets, parens)) = body_skip {
let braces = braces + brace_delta(raw);
let brackets = brackets + bracket_balance(raw);
let parens = parens + paren_balance(raw);
depth += brace_delta(raw);
body_skip = if braces <= 0 && brackets <= 0 && parens <= 0 {
None
} else {
Some((braces, brackets, parens))
};
i += 1;
continue;
}
let indent = raw.len() - raw.trim_start().len();
let next_opens_body = lines[i + 1..]
.iter()
.map(|l| l.trim())
.find(|l| !l.is_empty())
.is_some_and(|l| l.starts_with('{'));
let keep = match family {
Family::Python => python_keeps(line, indent),
_ => c_like_keeps(line, depth, next_opens_body, family != Family::Rust),
};
if keep
&& family == Family::Python
&& indent == 0
&& let Some(eq) = python_constant_cut(line)
{
out.push(normalize_signature(&line[..eq]));
i += 1;
continue;
}
let mut binding_end = i;
let destructured = if keep && family != Family::Python && opens_destructure(line) {
let mut joined = line.to_string();
while brace_delta(&joined) + bracket_balance(&joined) > 0
&& binding_end + 1 < lines.len()
&& binding_end - i < 60
{
binding_end += 1;
if lines[binding_end].trim().is_empty() {
continue;
}
joined.push(' ');
joined.push_str(lines[binding_end].trim());
}
Some(joined)
} else {
None
};
let binding_line = destructured.as_deref().unwrap_or(line);
if keep
&& family != Family::Python
&& !(depth >= 1 && enum_member_re().is_match(line))
&& let Some(cut) = cut_value_binding(binding_line)
{
out.push(normalize_signature(&cut));
let span = &lines[i..=binding_end];
let mut opened = (
span.iter().map(|l| brace_delta(l)).sum::<i32>(),
span.iter().map(|l| bracket_balance(l)).sum::<i32>(),
span.iter().map(|l| paren_balance(l)).sum::<i32>(),
);
depth += opened.0;
i = binding_end + 1;
if binding_line.trim_end().ends_with('=') {
while i < lines.len() && lines[i].trim().is_empty() {
i += 1;
}
if i < lines.len() {
let v = lines[i];
opened = (
opened.0 + brace_delta(v),
opened.1 + bracket_balance(v),
opened.2 + paren_balance(v),
);
depth += brace_delta(v);
i += 1;
}
}
if opened.0 > 0 || opened.1 > 0 || opened.2 > 0 {
body_skip = Some(opened);
}
continue;
}
if keep {
let mut sig = line.to_string();
let mut j = i;
let c_like = family != Family::Python;
let next_is_operator_led = |k: usize| {
c_like
&& lines[k + 1..]
.iter()
.map(|l| l.trim())
.find(|l| !l.is_empty())
.is_some_and(|l| {
l.starts_with('|')
|| l.starts_with('&')
|| l.starts_with('?')
|| l.starts_with(':')
|| l.starts_with('.')
|| l.starts_with('+')
})
};
let ends_open = |s: &str| {
let t = s.trim_end();
c_like && (t.ends_with('=') || t.ends_with(':'))
};
while (!sig.trim_end().ends_with('{') || is_list_declaration(&sig))
&& (paren_balance(&sig) > 0
|| bracket_balance(&sig) > 0
|| (c_like && angle_balance(&sig) > 0)
|| (is_list_declaration(&sig) && brace_delta(&sig) > 0)
|| ends_open(&sig)
|| next_is_operator_led(j))
&& j + 1 < lines.len()
&& j - i < 60
{
j += 1;
if lines[j].trim().is_empty() {
continue;
}
sig.push(' ');
sig.push_str(lines[j].trim());
}
let opens_body = sig.trim_end().ends_with('{')
|| sig.contains("=>")
|| lines[j + 1..]
.iter()
.map(|l| l.trim())
.find(|l| !l.is_empty())
.is_some_and(|l| l.starts_with('{'));
if c_like && member_signature_only(&sig, depth) && !opens_body {
for l in &lines[i..=j] {
depth += brace_delta(l);
}
i = j + 1;
continue;
}
out.push(normalize_signature(&cut_at_body(&sig, family)));
if c_like {
for l in &lines[i..=j] {
depth += brace_delta(l);
}
}
i = j + 1;
} else {
if family != Family::Python {
depth += brace_delta(raw);
}
i += 1;
}
}
out.join("\n")
}
pub fn load_bearing_sections(
type_def: &memstead_schema::types::TypeDefinition,
) -> Vec<&memstead_schema::types::SectionDef> {
let explicit: Vec<_> = type_def
.sections
.iter()
.filter(|s| s.load_bearing == Some(true))
.collect();
if !explicit.is_empty() {
return explicit;
}
let required: Vec<_> = type_def
.sections
.iter()
.filter(|s| s.required && s.load_bearing != Some(false))
.collect();
if !required.is_empty() {
return required;
}
type_def.sections.iter().collect()
}
pub fn entity_load_bearing_form(
entity: &Entity,
type_def: Option<&memstead_schema::types::TypeDefinition>,
) -> String {
fn push(out: &mut String, key: &str, content: &str) {
out.push_str("## ");
out.push_str(key);
out.push_str("\n\n");
out.push_str(content.trim());
out.push_str("\n\n");
}
let mut out = String::new();
match type_def {
Some(td) => {
for section in load_bearing_sections(td) {
if let Some(content) = entity.sections.get(§ion.key) {
push(&mut out, §ion.key, content);
}
}
}
None => {
for (key, content) in &entity.sections {
push(&mut out, key, content);
}
}
}
out
}
pub fn entity_section_prepared_hash(key: &str, content: &str) -> String {
prepared_content_hash(format!("## {key}\n\n{}\n\n", content.trim()).as_bytes())
}
pub fn entity_load_bearing_section_marks(
entity: &Entity,
type_def: Option<&memstead_schema::types::TypeDefinition>,
) -> std::collections::BTreeMap<String, String> {
let mut out = std::collections::BTreeMap::new();
let mut add = |key: &String, content: &String| {
if !content.trim().is_empty() {
out.insert(key.clone(), entity_section_prepared_hash(key, content));
}
};
match type_def {
Some(td) => {
for section in load_bearing_sections(td) {
if let Some(content) = entity.sections.get(§ion.key) {
add(§ion.key, content);
}
}
}
None => {
for (key, content) in &entity.sections {
add(key, content);
}
}
}
out
}
pub fn entity_prepared_hash(
entity: &Entity,
type_def: Option<&memstead_schema::types::TypeDefinition>,
preparation: Option<&str>,
) -> Option<String> {
match entity_prepared(entity, type_def, preparation, None) {
PathPrepared::Hash(h) => Some(h),
PathPrepared::NoHash | PathPrepared::UnitAbsent => None,
}
}
pub fn entity_prepared(
entity: &Entity,
type_def: Option<&memstead_schema::types::TypeDefinition>,
preparation: Option<&str>,
locator: Option<&str>,
) -> PathPrepared {
let form = match preparation {
None => crate::render::render_entity_markdown(entity, None),
Some(ENTITY_LOAD_BEARING) => entity_load_bearing_form(entity, type_def),
Some(QUOTED_PHRASE) => {
let rendered = crate::render::render_entity_markdown(entity, None);
return match locator {
Some(phrase) => quoted_phrase_prepared(phrase, &rendered),
None => PathPrepared::Hash(prepared_content_hash(rendered.as_bytes())),
};
}
Some(_) => return PathPrepared::NoHash,
};
PathPrepared::Hash(prepared_content_hash(form.as_bytes()))
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeliveryUnit {
pub key: String,
pub order_key: String,
pub start_line: usize,
pub end_line: usize,
pub hash: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum UnitChange {
Added,
Modified,
Deleted,
}
pub fn unit_id(path: &str, key: &str) -> String {
format!("{path}#{key}")
}
pub fn split_unit_id(id: &str) -> (&str, Option<&str>) {
match id.find('#') {
Some(cut) => (&id[..cut], Some(&id[cut + 1..])),
None => (id, None),
}
}
pub fn unitize(preparation: &str, content: &str) -> Option<Vec<DeliveryUnit>> {
match preparation {
DATED_ENTRIES => Some(dated_entries(content)),
_ => None,
}
}
pub fn unit_text(content: &str, unit: &DeliveryUnit) -> String {
content
.lines()
.skip(unit.start_line.saturating_sub(1))
.take(unit.end_line + 1 - unit.start_line.max(1))
.collect::<Vec<_>>()
.join("\n")
}
pub fn diff_units(
before: &[DeliveryUnit],
after: &[DeliveryUnit],
) -> Vec<(DeliveryUnit, UnitChange)> {
let old: std::collections::BTreeMap<&str, &DeliveryUnit> =
before.iter().map(|u| (u.key.as_str(), u)).collect();
let new: std::collections::BTreeMap<&str, &DeliveryUnit> =
after.iter().map(|u| (u.key.as_str(), u)).collect();
let mut out = Vec::new();
for u in after {
match old.get(u.key.as_str()) {
None => out.push((u.clone(), UnitChange::Added)),
Some(prev) if prev.hash != u.hash => out.push((u.clone(), UnitChange::Modified)),
Some(_) => {}
}
}
for u in before {
if !new.contains_key(u.key.as_str()) {
out.push((u.clone(), UnitChange::Deleted));
}
}
out
}
fn dated_entries(content: &str) -> Vec<DeliveryUnit> {
let lines: Vec<&str> = content.lines().collect();
let starts: Vec<(usize, String)> = lines
.iter()
.enumerate()
.filter_map(|(i, line)| leading_stamp(line).map(|stamp| (i, stamp)))
.collect();
if starts.is_empty() {
return vec![DeliveryUnit {
key: WHOLE_FILE_UNIT.to_string(),
order_key: String::new(),
start_line: 1,
end_line: lines.len().max(1),
hash: prepared_content_hash(content.as_bytes()),
}];
}
let mut seen: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
let mut units = Vec::with_capacity(starts.len());
for (n, (start, stamp)) in starts.iter().enumerate() {
let from = if n == 0 { 0 } else { *start };
let to = starts.get(n + 1).map_or(lines.len(), |(next, _)| *next);
let text = lines[from..to].join("\n");
let count = seen
.entry(stamp.clone())
.and_modify(|c| *c += 1)
.or_insert(1);
let key = if *count == 1 {
stamp.clone()
} else {
format!("{stamp}.{count}")
};
units.push(DeliveryUnit {
key,
order_key: stamp.clone(),
start_line: from + 1,
end_line: to,
hash: prepared_content_hash(text.as_bytes()),
});
}
units
}
fn leading_stamp(line: &str) -> Option<String> {
static STAMP: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let re = STAMP.get_or_init(|| {
regex::Regex::new(
r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?\b",
)
.expect("the stamp regex compiles")
});
let s = line.trim_start_matches(|c: char| {
c.is_whitespace() || matches!(c, '#' | '-' | '*' | '>' | '[' | '(' | '|' | '`' | '+')
});
let caps = re.captures(s)?;
let num = |i: usize| -> u32 {
caps.get(i)
.map(|m| m.as_str().parse().unwrap_or(0))
.unwrap_or(0)
};
let (y, mo, d, h, mi, sec) = (num(1), num(2), num(3), num(4), num(5), num(6));
let days_in_month = match mo {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => 29,
_ => return None,
};
if !(1..=days_in_month).contains(&d) || h > 23 || mi > 59 || sec > 59 {
return None;
}
Some(format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{sec:02}"))
}
#[cfg(test)]
mod tests;