[core] Merge: feature/core (scaena-core v0.1.0, PR #1)
This commit is contained in:
Generated
+413
@@ -0,0 +1,413 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
|
||||
dependencies = [
|
||||
"bit-vec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bit-vec"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastrand"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 6.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proptest"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
|
||||
dependencies = [
|
||||
"bit-set",
|
||||
"bit-vec",
|
||||
"bitflags",
|
||||
"num-traits",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"rand_xorshift",
|
||||
"regex-syntax",
|
||||
"rusty-fork",
|
||||
"tempfile",
|
||||
"unarray",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-error"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_xorshift"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusty-fork"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
|
||||
dependencies = [
|
||||
"fnv",
|
||||
"quick-error",
|
||||
"tempfile",
|
||||
"wait-timeout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scaena-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"proptest",
|
||||
"serde",
|
||||
"thiserror",
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.229"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.119"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.27.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "2.0.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unarray"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-segmentation"
|
||||
version = "1.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
|
||||
|
||||
[[package]]
|
||||
name = "wait-timeout"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.1+wasi-0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.46.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.64"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.64"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
@@ -0,0 +1,3 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/scaena-core"]
|
||||
@@ -4,6 +4,103 @@ The pure core of Scaena, Domi's video studio: canon parser and claim checker, ho
|
||||
model, ffmpeg argument compiler, ASS subtitle builder, audits, similarity scoring, hook evolution and Thompson
|
||||
sampling. Pure Rust, no I/O. Used by Praeco Domi by git tag.
|
||||
|
||||
## What's in v0
|
||||
|
||||
Crate `scaena-core` (`crates/scaena-core`), tag `core-v0.1.0`. Pure Rust, `#![forbid(unsafe_code)]`, no I/O;
|
||||
dependencies are serde, thiserror and unicode-segmentation only. Builds for Windows, Android
|
||||
(`aarch64-linux-android`) and the web (`wasm32-unknown-unknown`). If you redistribute it, alone or inside your own
|
||||
app, show the Exhibit B credit (see [Licence](#licence)).
|
||||
|
||||
```toml
|
||||
scaena-core = { git = "https://gitea.marek-novak.cz/mnovak/ScaenaPublic.git", tag = "core-v0.1.0" }
|
||||
```
|
||||
|
||||
### `scaena_core::canon`: canon files
|
||||
|
||||
```rust
|
||||
pub fn parse(file_stem: &str, text: &str) -> Result<CanonFile, CanonError>; // CanonError { line, code }
|
||||
pub struct CanonFile { pub id: String, pub front: FrontMatter, pub facts: Vec<Fact> }
|
||||
pub struct FrontMatter { pub name, one_liner, audience, price, clicks: String, pub status: Status,
|
||||
pub aula: Option<String>, pub site: Option<String> }
|
||||
pub enum Status { Released, Beta, Planned }
|
||||
pub struct Fact { pub id: u32, pub text: String, pub assumption: bool, pub line: usize }
|
||||
impl CanonFile { fn fact(&self, id: u32) -> Option<&Fact>; fn urls(&self) -> Vec<String>;
|
||||
fn adhoc(id: &str, name: &str, facts: Vec<(u32, String)>) -> CanonFile; }
|
||||
pub struct Canon; // new, insert (duplicate id = error), get, apps, fact, allowed_urls
|
||||
pub fn is_valid_app_id(id: &str) -> bool;
|
||||
pub fn is_assumption_value(value: &str) -> bool;
|
||||
```
|
||||
|
||||
The format of `apps/<id>.md` (UTF-8, at most 64 KiB):
|
||||
|
||||
```markdown
|
||||
---
|
||||
id: tabula
|
||||
name: Tabula
|
||||
one_liner: Notes that stay on your own computer.
|
||||
audience: People who want notes without an account.
|
||||
price: (assumption) one-time purchase
|
||||
clicks: New note in 1 click.
|
||||
status: released
|
||||
aula: https://aula.marek-novak.cz/tabula/
|
||||
---
|
||||
|
||||
## What it does
|
||||
- [F1] Tabula keeps notes on your own computer.
|
||||
- [F2] It syncs between your devices without a cloud account. (assumption)
|
||||
```
|
||||
|
||||
- Front matter: flat `key: value` lines between two `---` lines. Required: `id name one_liner audience price clicks
|
||||
status`; optional: `aula`, `site` (each a single `https://` URL). Unknown, duplicate, missing or empty keys are
|
||||
errors. `id` equals the file stem: 1–32 of `[a-z0-9-]`, no leading or trailing `-`. `status` is `released`,
|
||||
`beta` or `planned`.
|
||||
- Facts: `- [F<n>] <text>`, `n` 1–9999 without leading zeros, unique, under any heading. Any bullet line starting
|
||||
`[F` that does not match exactly is an error. A fact ending in `(assumption)` is unconfirmed; the marker is removed
|
||||
from `text` and `assumption` is set (a marker elsewhere in the text also sets it).
|
||||
- Hostile input: a leading BOM and CRLF line endings are accepted; a lone CR, control characters other than tab,
|
||||
bidi controls, zero-width space, word joiner, BOM inside the text and tag characters are errors.
|
||||
- Allowed URLs: `aula`, `site` and every `https://` URL in a fact's text.
|
||||
|
||||
### `scaena_core::claims`: the claim checker
|
||||
|
||||
```rust
|
||||
pub fn check(text: &str, canon: &Canon) -> Report;
|
||||
pub struct Report { pub refs: Vec<Ref> /* sorted, unique */, pub problems: Vec<Problem> } // ok() = no problems
|
||||
pub struct Ref { pub app: String, pub fact: u32 }
|
||||
pub enum Problem { Unsourced { sentence }, MissingFact { r }, UnknownApp { r }, Unconfirmed { r },
|
||||
MalformedRef { text }, UrlNotInCanon { url }, HiddenCharacter { codepoint } } // non_exhaustive
|
||||
impl Problem { pub fn reason(&self) -> String } // plain English
|
||||
pub fn strip_refs(text: &str) -> String;
|
||||
pub fn sentences(text: &str) -> Vec<String>;
|
||||
pub fn states_fact(sentence: &str, canon: &Canon) -> bool;
|
||||
```
|
||||
|
||||
- References look like `[tabula#F3]`; several may be adjacent (`[tabula#F3][tabula#F7]`), at the end of the
|
||||
sentence they support (before or after its full stop). A sentence ends at `.`, `!`, `?` or `…` followed by
|
||||
whitespace, and at every line break; `1.2` and URLs do not end one. The checker cannot tell whether a fact
|
||||
really supports its sentence: a valid reference anywhere in a sentence sources the whole sentence.
|
||||
- Fail closed: every sentence needs a reference to a confirmed fact unless it is one of a short list of plain
|
||||
phrases ("Here's what's new.", "Try it today.", "Try Tabula today.", "Learn more.", "Thanks for reading."…).
|
||||
So numbers, prices, platforms and feature claims always need one.
|
||||
- Rejected: unsourced sentences, references to unknown apps or missing facts, references to `(assumption)` facts
|
||||
("unconfirmed fact"), malformed references (`[F3]`, `[Tabula#F3]`, `tabula#F3`…), URLs not in
|
||||
`Canon::allowed_urls` (`scheme://`, `www.` and bare `host.tld/path` forms), hidden or direction-changing
|
||||
characters.
|
||||
|
||||
### `scaena_core::hooks`: hook templates
|
||||
|
||||
```rust
|
||||
pub fn parse(md: &str) -> Result<Vec<HookTemplate>, HookError>; // brand/hooks.md: "- [H<n>] <template>"
|
||||
pub struct HookTemplate { pub id: String /* "H3" */, pub text: String, pub slots: Vec<String>, pub genome: Genome }
|
||||
impl HookTemplate { pub fn fill(&self, values: &BTreeMap<String, String>) -> Result<String, HookError>; }
|
||||
pub struct Genome { pub opening: Opening, pub words: usize, pub has_number: bool, pub lead_verb: Option<String> }
|
||||
pub enum Opening { Question, Statement, Number, Command }
|
||||
pub const SLOTS: [&str; 7] = ["app", "feature", "pain", "number", "platform", "clicks", "audience"];
|
||||
```
|
||||
|
||||
Any slot outside `SLOTS` and any unbalanced brace is an error. `fill` fails on a missing value and never expands
|
||||
braces inside values.
|
||||
|
||||
## Licence
|
||||
|
||||
Common Public Attribution License 1.0 (CPAL-1.0), see [LICENSE](LICENSE).
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "scaena-core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
license = "CPAL-1.0"
|
||||
description = "Pure core of Scaena: canon parser, claim checker, hook templates. No I/O."
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/ScaenaPublic"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
thiserror = "2"
|
||||
unicode-segmentation = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = "1"
|
||||
@@ -0,0 +1,413 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
//! Canon files: `apps/<id>.md`, the only facts Praeco Domi may state.
|
||||
//!
|
||||
//! Format (strict):
|
||||
//!
|
||||
//! ```text
|
||||
//! ---
|
||||
//! id: tabula
|
||||
//! name: Tabula
|
||||
//! one_liner: Notes that stay on your own computer.
|
||||
//! audience: People who want notes without an account.
|
||||
//! price: (assumption) one-time purchase
|
||||
//! clicks: New note in 1 click.
|
||||
//! status: released
|
||||
//! aula: https://aula.marek-novak.cz/tabula/
|
||||
//! ---
|
||||
//!
|
||||
//! # Tabula
|
||||
//! - [F1] Tabula keeps notes on your own computer.
|
||||
//! - [F2] It syncs between your devices without a cloud account. (assumption)
|
||||
//! ```
|
||||
|
||||
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;
|
||||
|
||||
/// Highest fact number (`[F9999]`).
|
||||
pub const MAX_FACT_ID: u32 = 9999;
|
||||
|
||||
/// A parsed canon file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CanonFile {
|
||||
pub id: String,
|
||||
pub front: FrontMatter,
|
||||
pub facts: Vec<Fact>,
|
||||
}
|
||||
|
||||
/// The front matter of a canon file. Values are kept as written, including a leading `(assumption) `.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct FrontMatter {
|
||||
pub name: String,
|
||||
pub one_liner: String,
|
||||
pub audience: String,
|
||||
pub price: String,
|
||||
pub clicks: String,
|
||||
pub status: Status,
|
||||
pub aula: Option<String>,
|
||||
pub site: Option<String>,
|
||||
}
|
||||
|
||||
/// Release status of an app.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Status {
|
||||
Released,
|
||||
Beta,
|
||||
Planned,
|
||||
}
|
||||
|
||||
/// One fact line `- [F<id>] <text>`. `text` has the trailing ` (assumption)` marker removed;
|
||||
/// `assumption` says whether the fact is unconfirmed. `line` is 1-based (0 for ad-hoc facts).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Fact {
|
||||
pub id: u32,
|
||||
pub text: String,
|
||||
pub assumption: bool,
|
||||
pub line: usize,
|
||||
}
|
||||
|
||||
/// A canon error: the 1-based line it was found on (0 = the whole file) and what is wrong.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("line {line}: {code}")]
|
||||
pub struct CanonError {
|
||||
pub line: usize,
|
||||
pub code: CanonCode,
|
||||
}
|
||||
|
||||
/// What is wrong with a canon file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum CanonCode {
|
||||
#[error("the file is {bytes} bytes; the limit is 65536")]
|
||||
TooLarge { bytes: usize },
|
||||
#[error("forbidden character U+{codepoint:04X} (control, hidden or direction-changing)")]
|
||||
ForbiddenCharacter { codepoint: u32 },
|
||||
#[error("a carriage return that is not part of a CRLF line ending")]
|
||||
LoneCarriageReturn,
|
||||
#[error("the file must start with a '---' line")]
|
||||
NoFrontMatter,
|
||||
#[error("the front matter is not closed with a '---' line")]
|
||||
UnclosedFrontMatter,
|
||||
#[error("front matter lines must be 'key: value'")]
|
||||
FrontMatterLine,
|
||||
#[error("unknown front matter key '{0}'")]
|
||||
UnknownKey(String),
|
||||
#[error("front matter key '{0}' appears twice")]
|
||||
DuplicateKey(String),
|
||||
#[error("front matter key '{0}' is missing")]
|
||||
MissingKey(String),
|
||||
#[error("front matter key '{0}' has no value")]
|
||||
EmptyValue(String),
|
||||
#[error("'{0}' is not a valid app id (1-32 of a-z 0-9 -, no leading or trailing -)")]
|
||||
BadId(String),
|
||||
#[error("id '{id}' does not match the file name '{stem}'")]
|
||||
IdMismatch { id: String, stem: String },
|
||||
#[error("status '{0}' is not one of released, beta, planned")]
|
||||
BadStatus(String),
|
||||
#[error("'{0}' is not a single https:// URL")]
|
||||
BadUrl(String),
|
||||
#[error("a line starting '- [F' must be '- [F<n>] <text>'")]
|
||||
MalformedFact,
|
||||
#[error("fact number must be 1-9999 without leading zeros")]
|
||||
FactIdOutOfRange,
|
||||
#[error("fact F{0} appears twice")]
|
||||
DuplicateFact(u32),
|
||||
#[error("fact has no text")]
|
||||
EmptyFact,
|
||||
#[error("app '{0}' is already in the canon")]
|
||||
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/<file_stem>.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<CanonFile, CanonError> {
|
||||
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<Option<String>, 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<Fact> = 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 {
|
||||
!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 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> {
|
||||
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<String> {
|
||||
let mut set: BTreeSet<String> = 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 {
|
||||
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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The set of canon files, keyed by app id.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Canon {
|
||||
files: BTreeMap<String, CanonFile>,
|
||||
}
|
||||
|
||||
impl Canon {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Add a file. A second file with the same id is an error.
|
||||
pub fn insert(&mut self, f: CanonFile) -> Result<(), CanonError> {
|
||||
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> {
|
||||
self.files.get(app)
|
||||
}
|
||||
|
||||
/// All files, sorted by id.
|
||||
pub fn apps(&self) -> impl Iterator<Item = &CanonFile> {
|
||||
self.files.values()
|
||||
}
|
||||
|
||||
pub fn fact(&self, app: &str, id: u32) -> Option<&Fact> {
|
||||
self.get(app)?.fact(id)
|
||||
}
|
||||
|
||||
/// The union of every file's [`CanonFile::urls`].
|
||||
pub fn allowed_urls(&self) -> BTreeSet<String> {
|
||||
self.files.values().flat_map(CanonFile::urls).collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
// 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))
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
//! Hook templates: `brand/hooks.md` lines `- [H<n>] <template>` with slots from a fixed set.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
use crate::text::{self, ItemLine, LineError};
|
||||
|
||||
/// The only slot names a template may use.
|
||||
pub const SLOTS: [&str; 7] = [
|
||||
"app", "feature", "pain", "number", "platform", "clicks", "audience",
|
||||
];
|
||||
|
||||
/// Largest hooks file accepted, in bytes.
|
||||
pub const MAX_FILE_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// One hook template. `id` is `H<n>`; `slots` are unique, in order of first use.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct HookTemplate {
|
||||
pub id: String,
|
||||
pub text: String,
|
||||
pub slots: Vec<String>,
|
||||
pub genome: Genome,
|
||||
}
|
||||
|
||||
/// How a hook opens.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Opening {
|
||||
Question,
|
||||
Statement,
|
||||
Number,
|
||||
Command,
|
||||
}
|
||||
|
||||
/// A simple genome derived from a hook's text (Day 4 evolves it).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct Genome {
|
||||
pub opening: Opening,
|
||||
/// Words, a slot counts as one.
|
||||
pub words: usize,
|
||||
/// A digit or the `{number}` slot.
|
||||
pub has_number: bool,
|
||||
/// The first word, lowercased, when the hook opens with a command.
|
||||
pub lead_verb: Option<String>,
|
||||
}
|
||||
|
||||
/// Imperative openers recognised as commands.
|
||||
const COMMAND_VERBS: &[&str] = &[
|
||||
"ask", "build", "check", "discover", "ditch", "do", "don't", "dont", "download", "find",
|
||||
"forget", "get", "give", "grab", "imagine", "install", "join", "keep", "learn", "let", "make",
|
||||
"meet", "never", "open", "picture", "plan", "quit", "read", "save", "say", "see", "skip",
|
||||
"start", "stop", "switch", "take", "track", "try", "turn", "use", "watch", "write",
|
||||
];
|
||||
|
||||
impl Genome {
|
||||
/// Derive the genome from a template or a filled hook.
|
||||
///
|
||||
/// Opening, in this order: starts with a digit or `{number}` → number; first sentence ends with `?` →
|
||||
/// question; first word is a known imperative verb → command; otherwise statement.
|
||||
pub fn of(text: &str) -> Genome {
|
||||
let words: Vec<&str> = text.unicode_words().collect();
|
||||
let has_number = text.chars().any(char::is_numeric) || text.contains("{number}");
|
||||
let lead = text
|
||||
.trim_start()
|
||||
.trim_start_matches(|c: char| !c.is_alphanumeric() && c != '{');
|
||||
let first_word = words.first().map(|w| w.to_lowercase().replace('’', "'"));
|
||||
let opening = if lead.starts_with(|c: char| c.is_numeric()) || lead.starts_with("{number}")
|
||||
{
|
||||
Opening::Number
|
||||
} else if first_sentence_is_question(text) {
|
||||
Opening::Question
|
||||
} else if first_word
|
||||
.as_deref()
|
||||
.is_some_and(|w| COMMAND_VERBS.contains(&w))
|
||||
&& !lead.starts_with('{')
|
||||
{
|
||||
Opening::Command
|
||||
} else {
|
||||
Opening::Statement
|
||||
};
|
||||
let lead_verb = if opening == Opening::Command {
|
||||
first_word
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Genome {
|
||||
opening,
|
||||
words: words.len(),
|
||||
has_number,
|
||||
lead_verb,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn first_sentence_is_question(text: &str) -> bool {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
if matches!(c, '.' | '!' | '?' | '…') && chars.get(i + 1).is_none_or(|n| n.is_whitespace())
|
||||
{
|
||||
return c == '?';
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A hooks file error.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[non_exhaustive]
|
||||
pub enum HookError {
|
||||
#[error("the file is {bytes} bytes; the limit is 65536")]
|
||||
TooLarge { bytes: usize },
|
||||
#[error(
|
||||
"line {line}: forbidden character U+{codepoint:04X} (control, hidden or direction-changing)"
|
||||
)]
|
||||
ForbiddenCharacter { line: usize, codepoint: u32 },
|
||||
#[error("line {line}: a carriage return that is not part of a CRLF line ending")]
|
||||
LoneCarriageReturn { line: usize },
|
||||
#[error("line {line}: a line starting '- [H' must be '- [H<n>] <template>'")]
|
||||
Malformed { line: usize },
|
||||
#[error("line {line}: hook number must be 1-9999 without leading zeros")]
|
||||
IdOutOfRange { line: usize },
|
||||
#[error("line {line}: hook {id} appears twice")]
|
||||
Duplicate { line: usize, id: String },
|
||||
#[error("line {line}: unknown slot '{{{slot}}}'")]
|
||||
UnknownSlot { line: usize, slot: String },
|
||||
#[error("line {line}: unbalanced '{{' or '}}'")]
|
||||
UnbalancedBrace { line: usize },
|
||||
#[error("line {line}: hook has no text")]
|
||||
Empty { line: usize },
|
||||
#[error("no value for slot '{{{slot}}}'")]
|
||||
MissingValue { slot: String },
|
||||
}
|
||||
|
||||
/// The slots of a template, unique, in order of first use.
|
||||
fn slots_of(template: &str, line: usize) -> Result<Vec<String>, HookError> {
|
||||
let mut slots: Vec<String> = Vec::new();
|
||||
let mut rest = template;
|
||||
while let Some(i) = rest.find(['{', '}']) {
|
||||
if rest[i..].starts_with('}') {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
}
|
||||
let after = &rest[i + 1..];
|
||||
let Some(j) = after.find(['{', '}']) else {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
};
|
||||
if after[j..].starts_with('{') {
|
||||
return Err(HookError::UnbalancedBrace { line });
|
||||
}
|
||||
let name = &after[..j];
|
||||
if !SLOTS.contains(&name) {
|
||||
return Err(HookError::UnknownSlot {
|
||||
line,
|
||||
slot: name.to_string(),
|
||||
});
|
||||
}
|
||||
if !slots.iter().any(|s| s == name) {
|
||||
slots.push(name.to_string());
|
||||
}
|
||||
rest = &after[j + 1..];
|
||||
}
|
||||
Ok(slots)
|
||||
}
|
||||
|
||||
/// Parse `brand/hooks.md`. Lines that do not start `- [H` are ignored (headings, prose).
|
||||
///
|
||||
/// Strict like the canon: a bullet line starting `[H` must be exactly `- [H<n>] <template>`; a leading BOM and CRLF
|
||||
/// are tolerated; control, hidden and direction-changing characters are errors; 64 KiB at most.
|
||||
pub fn parse(md: &str) -> Result<Vec<HookTemplate>, HookError> {
|
||||
if md.len() > MAX_FILE_BYTES {
|
||||
return Err(HookError::TooLarge { bytes: md.len() });
|
||||
}
|
||||
let lines = text::clean_lines(md).map_err(|(line, e)| match e {
|
||||
LineError::LoneCr => HookError::LoneCarriageReturn { line },
|
||||
LineError::Forbidden(codepoint) => HookError::ForbiddenCharacter { line, codepoint },
|
||||
})?;
|
||||
let mut out = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for (i, &l) in lines.iter().enumerate() {
|
||||
let line = i + 1;
|
||||
match text::item_line(l, 'H') {
|
||||
ItemLine::No => {}
|
||||
ItemLine::Malformed => return Err(HookError::Malformed { line }),
|
||||
ItemLine::IdOutOfRange => return Err(HookError::IdOutOfRange { line }),
|
||||
ItemLine::Item { id, text } => {
|
||||
let text = text.trim();
|
||||
if text.is_empty() {
|
||||
return Err(HookError::Empty { line });
|
||||
}
|
||||
let id = format!("H{id}");
|
||||
if !seen.insert(id.clone()) {
|
||||
return Err(HookError::Duplicate { line, id });
|
||||
}
|
||||
let slots = slots_of(text, line)?;
|
||||
out.push(HookTemplate {
|
||||
id,
|
||||
text: text.to_string(),
|
||||
slots,
|
||||
genome: Genome::of(text),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl HookTemplate {
|
||||
/// Fill every slot. A missing value is an error; braces inside values are not expanded again.
|
||||
/// Extra values are ignored.
|
||||
pub fn fill(&self, values: &BTreeMap<String, String>) -> Result<String, HookError> {
|
||||
let mut out = String::with_capacity(self.text.len() + 32);
|
||||
let mut rest = self.text.as_str();
|
||||
while let Some(i) = rest.find('{') {
|
||||
out.push_str(&rest[..i]);
|
||||
let after = &rest[i + 1..];
|
||||
// Templates are validated at parse time; a hand-built one with a stray brace keeps it literally.
|
||||
let Some(j) = after.find('}') else {
|
||||
out.push_str(&rest[i..]);
|
||||
return Ok(out);
|
||||
};
|
||||
let name = &after[..j];
|
||||
let value = values.get(name).ok_or_else(|| HookError::MissingValue {
|
||||
slot: name.to_string(),
|
||||
})?;
|
||||
out.push_str(value);
|
||||
rest = &after[j + 1..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
//! `scaena-core`: the pure core of Scaena and Praeco Domi.
|
||||
//!
|
||||
//! - [`canon`]: the strict parser for canon files (`apps/<id>.md`), the only facts Praeco Domi may state.
|
||||
//! - [`claims`]: the claim checker. Every sentence that states a fact must carry an `[app#Fn]` reference to a
|
||||
//! confirmed canon fact. Fail closed: when unsure whether a sentence states a fact, it does.
|
||||
//! - [`hooks`]: hook templates (`brand/hooks.md`) with a fixed slot set, filling, and a simple genome.
|
||||
//!
|
||||
//! No I/O, no unsafe code.
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod canon;
|
||||
pub mod claims;
|
||||
pub mod hooks;
|
||||
|
||||
mod text;
|
||||
@@ -0,0 +1,299 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
//! Shared text scanning: forbidden characters, line splitting, URLs, claim references.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Control, hidden and direction-changing characters. `\n` and `\t` are fine; `\r` is handled by callers.
|
||||
pub(crate) fn is_forbidden(c: char) -> bool {
|
||||
match c {
|
||||
'\n' | '\t' => false,
|
||||
c if c.is_control() => true,
|
||||
'\u{061C}'
|
||||
| '\u{200B}'
|
||||
| '\u{200E}'
|
||||
| '\u{200F}'
|
||||
| '\u{202A}'..='\u{202E}'
|
||||
| '\u{2060}'..='\u{2064}'
|
||||
| '\u{2066}'..='\u{2069}'
|
||||
| '\u{FEFF}'
|
||||
| '\u{FFF9}'..='\u{FFFB}'
|
||||
| '\u{E0000}'..='\u{E007F}' => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum LineError {
|
||||
LoneCr,
|
||||
Forbidden(u32),
|
||||
}
|
||||
|
||||
/// Split a file into lines. A leading BOM is dropped and CRLF counts as LF; a lone CR or a forbidden
|
||||
/// character is an error with its 1-based line number.
|
||||
pub(crate) fn clean_lines(text: &str) -> Result<Vec<&str>, (usize, LineError)> {
|
||||
let text = text.strip_prefix('\u{FEFF}').unwrap_or(text);
|
||||
let mut out = Vec::new();
|
||||
for (i, raw) in text.split('\n').enumerate() {
|
||||
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
if line.contains('\r') {
|
||||
return Err((i + 1, LineError::LoneCr));
|
||||
}
|
||||
if let Some(c) = line.chars().find(|&c| is_forbidden(c)) {
|
||||
return Err((i + 1, LineError::Forbidden(c as u32)));
|
||||
}
|
||||
out.push(line);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Parse the number of a `[F<n>]` / `[H<n>]` id: 1-9999, ASCII digits, no leading zeros.
|
||||
pub(crate) fn parse_id(digits: &str) -> Option<u32> {
|
||||
if digits.is_empty()
|
||||
|| digits.len() > 4
|
||||
|| digits.starts_with('0')
|
||||
|| !digits.bytes().all(|b| b.is_ascii_digit())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
digits.parse().ok()
|
||||
}
|
||||
|
||||
/// How a strict `- [X<n>] <text>` line parsed.
|
||||
pub(crate) enum ItemLine<'a> {
|
||||
/// Not an item line of this kind.
|
||||
No,
|
||||
Malformed,
|
||||
IdOutOfRange,
|
||||
Item {
|
||||
id: u32,
|
||||
text: &'a str,
|
||||
},
|
||||
}
|
||||
|
||||
/// Parse a `- [<letter><n>] <text>` line strictly. Any bullet line whose content starts `[<letter>` (any case,
|
||||
/// any indentation, any bullet) counts as an attempt and must match exactly.
|
||||
pub(crate) fn item_line(line: &str, letter: char) -> ItemLine<'_> {
|
||||
let t = line.trim_start();
|
||||
let Some(rest) = t.strip_prefix(['-', '*', '+']) else {
|
||||
return ItemLine::No;
|
||||
};
|
||||
let rest = rest.trim_start();
|
||||
let mut cs = rest.chars();
|
||||
if cs.next() != Some('[') || !cs.next().is_some_and(|c| c.eq_ignore_ascii_case(&letter)) {
|
||||
return ItemLine::No;
|
||||
}
|
||||
let prefix = format!("- [{letter}");
|
||||
let Some(rest) = line.strip_prefix(prefix.as_str()) else {
|
||||
return ItemLine::Malformed;
|
||||
};
|
||||
let digits_len = rest.bytes().take_while(u8::is_ascii_digit).count();
|
||||
let (digits, rest) = rest.split_at(digits_len);
|
||||
if digits.is_empty() {
|
||||
return ItemLine::Malformed;
|
||||
}
|
||||
let Some(text) = rest.strip_prefix("] ") else {
|
||||
return ItemLine::Malformed;
|
||||
};
|
||||
match parse_id(digits) {
|
||||
Some(id) => ItemLine::Item { id, text },
|
||||
None => ItemLine::IdOutOfRange,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum UrlKind {
|
||||
/// `scheme://...`
|
||||
Scheme,
|
||||
/// `www.example.com...` without a scheme.
|
||||
Www,
|
||||
/// `example.com/...` or `example.com` with a common top-level domain.
|
||||
Bare,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct FoundUrl {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub kind: UrlKind,
|
||||
}
|
||||
|
||||
impl FoundUrl {
|
||||
pub fn as_str<'a>(&self, text: &'a str) -> &'a str {
|
||||
&text[self.start..self.end]
|
||||
}
|
||||
}
|
||||
|
||||
fn is_url_stop(c: char) -> bool {
|
||||
c.is_whitespace()
|
||||
|| matches!(
|
||||
c,
|
||||
'<' | '>'
|
||||
| '"'
|
||||
| '\''
|
||||
| '['
|
||||
| ']'
|
||||
| '{'
|
||||
| '}'
|
||||
| '|'
|
||||
| '\\'
|
||||
| '^'
|
||||
| '`'
|
||||
| '('
|
||||
| ')'
|
||||
| '“'
|
||||
| '”'
|
||||
| '‘'
|
||||
| '’'
|
||||
| '«'
|
||||
| '»'
|
||||
)
|
||||
}
|
||||
|
||||
fn is_edge_punct(c: char) -> bool {
|
||||
matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | '*' | '_' | '~' | '…')
|
||||
}
|
||||
|
||||
const COMMON_TLDS: &[&str] = &[
|
||||
"com", "net", "org", "io", "dev", "app", "cz", "sk", "de", "eu", "uk", "us", "me", "co", "ai",
|
||||
"gg", "tv", "xyz", "info", "biz", "page", "site", "online", "tech", "store", "blog", "fr",
|
||||
"nl", "pl", "at", "ch", "it", "es", "ru", "cn", "jp", "ly", "to", "sh", "so", "gl", "im", "fm",
|
||||
"ws", "link", "click", "live", "cloud", "news", "shop", "social", "gov", "edu",
|
||||
];
|
||||
|
||||
fn looks_like_host(host: &str) -> Option<&str> {
|
||||
let host = host.rsplit('@').next().unwrap_or(host);
|
||||
let labels: Vec<&str> = host.split('.').collect();
|
||||
if labels.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
if !labels
|
||||
.iter()
|
||||
.all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let tld = labels[labels.len() - 1];
|
||||
if tld.len() < 2 || tld.len() > 24 || !tld.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||
return None;
|
||||
}
|
||||
Some(tld)
|
||||
}
|
||||
|
||||
/// Find URLs: any `scheme://`, any `www.` token, and bare `host.tld/path` or `host.<common tld>` tokens.
|
||||
/// Trailing sentence punctuation is not part of a URL.
|
||||
pub(crate) fn find_urls(text: &str) -> Vec<FoundUrl> {
|
||||
let mut out = Vec::new();
|
||||
let mut tok_start: Option<usize> = None;
|
||||
let handle = |s: usize, e: usize, out: &mut Vec<FoundUrl>| {
|
||||
let tok = &text[s..e];
|
||||
// Trim edge punctuation.
|
||||
let lead = tok.len() - tok.trim_start_matches(is_edge_punct).len();
|
||||
let trimmed = tok
|
||||
.trim_start_matches(is_edge_punct)
|
||||
.trim_end_matches(is_edge_punct);
|
||||
if trimmed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (s, e) = (s + lead, s + lead + trimmed.len());
|
||||
if let Some(p) = trimmed.find("://") {
|
||||
let scheme_start = trimmed[..p]
|
||||
.char_indices()
|
||||
.rev()
|
||||
.take_while(|&(_, c)| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
|
||||
.last()
|
||||
.map_or(p, |(i, _)| i);
|
||||
out.push(FoundUrl {
|
||||
start: s + scheme_start,
|
||||
end: e,
|
||||
kind: UrlKind::Scheme,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if trimmed.len() >= 4
|
||||
&& trimmed.is_char_boundary(4)
|
||||
&& trimmed[..4].eq_ignore_ascii_case("www.")
|
||||
{
|
||||
out.push(FoundUrl {
|
||||
start: s,
|
||||
end: e,
|
||||
kind: UrlKind::Www,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let (host, has_path) = match trimmed.find('/') {
|
||||
Some(i) => (&trimmed[..i], true),
|
||||
None => (trimmed, false),
|
||||
};
|
||||
if let Some(tld) = looks_like_host(host) {
|
||||
if has_path || COMMON_TLDS.contains(&tld.to_ascii_lowercase().as_str()) {
|
||||
out.push(FoundUrl {
|
||||
start: s,
|
||||
end: e,
|
||||
kind: UrlKind::Bare,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
for (i, c) in text.char_indices() {
|
||||
if is_url_stop(c) {
|
||||
if let Some(s) = tok_start.take() {
|
||||
handle(s, i, &mut out);
|
||||
}
|
||||
} else if tok_start.is_none() {
|
||||
tok_start = Some(i);
|
||||
}
|
||||
}
|
||||
if let Some(s) = tok_start {
|
||||
handle(s, text.len(), &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn toggle_slash(u: &str) -> String {
|
||||
match u.strip_suffix('/') {
|
||||
Some(x) => x.to_string(),
|
||||
None => format!("{u}/"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a found URL is one of the allowed ones (a trailing `/` does not matter; bare forms are read as https).
|
||||
pub(crate) fn url_allowed(url: &str, kind: UrlKind, allowed: &BTreeSet<String>) -> bool {
|
||||
let full = match kind {
|
||||
UrlKind::Scheme => url.to_string(),
|
||||
UrlKind::Www | UrlKind::Bare => format!("https://{url}"),
|
||||
};
|
||||
allowed.contains(&full) || allowed.contains(&toggle_slash(&full))
|
||||
}
|
||||
|
||||
/// If `chars[at]` is `[` and a `]` follows on the same line within 64 characters with no `[` in between,
|
||||
/// the index just after the `]` and the content between the brackets.
|
||||
pub(crate) fn bracket_group(
|
||||
chars: &[(usize, char)],
|
||||
at: usize,
|
||||
) -> Option<(usize, std::ops::Range<usize>)> {
|
||||
if chars.get(at).map(|x| x.1) != Some('[') {
|
||||
return None;
|
||||
}
|
||||
let content_start = chars[at].0 + 1;
|
||||
for (j, &(pos, c)) in chars.iter().enumerate().take(at + 66).skip(at + 1) {
|
||||
match c {
|
||||
']' => return Some((j + 1, content_start..pos)),
|
||||
'[' | '\n' | '\r' => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Content of a bracket group that is meant as a claim reference (well-formed or not).
|
||||
pub(crate) fn is_ref_like(content: &str) -> bool {
|
||||
if content.contains('#') {
|
||||
return true;
|
||||
}
|
||||
let mut cs = content.chars();
|
||||
matches!(cs.next(), Some('F' | 'f')) && {
|
||||
let rest = cs.as_str().trim();
|
||||
!rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
use scaena_core::canon::{self, Canon, CanonCode, CanonFile, Status};
|
||||
|
||||
const TABULA: &str = "---
|
||||
id: tabula
|
||||
name: Tabula
|
||||
one_liner: Notes that stay on your own computer.
|
||||
audience: People who want notes without an account.
|
||||
price: (assumption) one-time purchase
|
||||
clicks: New note in 1 click.
|
||||
status: released
|
||||
aula: https://aula.marek-novak.cz/tabula/
|
||||
---
|
||||
<!-- sources: Mark, 2026-11-23 -->
|
||||
|
||||
# Tabula
|
||||
|
||||
## What it does
|
||||
- [F1] Tabula keeps notes on your own computer.
|
||||
- [F2] It syncs between your devices without a cloud account. (assumption)
|
||||
|
||||
## Honest limits
|
||||
- [F3] There is no phone app yet. Docs: https://aula.marek-novak.cz/tabula/limits.
|
||||
";
|
||||
|
||||
fn code(stem: &str, text: &str) -> (usize, CanonCode) {
|
||||
let e = canon::parse(stem, text).expect_err("must be rejected");
|
||||
(e.line, e.code)
|
||||
}
|
||||
|
||||
fn with_front(front: &str, body: &str) -> String {
|
||||
format!("---\n{front}---\n{body}")
|
||||
}
|
||||
|
||||
const FRONT: &str = "id: tabula
|
||||
name: Tabula
|
||||
one_liner: Notes.
|
||||
audience: Everyone.
|
||||
price: free
|
||||
clicks: 1 click.
|
||||
status: beta
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn parses_the_sample_file() {
|
||||
let f = canon::parse("tabula", TABULA).unwrap();
|
||||
assert_eq!(f.id, "tabula");
|
||||
assert_eq!(f.front.name, "Tabula");
|
||||
assert_eq!(f.front.one_liner, "Notes that stay on your own computer.");
|
||||
assert_eq!(
|
||||
f.front.audience,
|
||||
"People who want notes without an account."
|
||||
);
|
||||
assert_eq!(f.front.price, "(assumption) one-time purchase");
|
||||
assert!(canon::is_assumption_value(&f.front.price));
|
||||
assert!(!canon::is_assumption_value(&f.front.name));
|
||||
assert_eq!(f.front.clicks, "New note in 1 click.");
|
||||
assert_eq!(f.front.status, Status::Released);
|
||||
assert_eq!(
|
||||
f.front.aula.as_deref(),
|
||||
Some("https://aula.marek-novak.cz/tabula/")
|
||||
);
|
||||
assert_eq!(f.front.site, None);
|
||||
assert_eq!(f.facts.len(), 3);
|
||||
let f1 = f.fact(1).unwrap();
|
||||
assert_eq!(f1.text, "Tabula keeps notes on your own computer.");
|
||||
assert!(!f1.assumption);
|
||||
assert_eq!(f1.line, 16);
|
||||
let f2 = f.fact(2).unwrap();
|
||||
assert_eq!(
|
||||
f2.text,
|
||||
"It syncs between your devices without a cloud account."
|
||||
);
|
||||
assert!(f2.assumption);
|
||||
assert_eq!(f2.line, 17);
|
||||
assert!(f.fact(4).is_none());
|
||||
assert!(f.fact(0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn urls_are_front_matter_plus_https_in_facts() {
|
||||
let f = canon::parse("tabula", TABULA).unwrap();
|
||||
assert_eq!(
|
||||
f.urls(),
|
||||
vec![
|
||||
"https://aula.marek-novak.cz/tabula/".to_string(),
|
||||
"https://aula.marek-novak.cz/tabula/limits".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_urls_in_facts_are_not_allowed() {
|
||||
let text = with_front(
|
||||
FRONT,
|
||||
"- [F1] See http://example.com/x and https://example.com/y.\n",
|
||||
);
|
||||
let f = canon::parse("tabula", &text).unwrap();
|
||||
assert_eq!(f.urls(), vec!["https://example.com/y".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn site_and_status_values() {
|
||||
for (s, st) in [
|
||||
("released", Status::Released),
|
||||
("beta", Status::Beta),
|
||||
("planned", Status::Planned),
|
||||
] {
|
||||
let front = FRONT.replace("status: beta", &format!("status: {s}"));
|
||||
let text = with_front(&format!("{front}site: https://tabula.example/\n"), "");
|
||||
let f = canon::parse("tabula", &text).unwrap();
|
||||
assert_eq!(f.front.status, st);
|
||||
assert_eq!(f.front.site.as_deref(), Some("https://tabula.example/"));
|
||||
assert!(f.facts.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_status() {
|
||||
let front = FRONT.replace("status: beta", "status: Released");
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")),
|
||||
(8, CanonCode::BadStatus("Released".into()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_unknown_duplicate_and_empty_keys() {
|
||||
let front = FRONT.replace("price: free\n", "");
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")).1,
|
||||
CanonCode::MissingKey("price".into())
|
||||
);
|
||||
|
||||
let front = format!("{FRONT}colour: brass\n");
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")),
|
||||
(9, CanonCode::UnknownKey("colour".into()))
|
||||
);
|
||||
|
||||
let front = format!("{FRONT}name: Other\n");
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")),
|
||||
(9, CanonCode::DuplicateKey("name".into()))
|
||||
);
|
||||
|
||||
let front = FRONT.replace("price: free", "price:");
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")).1,
|
||||
CanonCode::EmptyValue("price".into())
|
||||
);
|
||||
|
||||
let front = FRONT.replace("price: free", "price: ");
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")).1,
|
||||
CanonCode::EmptyValue("price".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_flat_front_matter() {
|
||||
for bad in [
|
||||
"just text",
|
||||
" indented: yes",
|
||||
"list:\n - a",
|
||||
"",
|
||||
"# comment",
|
||||
"Name: Tabula",
|
||||
"key:value",
|
||||
] {
|
||||
let front = format!("{FRONT}{bad}\n");
|
||||
let (line, c) = code("tabula", &with_front(&front, ""));
|
||||
assert_eq!(line, 9, "{bad:?}");
|
||||
assert!(
|
||||
matches!(c, CanonCode::FrontMatterLine | CanonCode::UnknownKey(_)),
|
||||
"{bad:?} gave {c:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_or_unclosed_front_matter() {
|
||||
assert_eq!(
|
||||
code("tabula", "# Tabula\n- [F1] x\n"),
|
||||
(1, CanonCode::NoFrontMatter)
|
||||
);
|
||||
assert_eq!(code("tabula", ""), (1, CanonCode::NoFrontMatter));
|
||||
assert_eq!(code("tabula", " ---\n"), (1, CanonCode::NoFrontMatter));
|
||||
assert_eq!(
|
||||
code("tabula", &format!("---\n{FRONT}")).1,
|
||||
CanonCode::UnclosedFrontMatter
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id_must_match_stem_and_be_valid() {
|
||||
assert_eq!(
|
||||
code("other", &with_front(FRONT, "")),
|
||||
(
|
||||
2,
|
||||
CanonCode::IdMismatch {
|
||||
id: "tabula".into(),
|
||||
stem: "other".into()
|
||||
}
|
||||
)
|
||||
);
|
||||
for bad in [
|
||||
"Tabula",
|
||||
"-tabula",
|
||||
"tabula-",
|
||||
"tab_ula",
|
||||
"tab ula",
|
||||
"a234567890123456789012345678901234",
|
||||
] {
|
||||
let front = FRONT.replace("id: tabula", &format!("id: {bad}"));
|
||||
let c = code(bad, &with_front(&front, "")).1;
|
||||
assert_eq!(c, CanonCode::BadId(bad.trim().into()), "{bad:?}");
|
||||
}
|
||||
assert!(canon::is_valid_app_id("a"));
|
||||
assert!(canon::is_valid_app_id("my-app-2"));
|
||||
assert!(canon::is_valid_app_id("a2345678901234567890123456789012"));
|
||||
assert!(!canon::is_valid_app_id(""));
|
||||
assert!(!canon::is_valid_app_id("a23456789012345678901234567890123"));
|
||||
assert!(!canon::is_valid_app_id("é"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn urls_in_front_matter_must_be_https() {
|
||||
for bad in [
|
||||
"http://aula.example/",
|
||||
"aula.example",
|
||||
"https://a b",
|
||||
"https://",
|
||||
] {
|
||||
let text = with_front(&format!("{FRONT}aula: {bad}\n"), "");
|
||||
assert_eq!(
|
||||
code("tabula", &text).1,
|
||||
CanonCode::BadUrl(bad.into()),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_fact_lines() {
|
||||
for bad in [
|
||||
"- [F] no number",
|
||||
"- [Fx] letters",
|
||||
"- [F1]no space",
|
||||
"- [F1 missing bracket",
|
||||
"- [F1]",
|
||||
"- [f1] lowercase",
|
||||
"- [F1] two spaces",
|
||||
"* [F1] star bullet",
|
||||
" - [F1] indented",
|
||||
"- [F1a] suffix",
|
||||
"- [F-1] negative",
|
||||
] {
|
||||
let text = with_front(FRONT, &format!("\n{bad}\n"));
|
||||
let (line, c) = code("tabula", &text);
|
||||
assert_eq!(line, 11, "{bad:?}");
|
||||
assert!(
|
||||
matches!(c, CanonCode::MalformedFact | CanonCode::EmptyFact),
|
||||
"{bad:?} gave {c:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fact_ids_in_range_without_leading_zeros() {
|
||||
let ok = with_front(FRONT, "- [F1] a\n- [F9999] b\n");
|
||||
let f = canon::parse("tabula", &ok).unwrap();
|
||||
assert_eq!(
|
||||
f.facts.iter().map(|x| x.id).collect::<Vec<_>>(),
|
||||
vec![1, 9999]
|
||||
);
|
||||
for bad in [
|
||||
"- [F0] zero",
|
||||
"- [F10000] big",
|
||||
"- [F01] lead",
|
||||
"- [F99999999999999999999] huge",
|
||||
] {
|
||||
let text = with_front(FRONT, &format!("{bad}\n"));
|
||||
assert_eq!(
|
||||
code("tabula", &text),
|
||||
(10, CanonCode::FactIdOutOfRange),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_facts_and_empty_facts() {
|
||||
let text = with_front(FRONT, "- [F1] a\n## Limits\n- [F1] b\n");
|
||||
assert_eq!(code("tabula", &text), (12, CanonCode::DuplicateFact(1)));
|
||||
let text = with_front(FRONT, "- [F1] \n");
|
||||
assert_eq!(code("tabula", &text), (10, CanonCode::EmptyFact));
|
||||
let text = with_front(FRONT, "- [F1] (assumption)\n");
|
||||
assert_eq!(code("tabula", &text), (10, CanonCode::EmptyFact));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assumption_marker() {
|
||||
let text = with_front(
|
||||
FRONT,
|
||||
"- [F1] Plain.\n- [F2] Unsure. (assumption)\n- [F3] Odd case (Assumption)\n\
|
||||
- [F4] Inside (assumption) the text.\n- [F5] Trailing spaces (assumption) \n",
|
||||
);
|
||||
let f = canon::parse("tabula", &text).unwrap();
|
||||
let got: Vec<(&str, bool)> = f
|
||||
.facts
|
||||
.iter()
|
||||
.map(|x| (x.text.as_str(), x.assumption))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
vec![
|
||||
("Plain.", false),
|
||||
("Unsure.", true),
|
||||
("Odd case", true),
|
||||
("Inside (assumption) the text.", true),
|
||||
("Trailing spaces", true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_body_lines_are_ignored() {
|
||||
let text = with_front(
|
||||
FRONT,
|
||||
"# T\n\nSome prose [F7] here.\n- plain bullet\n> - [F9] quoted\n- [F1] fact\n",
|
||||
);
|
||||
let f = canon::parse("tabula", &text).unwrap();
|
||||
assert_eq!(f.facts.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn size_limit_is_64_kib() {
|
||||
let mut text = with_front(FRONT, "");
|
||||
while text.len() < canon::MAX_FILE_BYTES {
|
||||
text.push('\n');
|
||||
}
|
||||
assert_eq!(text.len(), canon::MAX_FILE_BYTES);
|
||||
assert!(canon::parse("tabula", &text).is_ok());
|
||||
text.push('\n');
|
||||
assert_eq!(
|
||||
code("tabula", &text),
|
||||
(
|
||||
0,
|
||||
CanonCode::TooLarge {
|
||||
bytes: canon::MAX_FILE_BYTES + 1
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_line_is_fine_under_the_limit_and_rejected_over_it() {
|
||||
let long = "a".repeat(60 * 1024);
|
||||
let text = with_front(FRONT, &format!("- [F1] {long}\n"));
|
||||
assert_eq!(
|
||||
canon::parse("tabula", &text).unwrap().facts[0].text.len(),
|
||||
long.len()
|
||||
);
|
||||
let long = "a".repeat(70 * 1024);
|
||||
let text = with_front(FRONT, &format!("- [F1] {long}\n"));
|
||||
assert!(matches!(
|
||||
code("tabula", &text).1,
|
||||
CanonCode::TooLarge { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bom_and_crlf_are_tolerated() {
|
||||
let crlf = TABULA.replace('\n', "\r\n");
|
||||
let a = canon::parse("tabula", TABULA).unwrap();
|
||||
let b = canon::parse("tabula", &crlf).unwrap();
|
||||
assert_eq!(a, b);
|
||||
let bom = format!("\u{feff}{TABULA}");
|
||||
assert_eq!(canon::parse("tabula", &bom).unwrap(), a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lone_cr_nul_and_hidden_characters_are_rejected() {
|
||||
let text = with_front(FRONT, "- [F1] a\rb\n");
|
||||
assert_eq!(code("tabula", &text), (10, CanonCode::LoneCarriageReturn));
|
||||
for (ch, cp) in [
|
||||
('\0', 0u32),
|
||||
('\u{7}', 7),
|
||||
('\u{7f}', 0x7f),
|
||||
('\u{85}', 0x85),
|
||||
('\u{202e}', 0x202e),
|
||||
('\u{2066}', 0x2066),
|
||||
('\u{200f}', 0x200f),
|
||||
('\u{061c}', 0x061c),
|
||||
('\u{200b}', 0x200b),
|
||||
('\u{feff}', 0xfeff),
|
||||
('\u{e0041}', 0xe0041),
|
||||
] {
|
||||
let text = with_front(FRONT, &format!("- [F1] a{ch}b\n"));
|
||||
assert_eq!(
|
||||
code("tabula", &text),
|
||||
(10, CanonCode::ForbiddenCharacter { codepoint: cp }),
|
||||
"{cp:X}"
|
||||
);
|
||||
}
|
||||
// In the front matter too.
|
||||
let front = FRONT.replace("name: Tabula", "name: Tab\u{202e}ula");
|
||||
assert_eq!(
|
||||
code("tabula", &with_front(&front, "")),
|
||||
(3, CanonCode::ForbiddenCharacter { codepoint: 0x202e })
|
||||
);
|
||||
// Tabs and ordinary non-ASCII text are fine.
|
||||
let text = with_front(FRONT, "- [F1] Poznámky\tžluťoučký kůň 📝\n");
|
||||
assert!(canon::parse("tabula", &text).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canon_set() {
|
||||
let mut c = Canon::new();
|
||||
c.insert(canon::parse("tabula", TABULA).unwrap()).unwrap();
|
||||
let err = c
|
||||
.insert(canon::parse("tabula", TABULA).unwrap())
|
||||
.unwrap_err();
|
||||
assert_eq!(err.code, CanonCode::DuplicateApp("tabula".into()));
|
||||
c.insert(CanonFile::adhoc(
|
||||
"release",
|
||||
"Tabula",
|
||||
vec![(1, "Tabula 1.2 is out.".into())],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
c.apps().map(|f| f.id.as_str()).collect::<Vec<_>>(),
|
||||
vec!["release", "tabula"]
|
||||
);
|
||||
assert!(c.get("tabula").is_some());
|
||||
assert!(c.get("nope").is_none());
|
||||
assert_eq!(
|
||||
c.fact("tabula", 1).unwrap().text,
|
||||
"Tabula keeps notes on your own computer."
|
||||
);
|
||||
assert!(c.fact("tabula", 9).is_none());
|
||||
assert!(c.fact("nope", 1).is_none());
|
||||
let urls = c.allowed_urls();
|
||||
assert!(urls.contains("https://aula.marek-novak.cz/tabula/"));
|
||||
assert!(urls.contains("https://aula.marek-novak.cz/tabula/limits"));
|
||||
assert_eq!(urls.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adhoc_release_file() {
|
||||
let f = CanonFile::adhoc(
|
||||
"release",
|
||||
"Tabula",
|
||||
vec![
|
||||
(1, "Tabula 1.2 is out.".into()),
|
||||
(2, "Faster search. (assumption)".into()),
|
||||
],
|
||||
);
|
||||
assert_eq!(f.id, "release");
|
||||
assert_eq!(f.front.name, "Tabula");
|
||||
assert_eq!(f.facts.len(), 2);
|
||||
assert!(
|
||||
f.facts.iter().all(|x| !x.assumption),
|
||||
"release facts count as confirmed"
|
||||
);
|
||||
assert_eq!(f.fact(2).unwrap().text, "Faster search. (assumption)");
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
use scaena_core::canon::{self, Canon, CanonFile};
|
||||
use scaena_core::claims::{self, Problem, Ref};
|
||||
|
||||
const TABULA: &str = "---
|
||||
id: tabula
|
||||
name: Tabula
|
||||
one_liner: Notes that stay on your own computer.
|
||||
audience: People who want notes without an account.
|
||||
price: (assumption) one-time purchase
|
||||
clicks: New note in 1 click.
|
||||
status: released
|
||||
aula: https://aula.marek-novak.cz/tabula/
|
||||
---
|
||||
- [F1] Tabula keeps notes on your own computer.
|
||||
- [F2] It syncs between your devices without a cloud account. (assumption)
|
||||
- [F3] It runs on Windows. More: https://aula.marek-novak.cz/tabula/windows
|
||||
- [F7] A new note takes 1 click.
|
||||
";
|
||||
|
||||
fn canon() -> Canon {
|
||||
let mut c = Canon::new();
|
||||
c.insert(canon::parse("tabula", TABULA).unwrap()).unwrap();
|
||||
c.insert(CanonFile::adhoc(
|
||||
"release",
|
||||
"Tabula",
|
||||
vec![
|
||||
(1, "Tabula 1.2 is out.".into()),
|
||||
(2, "Search is faster.".into()),
|
||||
],
|
||||
))
|
||||
.unwrap();
|
||||
c
|
||||
}
|
||||
|
||||
fn r(app: &str, fact: u32) -> Ref {
|
||||
Ref {
|
||||
app: app.into(),
|
||||
fact,
|
||||
}
|
||||
}
|
||||
|
||||
fn unsourced(text: &str) -> bool {
|
||||
let rep = claims::check(text, &canon());
|
||||
!rep.ok()
|
||||
&& rep
|
||||
.problems
|
||||
.iter()
|
||||
.all(|p| matches!(p, Problem::Unsourced { .. }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sourced_sentences_pass_and_refs_are_collected() {
|
||||
let c = canon();
|
||||
let rep = claims::check(
|
||||
"Tabula keeps your notes on your computer [tabula#F1]. A new note takes 1 click.[tabula#F7][tabula#F1] \
|
||||
Tabula 1.2 is out! [release#F1]",
|
||||
&c,
|
||||
);
|
||||
assert!(rep.ok(), "{:?}", rep.problems);
|
||||
assert_eq!(
|
||||
rep.refs,
|
||||
vec![r("release", 1), r("tabula", 1), r("tabula", 7)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_prices_platforms_and_features_need_refs() {
|
||||
for s in [
|
||||
"Tabula 1.2 is out.",
|
||||
"A new note takes 1 click.",
|
||||
"It costs $5.",
|
||||
"Only 5 € once.",
|
||||
"It costs five dollars.",
|
||||
"Pay once, own it forever.",
|
||||
"It runs on Windows.",
|
||||
"Now on Linux and macOS.",
|
||||
"Coming to Android and iOS.",
|
||||
"Install it as a PWA.",
|
||||
"Works in your browser.",
|
||||
"Use it on your phone.",
|
||||
"A desktop app.",
|
||||
"Runs on your home server.",
|
||||
"It syncs between your devices.",
|
||||
"Tabula keeps notes on your own computer.",
|
||||
"No account needed",
|
||||
"The fastest notes app ever made!",
|
||||
"Search is faster now.",
|
||||
"Tabula",
|
||||
"Tabula is free.",
|
||||
"100% private",
|
||||
"Your notes never leave your computer?",
|
||||
"Ten times faster",
|
||||
"I made this for myself.",
|
||||
"#tabula",
|
||||
] {
|
||||
assert!(unsourced(s), "{s:?} must be rejected as unsourced");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_sentences_pass_without_refs() {
|
||||
for s in [
|
||||
"Here's what's new.",
|
||||
"Here’s what’s new:",
|
||||
"What's new",
|
||||
"Try it today.",
|
||||
"Try it today! 🎉",
|
||||
"Try Tabula today.",
|
||||
"try it now",
|
||||
"Check it out.",
|
||||
"Learn more.",
|
||||
"Read more: https://aula.marek-novak.cz/tabula/",
|
||||
"Get it here: https://aula.marek-novak.cz/tabula/",
|
||||
"Thanks for reading.",
|
||||
"Let me know what you think.",
|
||||
"Feedback welcome.",
|
||||
"🎉",
|
||||
"---",
|
||||
"",
|
||||
" \n\n ",
|
||||
] {
|
||||
let rep = claims::check(s, &canon());
|
||||
assert!(rep.ok(), "{s:?} should pass: {:?}", rep.problems);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_phrase_with_anything_extra_needs_a_ref() {
|
||||
for s in [
|
||||
"Try it today on Windows.",
|
||||
"Try it today for $5.",
|
||||
"Try it today, it's free.",
|
||||
"Here's what's new in 1.2.",
|
||||
"Try the fastest notes app today.",
|
||||
"Try it 2day.",
|
||||
"#tabula #windows",
|
||||
] {
|
||||
assert!(unsourced(s), "{s:?} must be rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_sentence_is_checked_separately() {
|
||||
let c = canon();
|
||||
let rep = claims::check(
|
||||
"Tabula keeps notes local [tabula#F1]. It runs on Linux. Try it today.",
|
||||
&c,
|
||||
);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::Unsourced {
|
||||
sentence: "It runs on Linux.".into()
|
||||
}]
|
||||
);
|
||||
// Lines are sentences too.
|
||||
let rep = claims::check("Tabula 1.2 [release#F1]\nFaster search", &c);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::Unsourced {
|
||||
sentence: "Faster search".into()
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimals_and_urls_do_not_split_sentences() {
|
||||
let c = canon();
|
||||
assert_eq!(
|
||||
claims::sentences("Tabula 1.2 is out. Try it."),
|
||||
vec!["Tabula 1.2 is out.", "Try it."]
|
||||
);
|
||||
assert_eq!(
|
||||
claims::sentences("See https://aula.marek-novak.cz/tabula/?a=1. Thanks!"),
|
||||
vec!["See https://aula.marek-novak.cz/tabula/?a=1.", "Thanks!"]
|
||||
);
|
||||
assert_eq!(
|
||||
claims::sentences("A. [tabula#F1] B"),
|
||||
vec!["A. [tabula#F1]", "B"]
|
||||
);
|
||||
assert!(claims::check("Tabula 1.2 is out. [release#F1]", &c).ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_refs_are_rejected() {
|
||||
let c = canon();
|
||||
let rep = claims::check("Tabula keeps notes local. [tabula#F99]", &c);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::MissingFact { r: r("tabula", 99) }]
|
||||
);
|
||||
let rep = claims::check("Notes, done. [notapp#F1]", &c);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::UnknownApp { r: r("notapp", 1) }]
|
||||
);
|
||||
let rep = claims::check("It syncs everywhere. [tabula#F2]", &c);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::Unconfirmed { r: r("tabula", 2) }]
|
||||
);
|
||||
// A bad ref fails even on a plain sentence.
|
||||
let rep = claims::check("Try it today. [tabula#F99]", &c);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::MissingFact { r: r("tabula", 99) }]
|
||||
);
|
||||
// One good ref does not excuse a bad one.
|
||||
let rep = claims::check("Local notes. [tabula#F1][tabula#F2]", &c);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::Unconfirmed { r: r("tabula", 2) }]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_refs_are_rejected() {
|
||||
let c = canon();
|
||||
for bad in [
|
||||
"[F1]",
|
||||
"[tabula#f1]",
|
||||
"[Tabula#F1]",
|
||||
"[tabula #F1]",
|
||||
"[tabula#F01]",
|
||||
"[tabula#F0]",
|
||||
"[tabula#F10000]",
|
||||
"[tabula#1]",
|
||||
"[tabula#F1",
|
||||
"[#F1]",
|
||||
"[tabula#]",
|
||||
"[tabula_x#F1]",
|
||||
"tabula#F1",
|
||||
"[tabula#F1 ]",
|
||||
] {
|
||||
let text = format!("Tabula keeps notes on your own computer. {bad}");
|
||||
let rep = claims::check(&text, &c);
|
||||
assert!(
|
||||
rep.problems
|
||||
.iter()
|
||||
.any(|p| matches!(p, Problem::MalformedRef { .. })),
|
||||
"{bad:?}: {:?}",
|
||||
rep.problems
|
||||
);
|
||||
assert!(!rep.ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn urls_must_come_from_the_canon() {
|
||||
let c = canon();
|
||||
assert!(claims::check("Get it here: https://aula.marek-novak.cz/tabula/", &c).ok());
|
||||
assert!(claims::check("Get it here: https://aula.marek-novak.cz/tabula", &c).ok());
|
||||
assert!(claims::check("Read more: https://aula.marek-novak.cz/tabula/windows.", &c).ok());
|
||||
assert!(
|
||||
claims::check(
|
||||
"Read more: (https://aula.marek-novak.cz/tabula/windows)",
|
||||
&c
|
||||
)
|
||||
.ok()
|
||||
);
|
||||
for (text, url) in [
|
||||
(
|
||||
"Get it here: https://evil.example/tabula",
|
||||
"https://evil.example/tabula",
|
||||
),
|
||||
(
|
||||
"Get it here: http://aula.marek-novak.cz/tabula/",
|
||||
"http://aula.marek-novak.cz/tabula/",
|
||||
),
|
||||
(
|
||||
"Get it here: https://aula.marek-novak.cz/tabula/x",
|
||||
"https://aula.marek-novak.cz/tabula/x",
|
||||
),
|
||||
("Get it here: www.evil.example", "www.evil.example"),
|
||||
("Get it here: evil.com", "evil.com"),
|
||||
(
|
||||
"Get it here: evil.example/download",
|
||||
"evil.example/download",
|
||||
),
|
||||
("Get it here: ftp://evil.example", "ftp://evil.example"),
|
||||
] {
|
||||
let rep = claims::check(text, &c);
|
||||
assert!(
|
||||
rep.problems
|
||||
.contains(&Problem::UrlNotInCanon { url: url.into() }),
|
||||
"{text:?}: {:?}",
|
||||
rep.problems
|
||||
);
|
||||
}
|
||||
// A URL in a sourced sentence is still checked.
|
||||
let rep = claims::check(
|
||||
"It runs on Windows, see https://evil.example/ [tabula#F3]",
|
||||
&c,
|
||||
);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::UrlNotInCanon {
|
||||
url: "https://evil.example/".into()
|
||||
}]
|
||||
);
|
||||
// A bare form of an allowed URL is fine.
|
||||
assert!(claims::check("Get it here: aula.marek-novak.cz/tabula/", &c).ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_characters_are_rejected() {
|
||||
let c = canon();
|
||||
let rep = claims::check("Try it today.\u{202e}", &c);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::HiddenCharacter { codepoint: 0x202e }]
|
||||
);
|
||||
let rep = claims::check("Try it\0 today.", &c);
|
||||
assert!(
|
||||
rep.problems
|
||||
.contains(&Problem::HiddenCharacter { codepoint: 0 })
|
||||
);
|
||||
// CRLF and tabs are ordinary whitespace.
|
||||
assert!(claims::check("Try it today.\r\nThanks!\t", &c).ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasons_are_plain_english() {
|
||||
let c = canon();
|
||||
let rep = claims::check(
|
||||
"It runs on Linux. Local. [tabula#F99] Sync. [x#F1] Sync. [tabula#F2] [F3] https://evil.example/",
|
||||
&c,
|
||||
);
|
||||
let reasons: Vec<String> = rep.problems.iter().map(Problem::reason).collect();
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("It runs on Linux.") && s.contains("no source")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("tabula#F99") && s.contains("does not exist")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("unknown app") && s.contains("x")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("unconfirmed fact") && s.contains("tabula#F2")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert!(reasons.iter().any(|s| s.contains("[F3]")), "{reasons:?}");
|
||||
assert!(
|
||||
reasons
|
||||
.iter()
|
||||
.any(|s| s.contains("https://evil.example/") && s.contains("not in the canon")),
|
||||
"{reasons:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
Problem::HiddenCharacter { codepoint: 0x202e }.reason(),
|
||||
"Hidden or direction-changing character U+202E."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn problems_are_not_repeated() {
|
||||
let c = canon();
|
||||
let rep = claims::check("A. [tabula#F99] B. [tabula#F99]", &c);
|
||||
assert_eq!(
|
||||
rep.problems,
|
||||
vec![Problem::MissingFact { r: r("tabula", 99) }]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_refs_for_display() {
|
||||
assert_eq!(
|
||||
claims::strip_refs(
|
||||
"Tabula keeps notes local [tabula#F1]. One click.[tabula#F7][tabula#F1] Done [release#F1]"
|
||||
),
|
||||
"Tabula keeps notes local. One click. Done"
|
||||
);
|
||||
assert_eq!(
|
||||
claims::strip_refs("Tabula [tabula#F1] keeps notes."),
|
||||
"Tabula keeps notes."
|
||||
);
|
||||
assert_eq!(claims::strip_refs("A.[tabula#F1]B"), "A. B");
|
||||
assert_eq!(
|
||||
claims::strip_refs("Line one [tabula#F1]\nLine two"),
|
||||
"Line one\nLine two"
|
||||
);
|
||||
assert_eq!(
|
||||
claims::strip_refs("Keep [beta] and [Tabula#F1]."),
|
||||
"Keep [beta] and [Tabula#F1]."
|
||||
);
|
||||
assert_eq!(claims::strip_refs(""), "");
|
||||
assert_eq!(
|
||||
claims::strip_refs("Žluťoučký [tabula#F1]kůň"),
|
||||
"Žluťoučký kůň"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stripped_text_of_a_passing_text_has_no_refs() {
|
||||
let c = canon();
|
||||
let text = "Local notes [tabula#F1]. Try it today.";
|
||||
assert!(claims::check(text, &c).ok());
|
||||
let stripped = claims::strip_refs(text);
|
||||
assert!(claims::check(&stripped, &c).refs.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn states_fact_is_fail_closed() {
|
||||
let c = canon();
|
||||
assert!(!claims::states_fact("Try it today.", &c));
|
||||
assert!(!claims::states_fact("Here's what's new [tabula#F1].", &c));
|
||||
assert!(claims::states_fact("Tabula is great.", &c));
|
||||
assert!(claims::states_fact("It is what it is.", &c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_text_is_checked_without_trouble() {
|
||||
let c = canon();
|
||||
let text = "Local notes [tabula#F1]. ".repeat(2000);
|
||||
let rep = claims::check(&text, &c);
|
||||
assert!(rep.ok());
|
||||
assert_eq!(rep.refs, vec![r("tabula", 1)]);
|
||||
let line = "a".repeat(100_000);
|
||||
assert!(!claims::check(&line, &c).ok());
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use scaena_core::hooks::{self, Genome, HookError, Opening};
|
||||
|
||||
const HOOKS: &str = "# Hook templates
|
||||
|
||||
Prose is ignored.
|
||||
|
||||
- [H1] Tired of {pain}? {app} fixes it.
|
||||
- [H2] {number} reasons {audience} love {app}.
|
||||
- [H3] Try {feature} in {clicks}.
|
||||
- [H4] {app} now runs on {platform}.
|
||||
- [H5] Stop losing notes.
|
||||
";
|
||||
|
||||
fn values(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_templates_with_slots_in_order() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
assert_eq!(
|
||||
hs.iter().map(|h| h.id.as_str()).collect::<Vec<_>>(),
|
||||
vec!["H1", "H2", "H3", "H4", "H5"]
|
||||
);
|
||||
assert_eq!(hs[0].text, "Tired of {pain}? {app} fixes it.");
|
||||
assert_eq!(hs[0].slots, vec!["pain", "app"]);
|
||||
assert_eq!(hs[1].slots, vec!["number", "audience", "app"]);
|
||||
assert!(hs[4].slots.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slots_are_unique() {
|
||||
let hs = hooks::parse("- [H1] {app} and {app} and {feature}\n").unwrap();
|
||||
assert_eq!(hs[0].slots, vec!["app", "feature"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_fixed_slot_is_allowed() {
|
||||
let line = format!(
|
||||
"- [H1] {}\n",
|
||||
hooks::SLOTS.map(|s| format!("{{{s}}}")).join(" ")
|
||||
);
|
||||
let hs = hooks::parse(&line).unwrap();
|
||||
assert_eq!(hs[0].slots, hooks::SLOTS.to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_slots_are_errors() {
|
||||
for (bad, slot) in [
|
||||
("{price}", "price"),
|
||||
("{App}", "App"),
|
||||
("{}", ""),
|
||||
("{ app }", " app "),
|
||||
("{url}", "url"),
|
||||
] {
|
||||
let md = format!("# x\n- [H1] Hello {bad}\n");
|
||||
assert_eq!(
|
||||
hooks::parse(&md),
|
||||
Err(HookError::UnknownSlot {
|
||||
line: 2,
|
||||
slot: slot.into()
|
||||
}),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbalanced_braces_are_errors() {
|
||||
for bad in ["{app", "app}", "{{app}}", "{a{pp}", "}{"] {
|
||||
let md = format!("- [H1] Hi {bad}\n");
|
||||
assert_eq!(
|
||||
hooks::parse(&md),
|
||||
Err(HookError::UnbalancedBrace { line: 1 }),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_duplicate_and_empty_lines() {
|
||||
for bad in [
|
||||
"- [H] x",
|
||||
"- [Hx] x",
|
||||
"- [H1]x",
|
||||
"- [H1 x",
|
||||
"- [h1] x",
|
||||
" - [H1] x",
|
||||
"- [H1] x",
|
||||
] {
|
||||
assert_eq!(
|
||||
hooks::parse(&format!("{bad}\n")),
|
||||
Err(HookError::Malformed { line: 1 }),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
for bad in ["- [H0] x", "- [H01] x", "- [H10000] x"] {
|
||||
assert_eq!(
|
||||
hooks::parse(&format!("{bad}\n")),
|
||||
Err(HookError::IdOutOfRange { line: 1 }),
|
||||
"{bad:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1] a\n- [H1] b\n"),
|
||||
Err(HookError::Duplicate {
|
||||
line: 2,
|
||||
id: "H1".into()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1] \n"),
|
||||
Err(HookError::Empty { line: 1 })
|
||||
);
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1]\n"),
|
||||
Err(HookError::Malformed { line: 1 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input() {
|
||||
let big = format!("- [H1] {}\n", "a".repeat(hooks::MAX_FILE_BYTES));
|
||||
assert!(matches!(
|
||||
hooks::parse(&big),
|
||||
Err(HookError::TooLarge { .. })
|
||||
));
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1] a\u{202e}b\n"),
|
||||
Err(HookError::ForbiddenCharacter {
|
||||
line: 1,
|
||||
codepoint: 0x202e
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
hooks::parse("x\n- [H1] a\0b\n"),
|
||||
Err(HookError::ForbiddenCharacter {
|
||||
line: 2,
|
||||
codepoint: 0
|
||||
})
|
||||
);
|
||||
let crlf = HOOKS.replace('\n', "\r\n");
|
||||
assert_eq!(hooks::parse(&crlf).unwrap(), hooks::parse(HOOKS).unwrap());
|
||||
let bom = format!("\u{feff}{HOOKS}");
|
||||
assert_eq!(hooks::parse(&bom).unwrap(), hooks::parse(HOOKS).unwrap());
|
||||
assert_eq!(hooks::parse("").unwrap(), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_replaces_every_slot() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
let v = values(&[("pain", "lost notes"), ("app", "Tabula"), ("unused", "x")]);
|
||||
assert_eq!(
|
||||
hs[0].fill(&v).unwrap(),
|
||||
"Tired of lost notes? Tabula fixes it."
|
||||
);
|
||||
assert_eq!(hs[4].fill(&BTreeMap::new()).unwrap(), "Stop losing notes.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_missing_value_is_an_error() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
let v = values(&[("app", "Tabula")]);
|
||||
assert_eq!(
|
||||
hs[0].fill(&v),
|
||||
Err(HookError::MissingValue {
|
||||
slot: "pain".into()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_does_not_re_expand_braces_in_values() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
let v = values(&[("pain", "{app}"), ("app", "{pain} {x}")]);
|
||||
assert_eq!(
|
||||
hs[0].fill(&v).unwrap(),
|
||||
"Tired of {app}? {pain} {x} fixes it."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn genome_from_text() {
|
||||
let hs = hooks::parse(HOOKS).unwrap();
|
||||
assert_eq!(
|
||||
hs[0].genome,
|
||||
Genome {
|
||||
opening: Opening::Question,
|
||||
words: 6,
|
||||
has_number: false,
|
||||
lead_verb: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
hs[1].genome,
|
||||
Genome {
|
||||
opening: Opening::Number,
|
||||
words: 5,
|
||||
has_number: true,
|
||||
lead_verb: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
hs[2].genome,
|
||||
Genome {
|
||||
opening: Opening::Command,
|
||||
words: 4,
|
||||
has_number: false,
|
||||
lead_verb: Some("try".into())
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
hs[3].genome,
|
||||
Genome {
|
||||
opening: Opening::Statement,
|
||||
words: 5,
|
||||
has_number: false,
|
||||
lead_verb: None
|
||||
}
|
||||
);
|
||||
assert_eq!(hs[4].genome.opening, Opening::Command);
|
||||
assert_eq!(hs[4].genome.lead_verb.as_deref(), Some("stop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn genome_of_filled_text() {
|
||||
let g = Genome::of("3 clicks to a new note.");
|
||||
assert_eq!(g.opening, Opening::Number);
|
||||
assert!(g.has_number);
|
||||
assert_eq!(g.words, 6);
|
||||
let g = Genome::of("Why do notes need an account?");
|
||||
assert_eq!(g.opening, Opening::Question);
|
||||
let g = Genome::of("Your notes, on your computer. Ever wondered why?");
|
||||
assert_eq!(g.opening, Opening::Statement);
|
||||
let g = Genome::of("");
|
||||
assert_eq!(
|
||||
g,
|
||||
Genome {
|
||||
opening: Opening::Statement,
|
||||
words: 0,
|
||||
has_number: false,
|
||||
lead_verb: None
|
||||
}
|
||||
);
|
||||
let g = Genome::of("Meet Tabula 2.");
|
||||
assert_eq!(g.opening, Opening::Command);
|
||||
assert!(g.has_number);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lone_carriage_return_is_an_error() {
|
||||
assert_eq!(
|
||||
hooks::parse("- [H1] a\rb\n"),
|
||||
Err(HookError::LoneCarriageReturn { line: 1 })
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
// SPDX-License-Identifier: CPAL-1.0
|
||||
// Copyright (c) 2026 Marek Novák. Exhibit A notice: LICENSE at the repository root.
|
||||
|
||||
//! Property tests: the parsers and the checker never panic; valid files round-trip;
|
||||
//! adding a valid reference fixes an unsourced sentence.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use proptest::prelude::*;
|
||||
use scaena_core::canon::{self, Canon, Status};
|
||||
use scaena_core::claims::{self, Problem};
|
||||
use scaena_core::hooks;
|
||||
|
||||
/// Pieces that hit the interesting paths of the parsers and the checker.
|
||||
fn fragment() -> impl Strategy<Value = String> {
|
||||
prop_oneof![
|
||||
Just("---\n".to_string()),
|
||||
Just("id: tabula\n".to_string()),
|
||||
Just("name: Tabula\n".to_string()),
|
||||
Just("status: released\n".to_string()),
|
||||
Just("aula: https://aula.marek-novak.cz/tabula/\n".to_string()),
|
||||
Just("- [F".to_string()),
|
||||
Just("- [F1] ".to_string()),
|
||||
Just("- [H1] ".to_string()),
|
||||
Just("[tabula#F1]".to_string()),
|
||||
Just("[tabula#F2]".to_string()),
|
||||
Just("[tabula#F".to_string()),
|
||||
Just("[x#F99999999999999999999]".to_string()),
|
||||
Just("#F1".to_string()),
|
||||
Just(" (assumption)".to_string()),
|
||||
Just("{app}".to_string()),
|
||||
Just("{".to_string()),
|
||||
Just("}".to_string()),
|
||||
Just("https://".to_string()),
|
||||
Just("www.".to_string()),
|
||||
Just("evil.com/".to_string()),
|
||||
Just(". ".to_string()),
|
||||
Just("? ".to_string()),
|
||||
Just("\r\n".to_string()),
|
||||
Just("\r".to_string()),
|
||||
Just("\n".to_string()),
|
||||
Just("\u{feff}".to_string()),
|
||||
Just("\u{202e}".to_string()),
|
||||
Just("\0".to_string()),
|
||||
Just("ž".to_string()),
|
||||
Just("🎉".to_string()),
|
||||
Just("1.2".to_string()),
|
||||
Just("$".to_string()),
|
||||
Just("Windows".to_string()),
|
||||
Just("Try it today".to_string()),
|
||||
"[a-zA-Z0-9 ]{0,12}",
|
||||
any::<String>(),
|
||||
]
|
||||
}
|
||||
|
||||
fn soup() -> impl Strategy<Value = String> {
|
||||
prop::collection::vec(fragment(), 0..40).prop_map(|v| v.concat())
|
||||
}
|
||||
|
||||
fn canon() -> Canon {
|
||||
let mut c = Canon::new();
|
||||
let f = canon::parse(
|
||||
"tabula",
|
||||
"---\nid: tabula\nname: Tabula\none_liner: a\naudience: b\nprice: c\nclicks: d\nstatus: released\n\
|
||||
aula: https://aula.marek-novak.cz/tabula/\n---\n- [F1] Notes stay local.\n- [F2] Sync. (assumption)\n",
|
||||
)
|
||||
.unwrap();
|
||||
c.insert(f).unwrap();
|
||||
c
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct GenFact {
|
||||
id: u32,
|
||||
text: String,
|
||||
assumption: bool,
|
||||
}
|
||||
|
||||
fn fact_text() -> impl Strategy<Value = String> {
|
||||
"[A-Za-z0-9ěščřžýáíéůú,.'$€-][A-Za-z0-9ěščřžýáíéůú ,.'$€():/-]{0,60}[A-Za-z0-9.]"
|
||||
.prop_filter("no marker", |s| !s.to_lowercase().contains("(assumption)"))
|
||||
}
|
||||
|
||||
fn value() -> impl Strategy<Value = String> {
|
||||
"[A-Za-z0-9][A-Za-z0-9 ,.'()-]{0,40}[A-Za-z0-9.]"
|
||||
}
|
||||
|
||||
fn gen_file() -> impl Strategy<Value = (String, Vec<GenFact>, [String; 5], Status)> {
|
||||
let id = "[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?";
|
||||
let facts = prop::collection::btree_map(1u32..=9999, (fact_text(), any::<bool>()), 0..40)
|
||||
.prop_map(|m| {
|
||||
m.into_iter()
|
||||
.map(|(id, (text, assumption))| GenFact {
|
||||
id,
|
||||
text,
|
||||
assumption,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let status = prop_oneof![
|
||||
Just(Status::Released),
|
||||
Just(Status::Beta),
|
||||
Just(Status::Planned)
|
||||
];
|
||||
(
|
||||
id,
|
||||
facts,
|
||||
[value(), value(), value(), value(), value()],
|
||||
status,
|
||||
)
|
||||
}
|
||||
|
||||
fn render(id: &str, facts: &[GenFact], v: &[String; 5], status: Status, shuffle: u64) -> String {
|
||||
let st = match status {
|
||||
Status::Released => "released",
|
||||
Status::Beta => "beta",
|
||||
Status::Planned => "planned",
|
||||
};
|
||||
let mut s = format!(
|
||||
"---\nid: {id}\nname: {}\none_liner: {}\naudience: {}\nprice: (assumption) {}\nclicks: {}\nstatus: {st}\n---\n\n# Title\n",
|
||||
v[0], v[1], v[2], v[3], v[4]
|
||||
);
|
||||
// Facts in a scrambled order under several headings.
|
||||
let mut order: Vec<&GenFact> = facts.iter().collect();
|
||||
if !order.is_empty() {
|
||||
let k = (shuffle as usize) % order.len();
|
||||
order.rotate_left(k);
|
||||
}
|
||||
for (i, f) in order.iter().enumerate() {
|
||||
if i % 7 == 3 {
|
||||
s.push_str("\n## More\n\nSome prose.\n");
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"- [F{}] {}{}\n",
|
||||
f.id,
|
||||
f.text,
|
||||
if f.assumption { " (assumption)" } else { "" }
|
||||
));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
|
||||
|
||||
#[test]
|
||||
fn canon_parse_never_panics(text in soup(), stem in "[a-z-]{0,6}") {
|
||||
let _ = canon::parse(&stem, &text);
|
||||
let _ = canon::parse("tabula", &text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canon_parse_never_panics_on_any_string(text in any::<String>()) {
|
||||
let _ = canon::parse("tabula", &text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hooks_parse_never_panics(text in soup()) {
|
||||
if let Ok(hs) = hooks::parse(&text) {
|
||||
let v: BTreeMap<String, String> =
|
||||
hooks::SLOTS.iter().map(|s| (s.to_string(), "{app}".to_string())).collect();
|
||||
for h in hs {
|
||||
let filled = h.fill(&v).unwrap();
|
||||
let slot = format!("{{{}}}", "feature");
|
||||
prop_assert!(!filled.contains(&slot));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn genome_never_panics(text in soup()) {
|
||||
let _ = hooks::Genome::of(&text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_never_panics(text in soup()) {
|
||||
let c = canon();
|
||||
let rep = claims::check(&text, &c);
|
||||
let mut sorted = rep.refs.clone();
|
||||
sorted.sort();
|
||||
sorted.dedup();
|
||||
prop_assert_eq!(&rep.refs, &sorted);
|
||||
let _ = rep.problems.iter().map(Problem::reason).collect::<Vec<_>>();
|
||||
let _ = claims::strip_refs(&text);
|
||||
let _ = claims::sentences(&text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_never_panics_on_any_string(text in any::<String>()) {
|
||||
let _ = claims::check(&text, &canon());
|
||||
let _ = claims::strip_refs(&text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_files_round_trip((id, facts, v, status) in gen_file(), shuffle in any::<u64>()) {
|
||||
let text = render(&id, &facts, &v, status, shuffle);
|
||||
let f = canon::parse(&id, &text).unwrap();
|
||||
prop_assert_eq!(&f.id, &id);
|
||||
prop_assert_eq!(&f.front.name, &v[0]);
|
||||
prop_assert_eq!(&f.front.price, &format!("(assumption) {}", v[3]));
|
||||
prop_assert_eq!(f.front.status, status);
|
||||
let mut got: Vec<(u32, String, bool)> =
|
||||
f.facts.iter().map(|x| (x.id, x.text.clone(), x.assumption)).collect();
|
||||
got.sort();
|
||||
let want: Vec<(u32, String, bool)> =
|
||||
facts.iter().map(|x| (x.id, x.text.clone(), x.assumption)).collect();
|
||||
prop_assert_eq!(got, want);
|
||||
// CRLF gives the same file.
|
||||
let crlf = canon::parse(&id, &text.replace('\n', "\r\n")).unwrap();
|
||||
prop_assert_eq!(crlf, f);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adding_a_valid_ref_fixes_an_unsourced_sentence(
|
||||
words in prop::collection::vec("[A-Za-z0-9$€%'ěščřž]{1,10}", 1..12),
|
||||
punct in prop_oneof![Just(""), Just("."), Just("!"), Just("?")],
|
||||
after in any::<bool>(),
|
||||
) {
|
||||
let c = canon();
|
||||
let body = words.join(" ");
|
||||
let sentence = format!("{body}{punct}");
|
||||
let rep = claims::check(&sentence, &c);
|
||||
let only_unsourced = !rep.ok()
|
||||
&& rep.problems.iter().all(|p| matches!(p, Problem::Unsourced { .. }));
|
||||
if only_unsourced {
|
||||
let fixed = if after {
|
||||
format!("{body}{punct} [tabula#F1]")
|
||||
} else {
|
||||
format!("{body} [tabula#F1]{punct}")
|
||||
};
|
||||
let rep2 = claims::check(&fixed, &c);
|
||||
prop_assert!(rep2.ok(), "{:?} -> {:?}", fixed, rep2.problems);
|
||||
prop_assert_eq!(claims::strip_refs(&fixed), sentence);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ref_to_an_assumption_never_passes(words in prop::collection::vec("[A-Za-z]{1,8}", 1..8)) {
|
||||
let c = canon();
|
||||
let text = format!("{} [tabula#F2].", words.join(" "));
|
||||
prop_assert!(!claims::check(&text, &c).ok());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user