Files
ScaenaPublic/crates/scaena-core/src/claims.rs
T

453 lines
14 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
//! The claim checker.
//!
//! 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."), 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::{self, Canon};
use crate::text::{self, FoundUrl};
/// A claim reference `[app#F<fact>]`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Ref {
pub app: String,
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, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Problem {
/// A sentence that states a fact without any reference.
Unsourced { sentence: String },
/// The app exists, the fact does not.
MissingFact { r: Ref },
/// No canon file for the app.
UnknownApp { r: Ref },
/// The fact is marked `(assumption)`.
Unconfirmed { r: Ref },
/// Something that looks like a reference but is not `[app#Fn]`.
MalformedRef { text: String },
/// A URL that is not in [`Canon::allowed_urls`].
UrlNotInCanon { url: String },
/// A control, hidden or direction-changing character (addition to the Day 1 contract).
HiddenCharacter { codepoint: u32 },
}
impl Problem {
/// Plain English, for "Needs facts".
pub fn reason(&self) -> String {
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}.")
}
}
}
}
/// The result of [`check`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Report {
/// Every well-formed reference found, sorted and unique.
pub refs: Vec<Ref>,
pub problems: Vec<Problem>,
}
impl Report {
pub fn ok(&self) -> bool {
self.problems.is_empty()
}
}
/// 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<Ref> {
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<Ref>,
malformed: Vec<String>,
/// 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<String> = mapped
.split_whitespace()
.map(|w| w.trim_matches('\'').to_lowercase())
.filter(|w| !w.is_empty())
.collect();
words.join(" ")
}
fn app_names(canon: &Canon) -> BTreeSet<String> {
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<String>) -> 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<String>) -> 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 mut problems: Vec<Problem> = Vec::new();
let mut seen: HashSet<Problem> = HashSet::new();
let mut push = |p: Problem, problems: &mut Vec<Problem>| {
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<Ref> = 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 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 (trimmed, blank ones left out).
pub fn sentences(text: &str) -> Vec<String> {
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 urls = text::find_urls(sentence);
let sc = scan(sentence, 0, &urls);
needs_ref(&sc.residual, &app_names(canon))
}