diff --git a/crates/scaena-core/src/canon.rs b/crates/scaena-core/src/canon.rs index b18eae5..5050d18 100644 --- a/crates/scaena-core/src/canon.rs +++ b/crates/scaena-core/src/canon.rs @@ -26,6 +26,8 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; +use crate::text::{self, ItemLine, LineError, UrlKind}; + /// Largest canon file accepted, in bytes. pub const MAX_FILE_BYTES: usize = 64 * 1024; @@ -124,40 +126,250 @@ pub enum CanonCode { DuplicateApp(String), } +const REQUIRED: [&str; 7] = [ + "id", + "name", + "one_liner", + "audience", + "price", + "clicks", + "status", +]; +const OPTIONAL: [&str; 2] = ["aula", "site"]; +const MARKER: &str = "(assumption)"; + +fn err(line: usize, code: CanonCode) -> CanonError { + CanonError { line, code } +} + /// Parse `apps/.md`. Strict: any deviation from the format is an error. +/// +/// Tolerated: a leading byte order mark and CRLF line endings. Rejected anywhere: a lone CR, control characters +/// other than tab, and hidden or direction-changing characters (bidi controls, zero-width space, tag characters). pub fn parse(file_stem: &str, text: &str) -> Result { - let _ = (file_stem, text); - todo!() + if text.len() > MAX_FILE_BYTES { + return Err(err(0, CanonCode::TooLarge { bytes: text.len() })); + } + let lines = text::clean_lines(text).map_err(|(line, e)| match e { + LineError::LoneCr => err(line, CanonCode::LoneCarriageReturn), + LineError::Forbidden(codepoint) => err(line, CanonCode::ForbiddenCharacter { codepoint }), + })?; + if lines.first() != Some(&"---") { + return Err(err(1, CanonCode::NoFrontMatter)); + } + + // Front matter. + let mut fields: BTreeMap<&str, (String, usize)> = BTreeMap::new(); + let mut i = 1; + loop { + let line = match lines.get(i) { + // The empty piece after the final newline is the end of the file. + Some(&"") if i + 1 == lines.len() => None, + other => other.copied(), + }; + let Some(line) = line else { + return Err(err(i, CanonCode::UnclosedFrontMatter)); + }; + let n = i + 1; + if line == "---" { + break; + } + let Some((key, rest)) = line.split_once(':') else { + return Err(err(n, CanonCode::FrontMatterLine)); + }; + if key.is_empty() || !key.bytes().all(|b| b.is_ascii_lowercase() || b == b'_') { + return Err(err(n, CanonCode::FrontMatterLine)); + } + if !rest.is_empty() && !rest.starts_with(' ') { + return Err(err(n, CanonCode::FrontMatterLine)); + } + if !REQUIRED.contains(&key) && !OPTIONAL.contains(&key) { + return Err(err(n, CanonCode::UnknownKey(key.to_string()))); + } + if fields.contains_key(key) { + return Err(err(n, CanonCode::DuplicateKey(key.to_string()))); + } + let value = rest.trim(); + if value.is_empty() { + return Err(err(n, CanonCode::EmptyValue(key.to_string()))); + } + fields.insert(key, (value.to_string(), n)); + i += 1; + } + let close_line = i + 1; + for key in REQUIRED { + if !fields.contains_key(key) { + return Err(err(close_line, CanonCode::MissingKey(key.to_string()))); + } + } + let mut take = |key: &str| fields.remove(key).unwrap_or_default(); + let (id, id_line) = take("id"); + if !is_valid_app_id(&id) { + return Err(err(id_line, CanonCode::BadId(id))); + } + if id != file_stem { + return Err(err( + id_line, + CanonCode::IdMismatch { + id, + stem: file_stem.to_string(), + }, + )); + } + let (status_text, status_line) = take("status"); + let status = match status_text.as_str() { + "released" => Status::Released, + "beta" => Status::Beta, + "planned" => Status::Planned, + _ => return Err(err(status_line, CanonCode::BadStatus(status_text))), + }; + let mut url = |key: &str| -> Result, CanonError> { + let (v, line) = take(key); + if line == 0 { + Ok(None) + } else if is_single_https_url(&v) { + Ok(Some(v)) + } else { + Err(err(line, CanonCode::BadUrl(v))) + } + }; + let aula = url("aula")?; + let site = url("site")?; + let front = FrontMatter { + name: take("name").0, + one_liner: take("one_liner").0, + audience: take("audience").0, + price: take("price").0, + clicks: take("clicks").0, + status, + aula, + site, + }; + + // Body: fact lines. + let mut facts: Vec = Vec::new(); + let mut seen = BTreeSet::new(); + for (j, &line) in lines.iter().enumerate().skip(i + 1) { + let n = j + 1; + match text::item_line(line, 'F') { + ItemLine::No => {} + ItemLine::Malformed => return Err(err(n, CanonCode::MalformedFact)), + ItemLine::IdOutOfRange => return Err(err(n, CanonCode::FactIdOutOfRange)), + ItemLine::Item { id, text } => { + let (text, assumption) = split_marker(text.trim()); + if text.is_empty() { + return Err(err(n, CanonCode::EmptyFact)); + } + if !seen.insert(id) { + return Err(err(n, CanonCode::DuplicateFact(id))); + } + facts.push(Fact { + id, + text: text.to_string(), + assumption, + line: n, + }); + } + } + } + Ok(CanonFile { + id: file_stem.to_string(), + front, + facts, + }) +} + +/// Split a trailing `(assumption)` marker off (any case). A marker anywhere else also makes the fact an assumption. +fn split_marker(text: &str) -> (&str, bool) { + let len = text.len(); + if len >= MARKER.len() && text.is_char_boundary(len - MARKER.len()) { + let (head, tail) = text.split_at(len - MARKER.len()); + if tail.eq_ignore_ascii_case(MARKER) { + return (head.trim_end(), true); + } + } + (text, text.to_lowercase().contains(MARKER)) +} + +fn is_single_https_url(v: &str) -> bool { + let Some(rest) = v.strip_prefix("https://") else { + return false; + }; + if rest.is_empty() || v.chars().any(char::is_whitespace) { + return false; + } + let found = text::find_urls(v); + found.len() == 1 && found[0].kind == UrlKind::Scheme && found[0].as_str(v) == v } /// True if `id` is a valid app id: 1-32 of `[a-z0-9-]`, no leading or trailing `-`. pub fn is_valid_app_id(id: &str) -> bool { - let _ = id; - todo!() + !id.is_empty() + && id.len() <= 32 + && id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !id.starts_with('-') + && !id.ends_with('-') } /// True if a front matter value is marked `(assumption) `. pub fn is_assumption_value(value: &str) -> bool { - let _ = value; - todo!() + let v = value.trim_start(); + v.len() >= MARKER.len() + && v.is_char_boundary(MARKER.len()) + && v[..MARKER.len()].eq_ignore_ascii_case(MARKER) } impl CanonFile { /// The fact with this number. pub fn fact(&self, id: u32) -> Option<&Fact> { - let _ = id; - todo!() + self.facts.iter().find(|f| f.id == id) } /// Allowed URLs of this file: `aula`, `site`, and every `https://` URL inside a fact's text. Sorted, unique. pub fn urls(&self) -> Vec { - todo!() + let mut set: BTreeSet = BTreeSet::new(); + set.extend(self.front.aula.iter().cloned()); + set.extend(self.front.site.iter().cloned()); + for f in &self.facts { + for u in text::find_urls(&f.text) { + let s = u.as_str(&f.text); + if u.kind == UrlKind::Scheme + && s.len() > "https://".len() + && s.starts_with("https://") + { + set.insert(s.to_string()); + } + } + } + set.into_iter().collect() } /// An in-memory canon file (for the `release` source). Facts count as confirmed. Not validated. pub fn adhoc(id: &str, name: &str, facts: Vec<(u32, String)>) -> CanonFile { - let _ = (id, name, facts); - todo!() + CanonFile { + id: id.to_string(), + front: FrontMatter { + name: name.to_string(), + one_liner: String::new(), + audience: String::new(), + price: String::new(), + clicks: String::new(), + status: Status::Released, + aula: None, + site: None, + }, + facts: facts + .into_iter() + .map(|(id, text)| Fact { + id, + text, + assumption: false, + line: 0, + }) + .collect(), + } } } @@ -169,18 +381,20 @@ pub struct Canon { impl Canon { pub fn new() -> Self { - todo!() + Self::default() } /// Add a file. A second file with the same id is an error. pub fn insert(&mut self, f: CanonFile) -> Result<(), CanonError> { - let _ = f; - todo!() + if self.files.contains_key(&f.id) { + return Err(err(0, CanonCode::DuplicateApp(f.id))); + } + self.files.insert(f.id.clone(), f); + Ok(()) } pub fn get(&self, app: &str) -> Option<&CanonFile> { - let _ = app; - todo!() + self.files.get(app) } /// All files, sorted by id. @@ -189,12 +403,11 @@ impl Canon { } pub fn fact(&self, app: &str, id: u32) -> Option<&Fact> { - let _ = (app, id); - todo!() + self.get(app)?.fact(id) } /// The union of every file's [`CanonFile::urls`]. pub fn allowed_urls(&self) -> BTreeSet { - todo!() + self.files.values().flat_map(CanonFile::urls).collect() } } diff --git a/crates/scaena-core/src/claims.rs b/crates/scaena-core/src/claims.rs index cabe166..d3a07d6 100644 --- a/crates/scaena-core/src/claims.rs +++ b/crates/scaena-core/src/claims.rs @@ -6,11 +6,18 @@ //! Every sentence that states a fact carries at least one `[app#Fn]` reference (several may be adjacent: //! `[tabula#F3][tabula#F7]`) at its end, and every reference must point to a confirmed canon fact. //! Fail closed: a sentence states a fact unless it is one of a short list of plain phrases -//! ("Here's what's new.", "Try it today."). +//! ("Here's what's new.", "Try it today."), so numbers, prices, platforms and feature claims always need a reference. +//! +//! Sentences end at `.`, `!`, `?` or `…` followed by whitespace (or the end), and at every line break. +//! References directly after the end mark belong to the sentence before them. +//! URLs (`scheme://`, `www.`, bare `host.tld/path`) must be in [`Canon::allowed_urls`]. + +use std::collections::{BTreeSet, HashSet}; use serde::{Deserialize, Serialize}; -use crate::canon::Canon; +use crate::canon::{self, Canon}; +use crate::text::{self, FoundUrl}; /// A claim reference `[app#F]`. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] @@ -19,8 +26,14 @@ pub struct Ref { pub fact: u32, } +impl std::fmt::Display for Ref { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "[{}#F{}]", self.app, self.fact) + } +} + /// Why a text fails the claim check. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[non_exhaustive] pub enum Problem { /// A sentence that states a fact without any reference. @@ -42,7 +55,25 @@ pub enum Problem { impl Problem { /// Plain English, for "Needs facts". pub fn reason(&self) -> String { - todo!() + match self { + Problem::Unsourced { sentence } => { + format!("States a fact with no source: \"{sentence}\"") + } + Problem::MissingFact { r } => format!("{r} does not exist in the canon."), + Problem::UnknownApp { r } => format!("{r} points to an unknown app \"{}\".", r.app), + Problem::Unconfirmed { r } => { + format!( + "{r} is an unconfirmed fact (marked assumption); confirm it in the canon first." + ) + } + Problem::MalformedRef { text } => { + format!("\"{text}\" is not a valid reference; use [app#Fn].") + } + Problem::UrlNotInCanon { url } => format!("The URL {url} is not in the canon."), + Problem::HiddenCharacter { codepoint } => { + format!("Hidden or direction-changing character U+{codepoint:04X}.") + } + } } } @@ -60,26 +91,362 @@ impl Report { } } +/// Plain phrases that state no fact (normalised: lower case, letters, digits and apostrophes only). +/// `{app}` matches the name or id of any app in the canon. Keep this list short and conservative. +const PLAIN: &[&str] = &[ + "here's what's new", + "here is what's new", + "what's new", + "here's what changed", + "what changed", + "try it", + "try it today", + "try it now", + "try it out", + "try {app}", + "try {app} today", + "try {app} now", + "check it out", + "take a look", + "have a look", + "learn more", + "read more", + "more here", + "details here", + "more below", + "details below", + "get it here", + "get {app} here", + "download it here", + "release notes", + "full release notes", + "release notes below", + "thanks for reading", + "thank you", + "thanks", + "enjoy", + "let me know what you think", + "tell me what you think", + "feedback welcome", + "feedback is welcome", +]; + +/// Parse the inside of `[...]` as a reference. +fn parse_ref(content: &str) -> Option { + let (app, fact) = content.split_once("#F")?; + if !canon::is_valid_app_id(app) { + return None; + } + Some(Ref { + app: app.to_string(), + fact: text::parse_id(fact)?, + }) +} + +fn is_terminator(c: char) -> bool { + matches!(c, '.' | '!' | '?' | '…' | '。' | '!' | '?') +} + +fn is_closer(c: char) -> bool { + matches!(c, ')' | '"' | '\'' | '”' | '’' | '»' | '*' | '_') +} + +/// Sentence byte ranges (untrimmed; may be blank). +fn split(text: &str, urls: &[FoundUrl]) -> Vec<(usize, usize)> { + let chars: Vec<(usize, char)> = text.char_indices().collect(); + let n = chars.len(); + let mut in_url = vec![false; n]; + { + let mut u = 0; + for (k, &(pos, _)) in chars.iter().enumerate() { + while u < urls.len() && urls[u].end <= pos { + u += 1; + } + in_url[k] = u < urls.len() && urls[u].start <= pos && pos < urls[u].end; + } + } + let pos_of = |k: usize| if k < n { chars[k].0 } else { text.len() }; + let mut out = Vec::new(); + let mut start = 0; + let mut k = 0; + while k < n { + let (pos, c) = chars[k]; + if in_url[k] { + k += 1; + continue; + } + if c == '\n' || c == '\r' { + out.push((start, pos)); + start = pos + c.len_utf8(); + k += 1; + continue; + } + if is_terminator(c) { + let mut j = k + 1; + while j < n && !in_url[j] && (is_terminator(chars[j].1) || is_closer(chars[j].1)) { + j += 1; + } + // References right after the end mark belong to this sentence. + loop { + let mut m = j; + while m < n && matches!(chars[m].1, ' ' | '\t') { + m += 1; + } + match text::bracket_group(&chars, m) { + Some((end, range)) if text::is_ref_like(&text[range.clone()]) => j = end, + _ => break, + } + } + if j >= n || chars[j].1.is_whitespace() { + let end = pos_of(j); + out.push((start, end)); + start = end; + k = j; + continue; + } + } + k += 1; + } + out.push((start, text.len())); + out +} + +struct Scan { + refs: Vec, + malformed: Vec, + /// The sentence without references, malformed references and URLs. + residual: String, +} + +fn scan(seg: &str, seg_start: usize, urls: &[FoundUrl]) -> Scan { + let chars: Vec<(usize, char)> = seg.char_indices().collect(); + let n = chars.len(); + let mut refs = Vec::new(); + let mut malformed = Vec::new(); + let mut residual = String::with_capacity(seg.len()); + let mut k = 0; + while k < n { + let (pos, c) = chars[k]; + let abs = seg_start + pos; + if let Some(u) = urls.iter().find(|u| u.start <= abs && abs < u.end) { + residual.push(' '); + while k < n && seg_start + chars[k].0 < u.end { + k += 1; + } + continue; + } + if c == '[' { + if let Some((end, range)) = text::bracket_group(&chars, k) { + let content = &seg[range]; + if let Some(r) = parse_ref(content) { + refs.push(r); + residual.push(' '); + k = end; + continue; + } + if text::is_ref_like(content) { + malformed.push(format!("[{content}]")); + residual.push(' '); + k = end; + continue; + } + } else { + // An unclosed bracket: `[tabula#F1` up to the next whitespace. + let run_end = chars[k..] + .iter() + .position(|&(_, c)| c.is_whitespace()) + .map_or(n, |p| k + p); + let run = &seg[pos..pos_of(&chars, run_end, seg.len())]; + if run.contains('#') || text::is_ref_like(&run[1..]) { + malformed.push(run.to_string()); + residual.push(' '); + k = run_end; + continue; + } + } + } + residual.push(c); + k += 1; + } + // A bare `app#F1` without brackets. + for word in residual.split_whitespace() { + let w = word.as_bytes(); + if w.windows(3) + .any(|x| x[0] == b'#' && (x[1] == b'F' || x[1] == b'f') && x[2].is_ascii_digit()) + { + malformed.push(word.to_string()); + } + } + Scan { + refs, + malformed, + residual, + } +} + +fn pos_of(chars: &[(usize, char)], k: usize, len: usize) -> usize { + chars.get(k).map_or(len, |x| x.0) +} + +/// Lower case, letters, digits and apostrophes, single spaces. +fn normalize(s: &str) -> String { + let mapped: String = s + .chars() + .map(|c| match c { + '’' | '‘' | 'ʼ' | '`' => '\'', + c if c.is_alphanumeric() || c == '\'' => c, + _ => ' ', + }) + .collect(); + let words: Vec = mapped + .split_whitespace() + .map(|w| w.trim_matches('\'').to_lowercase()) + .filter(|w| !w.is_empty()) + .collect(); + words.join(" ") +} + +fn app_names(canon: &Canon) -> BTreeSet { + let mut names = BTreeSet::new(); + for f in canon.apps() { + for n in [normalize(&f.front.name), normalize(&f.id)] { + if !n.is_empty() && !n.chars().any(char::is_numeric) { + names.insert(n); + } + } + } + names +} + +fn is_plain(norm: &str, names: &BTreeSet) -> bool { + PLAIN.iter().any(|p| match p.split_once("{app}") { + None => *p == norm, + Some((pre, post)) => norm + .strip_prefix(pre) + .and_then(|rest| rest.strip_suffix(post)) + .is_some_and(|mid| names.contains(mid)), + }) +} + +fn needs_ref(residual: &str, names: &BTreeSet) -> bool { + let norm = normalize(residual); + !norm.is_empty() && !is_plain(&norm, names) +} + /// Check generated text against the canon. pub fn check(text: &str, canon: &Canon) -> Report { - let _ = (text, canon); - todo!() + let mut problems: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut push = |p: Problem, problems: &mut Vec| { + if seen.insert(p.clone()) { + problems.push(p); + } + }; + + for c in text.chars() { + if c != '\r' && text::is_forbidden(c) { + push( + Problem::HiddenCharacter { + codepoint: c as u32, + }, + &mut problems, + ); + } + } + + let urls = text::find_urls(text); + let allowed = canon.allowed_urls(); + for u in &urls { + let s = u.as_str(text); + if !text::url_allowed(s, u.kind, &allowed) { + push(Problem::UrlNotInCanon { url: s.to_string() }, &mut problems); + } + } + + let names = app_names(canon); + let mut all_refs: BTreeSet = BTreeSet::new(); + for (s, e) in split(text, &urls) { + let seg = &text[s..e]; + let first = urls.partition_point(|u| u.end <= s); + let last = urls.partition_point(|u| u.start < e); + let sc = scan(seg, s, &urls[first..last.max(first)]); + for m in sc.malformed { + push(Problem::MalformedRef { text: m }, &mut problems); + } + for r in &sc.refs { + let p = match canon.get(&r.app) { + None => Some(Problem::UnknownApp { r: r.clone() }), + Some(f) => match f.fact(r.fact) { + None => Some(Problem::MissingFact { r: r.clone() }), + Some(fact) if fact.assumption => Some(Problem::Unconfirmed { r: r.clone() }), + Some(_) => None, + }, + }; + if let Some(p) = p { + push(p, &mut problems); + } + } + if sc.refs.is_empty() && needs_ref(&sc.residual, &names) { + push( + Problem::Unsourced { + sentence: seg.trim().to_string(), + }, + &mut problems, + ); + } + all_refs.extend(sc.refs); + } + Report { + refs: all_refs.into_iter().collect(), + problems, + } } /// Remove every well-formed `[app#Fn]` reference (and the spaces before it), for display and posting. +/// Malformed references are left in place. pub fn strip_refs(text: &str) -> String { - let _ = text; - todo!() + let chars: Vec<(usize, char)> = text.char_indices().collect(); + let n = chars.len(); + let mut out = String::with_capacity(text.len()); + let mut k = 0; + while k < n { + let c = chars[k].1; + if c == '[' { + if let Some((end, range)) = text::bracket_group(&chars, k) { + if parse_ref(&text[range]).is_some() { + while out.ends_with([' ', '\t']) { + out.pop(); + } + k = end; + let next_alnum = chars.get(k).is_some_and(|x| x.1.is_alphanumeric()); + let prev_space = out.chars().last().is_none_or(char::is_whitespace); + if next_alnum && !prev_space { + out.push(' '); + } + continue; + } + } + } + out.push(c); + k += 1; + } + out } -/// Split text into sentences the way [`check`] does. +/// Split text into sentences the way [`check`] does (trimmed, blank ones left out). pub fn sentences(text: &str) -> Vec { - let _ = text; - todo!() + let urls = text::find_urls(text); + split(text, &urls) + .into_iter() + .map(|(s, e)| text[s..e].trim()) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect() } /// Whether [`check`] treats this sentence (without its references) as stating a fact. Fail closed. pub fn states_fact(sentence: &str, canon: &Canon) -> bool { - let _ = (sentence, canon); - todo!() + let urls = text::find_urls(sentence); + let sc = scan(sentence, 0, &urls); + needs_ref(&sc.residual, &app_names(canon)) } diff --git a/crates/scaena-core/src/hooks.rs b/crates/scaena-core/src/hooks.rs index 8fbf5fd..173537c 100644 --- a/crates/scaena-core/src/hooks.rs +++ b/crates/scaena-core/src/hooks.rs @@ -3,12 +3,17 @@ //! Hook templates: `brand/hooks.md` lines `- [H]