use blake3::Hasher;
use regex::Regex;
use std::sync::LazyLock;
use unicode_normalization::char::is_combining_mark;
use unicode_normalization::UnicodeNormalization;
use crate::marker::ID;
static SIGN_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(
r#"(?i)\(\s*§\s*<a\s+id="({ID})">{ID}</a>\s*\)|§\s*<a\s+id="({ID})">{ID}</a>|\(\s*§\s*({ID})\s*\)|§\s+({ID})\b"#
))
.expect("marker regex")
});
static ALIAS_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(&format!(r#"<a\s+id="({ID})"\s*></a>"#)).expect("alias regex"));
pub fn aliases_in(line: &str) -> Vec<String> {
ALIAS_RE
.captures_iter(line)
.map(|c| c[1].to_string())
.collect()
}
pub fn strip_aliases(line: &str) -> String {
ALIAS_RE.replace_all(line, "").into_owned()
}
const ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz";
const LETTERS: &[u8; 22] = b"abcdefghjkmnpqrstvwxyz";
pub fn canonicalise(carrying: &str) -> String {
let unaliased = strip_aliases(carrying);
let stripped = SIGN_RE.replace_all(&unaliased, "");
let composed: String = stripped.nfc().collect();
let mut out = String::with_capacity(composed.len());
for (code, part) in code_spans(&composed) {
if code {
out.push_str(part);
} else {
out.extend(fold_prose(part));
}
}
out.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn fold_prose(prose: &str) -> impl Iterator<Item = char> + '_ {
prose
.chars()
.flat_map(char::to_lowercase)
.nfkd()
.filter(|c| !is_combining_mark(*c))
.filter(|c| c.is_alphanumeric() || *c == ' ')
}
pub(crate) fn code_spans(text: &str) -> Vec<(bool, &str)> {
let bytes = text.as_bytes();
let run = |at: usize| bytes[at..].iter().take_while(|&&b| b == b'`').count();
let mut out = Vec::new();
let (mut prose, mut i) = (0, 0);
while i < bytes.len() {
if bytes[i] != b'`' {
i += 1;
continue;
}
let open = run(i);
let content = i + open;
let mut j = content;
let mut close = None;
while j < bytes.len() {
if bytes[j] != b'`' {
j += 1;
continue;
}
let n = run(j);
if n == open {
close = Some(j);
break;
}
j += n;
}
match close {
Some(j) => {
out.push((false, &text[prose..i]));
out.push((true, &text[content..j]));
i = j + open;
prose = i;
}
None => i = content,
}
}
out.push((false, &text[prose..]));
out
}
pub fn pin_canon(body: &str) -> String {
let lines: Vec<&str> = body.lines().collect();
let fence = crate::parse::fence_mask(&lines);
let mut out = Vec::new();
let mut prose = String::new();
let flush = |prose: &mut String, out: &mut Vec<String>| {
let composed: String = prose.nfc().collect();
let c = composed.split_whitespace().collect::<Vec<_>>().join(" ");
if !c.is_empty() {
out.push(c);
}
prose.clear();
};
for (line, fenced) in lines.iter().zip(fence) {
if fenced {
flush(&mut prose, &mut out);
out.push(line.to_string());
continue;
}
let unaliased = strip_aliases(line);
let signed = SIGN_RE.replace_all(&unaliased, "");
prose.push_str(&signed);
prose.push('\n');
}
flush(&mut prose, &mut out);
out.join("\n")
}
pub fn mint_id(carrying: &str) -> String {
encode_hash(canonicalise(carrying).as_bytes())
}
fn encode_hash(bytes: &[u8]) -> String {
let mut hasher = Hasher::new();
hasher.update(bytes);
let mut xof = hasher.finalize_xof();
let mut bits = [0u8; 6];
xof.fill(&mut bits);
encode_bits(&bits)
}
pub fn verify_id(carrying: &str, id: &str) -> bool {
if id.len() != 9 {
return false;
}
mint_id(carrying) == normalise_id(id)
}
pub fn normalise_id(id: &str) -> String {
id.chars().map(normalise_symbol).collect()
}
pub fn is_crockford_id(id: &str) -> bool {
if id.len() != 9 {
return false;
}
let mut chars = id.chars();
let Some(first) = chars.next() else {
return false;
};
if !first.is_ascii_alphabetic() || matches!(first, 'i' | 'l' | 'o' | 'u') {
return false;
}
for c in chars {
if !c.is_ascii_alphanumeric() {
return false;
}
if matches!(c, 'i' | 'l' | 'o' | 'u') {
return false;
}
}
true
}
pub fn is_provisional_id(id: &str) -> bool {
id.starts_with('+')
&& id.len() > 1
&& id[1..]
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
fn normalise_symbol(c: char) -> char {
let lower = c.to_ascii_lowercase();
match lower {
'i' | 'l' => '1',
'o' => '0',
_ => lower,
}
}
fn encode_bits(bytes: &[u8; 6]) -> String {
let mut value: u64 = 0;
for &b in bytes {
value = (value << 8) | u64::from(b);
}
value >>= 3;
let mut out = String::with_capacity(9);
let first = ((value >> 40) & 0x1f) as usize % LETTERS.len();
out.push(LETTERS[first] as char);
let mut rest = value & ((1u64 << 40) - 1);
for _ in 0..8 {
let idx = (rest & 0x1f) as usize;
out.push(ALPHABET[idx] as char);
rest >>= 5;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wrapping_bold_does_not_remint() {
let plain = "Four verbs: declare, cite, retire, implements. There is no verb apply.";
let bold =
"**§ abcdefgh1 Four verbs: declare, cite, retire, implements. There is no verb apply.**";
assert_eq!(mint_id(plain), mint_id(bold));
}
#[test]
fn canonicalise_strips_markers_and_emphasis() {
let raw = "The `check` verb **must** resolve (§ abcdefgh1).";
assert_eq!(canonicalise(raw), "the check verb must resolve");
}
#[test]
fn canonicalise_strips_anchor_wrap() {
let raw = r#"Binding sentence § <a id="abcdefgh1">abcdefgh1</a>."#;
assert_eq!(canonicalise(raw), "binding sentence");
}
#[test]
fn uppercase_marker_does_not_reach_the_hash() {
assert_eq!(
canonicalise("The graph fails (§ ABCDEFGH1) open, § ABCDEFGH1."),
"the graph fails open"
);
}
#[test]
fn backticks_keep_case_and_punctuation() {
let below = "Refuse a transfer when `amount < 1000`.";
let above = "Refuse a transfer when `amount > 1000`.";
assert_eq!(canonicalise(below), "refuse a transfer when amount < 1000");
assert_ne!(mint_id(below), mint_id(above));
assert_ne!(mint_id("Run `Check`."), mint_id("Run `check`."));
assert_eq!(mint_id("Run `check`."), mint_id("Run *check*."));
}
#[test]
fn double_backticks_hold_a_backtick() {
assert_eq!(canonicalise("Strip `` ` `` and `*`."), "strip ` and *");
assert_eq!(canonicalise("An `unclosed tick."), "an unclosed tick");
}
#[test]
fn composed_and_decomposed_mint_one_id() {
let nfc = "Un \u{e9}nonc\u{e9} porte une lettre.";
let nfd = "Un e\u{301}nonce\u{301} porte une lettre.";
assert_eq!(canonicalise(nfc), "un enonce porte une lettre");
assert_eq!(mint_id(nfc), mint_id(nfd));
assert_eq!(canonicalise("\u{c9}T\u{c9} \u{3a9}"), "ete \u{3c9}");
}
#[test]
fn mint_is_deterministic() {
let a = mint_id("Every verb the CLI names is either shipped or a stub.");
let b = mint_id("Every verb the CLI names is either shipped or a stub.");
assert_eq!(a, b);
assert_eq!(a.len(), 9);
assert!(a.chars().next().unwrap().is_ascii_alphabetic());
}
#[test]
fn mint_differs_for_different_sentences() {
assert_ne!(
mint_id("First carrying sentence."),
mint_id("Second carrying sentence.")
);
}
#[test]
fn normalise_maps_crockford_homoglyphs() {
assert_eq!(normalise_id("abc1efgh1"), "abc1efgh1");
assert_eq!(normalise_id("abciefgh1"), "abc1efgh1");
assert_eq!(normalise_id("abc0efgh1"), "abc0efgh1");
}
#[test]
fn verify_accepts_minted_id() {
let sentence = "The graph path must not call a network, embeddings, or a model.";
let id = mint_id(sentence);
assert!(verify_id(sentence, &id));
}
#[test]
fn alias_anchor_does_not_remint() {
let plain = r#"**§ <a id="abcdefgh1">abcdefgh1</a> Every write goes through the writer.**"#;
let aliased = r#"**§ <a id="abcdefgh1">abcdefgh1</a><a id="abcdefgh2"></a> Every write goes through the writer.**"#;
assert_eq!(mint_id(plain), mint_id(aliased));
assert_eq!(aliases_in(aliased), vec!["abcdefgh2".to_string()]);
}
#[test]
fn mint_id_equals_ids_encoded_by_hand_from_blake3_reference_vectors() {
assert_eq!(mint_id(""), "zznfekm9w");
assert_eq!(mint_id("**§ abcdefgh1 Abc.**"), "p8r1b7vvg");
}
#[test]
fn fence_lines_keep_their_bytes() {
let a = "Run:\n```yaml\nkey: 1\n```";
for b in [
"Run:\n```yaml\nkey: 1 \n```",
"Run:\n```yaml \nkey: 1\n```",
"Run:\n```yaml\n key: 1\n```",
] {
assert_ne!(pin_canon(a), pin_canon(b), "{b:?}");
}
assert_eq!(
pin_canon("Run: now.\n```yaml\nkey: 1\n```"),
pin_canon(a).replace("Run:", "Run: now.")
);
}
#[test]
fn a_tilde_fence_keeps_its_bytes() {
let a = "Run:\n~~~yaml\nkey:\n value: 1\n~~~";
let b = "Run:\n~~~yaml\nkey:\n value: 1\n~~~";
assert_ne!(pin_canon(a), pin_canon(b));
let long = "Run:\n````\n```\n inner\n````\nAfter it.";
assert!(
pin_canon(long).contains("```\n inner"),
"{}",
pin_canon(long)
);
assert!(pin_canon(long).ends_with("After it."));
}
#[test]
fn a_clause_wrapped_onto_two_lines_keeps_its_text() {
assert_eq!(
pin_canon("Retry within 1.5 days,\n then stop."),
pin_canon("Retry within 1.5 days, then stop.")
);
assert_ne!(
pin_canon("Retry within 1.5 days,\nthen stop."),
pin_canon("Retry within 1.5 days.\nthen stop.")
);
}
#[test]
fn fence_lines_keep_punctuation() {
let a = "Flow:\n```mermaid\nA --> B\n```";
let b = "Flow:\n```mermaid\nA -.-> B\n```";
assert_ne!(pin_canon(a), pin_canon(b));
}
#[test]
fn pin_text_keeps_digits_signs_and_punctuation() {
for (a, b) in [
("Retry within 1.5 days.", "Retry within 15 days."),
("Refuse when amount < 10.", "Refuse when amount > 10."),
("Offset by -5.", "Offset by 5."),
("Charge 5% more.", "Charge 5 more."),
] {
assert_ne!(pin_canon(a), pin_canon(b), "{a}");
}
assert_eq!(pin_canon(" One line.\t"), "One line.");
assert_eq!(
pin_canon("Un e\u{301}tat § abcdefgh1 fixe."),
pin_canon("Un \u{e9}tat fixe.")
);
}
#[test]
fn the_pin_text_and_the_id_strip_the_head_and_its_id() {
assert_eq!(
pin_canon("**§ <a id=\"abcdefgh1\">abcdefgh1</a> Rule.**"),
pin_canon("**§ <a id=\"abcdefgh2\">abcdefgh2</a> Rule.**")
);
assert_eq!(
mint_id("Rule holds (§ abcdefgh1)."),
mint_id("Rule holds (§ abcdefgh2).")
);
}
mod props {
use super::super::*;
use proptest::prelude::*;
fn prop_hash_config() -> ProptestConfig {
ProptestConfig {
cases: 512,
failure_persistence: None,
..ProptestConfig::default()
}
}
fn prop_words() -> impl Strategy<Value = Vec<String>> {
prop::collection::vec("[A-Za-z0-9]{1,8}[.,;:]?", 1..8)
}
fn prop_marker() -> impl Strategy<Value = String> {
(crate::marker::ID, 0..6usize).prop_map(|(id, form)| match form {
0 => format!("§ {id}"),
5 => format!("§ {}", id.to_ascii_uppercase()),
1 => format!("(§ {id})"),
2 => format!("§ <a id=\"{id}\">{id}</a>"),
3 => format!("(§ <a id=\"{id}\">{id}</a>)"),
_ => format!("<a id=\"{id}\"></a>"),
})
}
fn prop_with_marker(words: &[String], at: usize, marker: &str) -> String {
let mut out: Vec<&str> = words.iter().map(String::as_str).collect();
out.insert(at % (words.len() + 1), marker);
out.join(" ")
}
proptest! {
#![proptest_config(prop_hash_config())]
#[test]
fn canonicalise_is_idempotent(s in "[ -_a-~]{0,120}") {
let once = canonicalise(&s);
prop_assert_eq!(canonicalise(&once), once);
}
#[test]
fn a_marker_does_not_remint(
words in prop_words(),
marker in prop_marker(),
at in any::<usize>(),
to in any::<usize>(),
) {
let plain = words.join(" ");
let placed = prop_with_marker(&words, at, &marker);
let moved = prop_with_marker(&words, to, &marker);
let bold = format!("**{placed}**");
prop_assert_eq!(mint_id(&placed), mint_id(&plain));
prop_assert_eq!(mint_id(&moved), mint_id(&plain));
prop_assert_eq!(mint_id(&bold), mint_id(&plain));
}
#[test]
fn a_minted_id_is_crockford(s in "[ -~]{0,120}") {
prop_assert!(is_crockford_id(&mint_id(&s)));
}
}
}
}