Files
VoelinClient/crates/voelin-gpui/src/theme/slint_parity.rs
T
faumarayandClaude Sonnet 5.5 5c94b15820 voelin-gpui: the parity test notices a second brush or string in theme.slint
The test compared the brush and string declarations of theme.slint by name
only (one backdrop, one font-family and the mode string), so a second brush or
string token in the Slint file passed unseen while docs/ui.md said a token on
one side only fails the test. It now asserts the brush declarations are
exactly {backdrop} and the strings exactly {mode, font-family}, and a test
adds a brush and a string to a copy of the file (a mutant) and checks both are
named: red with the previous rule ("backdrop-soft goes unnoticed"), green
with this one.

A Rust-only second brush or string is still not seen (tokens.rs has one
gradient and one family that the test cannot enumerate); docs/ui.md says so
instead of promising it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:29:02 +03:00

319 lines
11 KiB
Rust

//! `crates/voelin-ui/ui/theme.slint` against `tokens.rs`: the Slint file is
//! read and every token in it is compared with the Rust value of the same
//! name, light and dark and at four text sizes; a token on one side only, a
//! value that differs, or a declaration of a kind this test does not know
//! (or a second brush or string, of which it knows `backdrop`, `mode` and
//! `font-family`) fails it. While both front ends live, a token changed in
//! one place and not the other is caught here.
use std::collections::{BTreeMap, BTreeSet};
use super::tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
const SLINT: &str = include_str!("../../../voelin-ui/ui/theme.slint");
/// What `theme.slint` declares: the kind and the expression of each property
/// of the `Theme` global, in file order.
fn declarations() -> Vec<(String, String, String)> {
declarations_of(SLINT)
}
/// The same for the text of a `.slint` file (the tests below also read
/// altered copies of `theme.slint`).
fn declarations_of(source: &str) -> Vec<(String, String, String)> {
let without_comments: String = source
.lines()
.map(|line| line.split("//").next().unwrap_or(""))
.collect::<Vec<_>>()
.join("\n");
let body = without_comments.split_once("export global Theme {").expect("the Theme global").1;
let mut found = Vec::new();
for statement in body.split(';') {
let statement = statement.trim();
let Some(rest) = ["in-out property", "out property", "in property"]
.iter()
.find_map(|prefix| statement.strip_prefix(prefix))
else {
continue;
};
let (kind, rest) =
rest.trim().strip_prefix('<').expect("<kind>").split_once('>').expect("<kind>");
let (name, expr) = rest.trim().split_once(':').expect("name: expression");
// One line, single spaces: `backdrop` is written over several.
let expr = expr.split_whitespace().collect::<Vec<_>>().join(" ");
found.push((name.trim().to_owned(), kind.trim().to_owned(), expr));
}
found
}
/// `#rgb`-style literal as `Rgba`.
fn colour(text: &str) -> Rgba {
let hex = text.trim().strip_prefix('#').unwrap_or_else(|| panic!("a colour, not {text:?}"));
let value = u32::from_str_radix(hex, 16).unwrap_or_else(|_| panic!("hex digits in {text:?}"));
match hex.len() {
6 => Rgba(value << 8 | 0xff),
8 => Rgba(value),
_ => panic!("#rrggbb or #rrggbbaa, not {text:?}"),
}
}
/// Split `dark ? A : B` at its top-level `?` and `:`; `A` for a plain `A`.
fn by_mode(expr: &str) -> (String, String) {
let Some(rest) = expr.strip_prefix("dark ?") else {
return (expr.to_owned(), expr.to_owned());
};
let mut depth = 0;
for (i, c) in rest.char_indices() {
match c {
'(' => depth += 1,
')' => depth -= 1,
':' if depth == 0 => {
return (rest[..i].trim().to_owned(), rest[i + 1..].trim().to_owned());
}
_ => {}
}
}
panic!("no `:` in {expr:?}");
}
/// The arithmetic of the length tokens: numbers with a unit, other tokens,
/// `*`, `+`, `max(a, b)` and parentheses.
struct Eval<'a> {
tokens: Vec<String>,
at: usize,
env: &'a BTreeMap<String, String>,
scale: f64,
}
impl<'a> Eval<'a> {
fn run(expr: &str, env: &'a BTreeMap<String, String>, scale: f64) -> f64 {
let mut tokens = Vec::new();
let mut word = String::new();
for c in expr.chars() {
if c.is_alphanumeric() || matches!(c, '-' | '.' | '%') {
word.push(c);
} else {
if !word.is_empty() {
tokens.push(std::mem::take(&mut word));
}
if !c.is_whitespace() {
tokens.push(c.to_string());
}
}
}
if !word.is_empty() {
tokens.push(word);
}
let mut eval = Eval { tokens, at: 0, env, scale };
let value = eval.sum();
assert_eq!(eval.at, eval.tokens.len(), "all of {expr:?} is read");
value
}
fn peek(&self) -> Option<&str> {
self.tokens.get(self.at).map(String::as_str)
}
fn take(&mut self) -> String {
self.at += 1;
self.tokens[self.at - 1].clone()
}
fn sum(&mut self) -> f64 {
let mut value = self.product();
while self.peek() == Some("+") {
self.take();
value += self.product();
}
value
}
fn product(&mut self) -> f64 {
let mut value = self.factor();
while self.peek() == Some("*") {
self.take();
value *= self.factor();
}
value
}
fn factor(&mut self) -> f64 {
let token = self.take();
if token == "(" {
let value = self.sum();
assert_eq!(self.take(), ")");
return value;
}
if token == "max" {
assert_eq!(self.take(), "(");
let a = self.sum();
assert_eq!(self.take(), ",");
let b = self.sum();
assert_eq!(self.take(), ")");
return a.max(b);
}
if token == "font-scale" {
return self.scale;
}
if token.starts_with(|c: char| c.is_ascii_digit()) {
let number: String =
token.chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();
return number.parse().unwrap_or_else(|_| panic!("a number in {token:?}"));
}
let expr =
self.env.get(&token).unwrap_or_else(|| panic!("a token named {token:?}")).clone();
Eval::run(&expr, self.env, self.scale)
}
}
/// The names `theme.slint` declares that are state, not tokens: the mode and
/// what it resolves to, and the text size factor (the factor is a parameter
/// of [`Metrics`]).
const STATE: [&str; 4] = ["mode", "system-dark", "dark", "font-scale"];
#[test]
fn every_colour_is_the_same_in_both_files() {
let slint: Vec<(String, String, String)> =
declarations().into_iter().filter(|(_, kind, _)| kind == "color").collect();
assert!(slint.len() > 40, "the colours were found: {}", slint.len());
let dark: BTreeMap<_, _> = Palette::DARK.entries().into_iter().collect();
let light: BTreeMap<_, _> = Palette::LIGHT.entries().into_iter().collect();
let mut names = BTreeSet::new();
for (name, _, expr) in &slint {
let (d, l) = by_mode(expr);
assert_eq!(dark.get(name.as_str()), Some(&colour(&d)), "{name} (dark)");
assert_eq!(light.get(name.as_str()), Some(&colour(&l)), "{name} (light)");
names.insert(name.as_str());
}
let ours: BTreeSet<&str> = dark.keys().copied().collect();
assert_eq!(ours, names, "colours in tokens.rs and not in theme.slint, or the other way");
}
#[test]
fn every_length_weight_and_duration_is_the_same_in_both_files() {
let all = declarations();
let env: BTreeMap<String, String> =
all.iter().map(|(name, _, expr)| (name.clone(), expr.clone())).collect();
let numeric: Vec<&(String, String, String)> = all
.iter()
.filter(|(name, kind, _)| {
matches!(kind.as_str(), "length" | "int" | "duration")
&& !STATE.contains(&name.as_str())
})
.collect();
assert!(numeric.len() > 30, "the numbers were found: {}", numeric.len());
for scale in [1.0_f32, 1.25, 0.8, 2.0] {
let ours: BTreeMap<&str, f64> = Metrics::new(scale).entries().into_iter().collect();
let mut names = BTreeSet::new();
for (name, _, expr) in &numeric {
let slint = Eval::run(expr, &env, f64::from(scale));
let ours = *ours.get(name.as_str()).unwrap_or_else(|| panic!("{name} is in tokens.rs"));
assert!(
(slint - ours).abs() < 1e-3,
"{name} at {scale}: theme.slint {slint}, tokens.rs {ours}"
);
names.insert(name.as_str());
}
let rust: BTreeSet<&str> = ours.keys().copied().collect();
assert_eq!(rust, names, "numbers in tokens.rs and not in theme.slint, or the other way");
}
}
#[test]
fn the_backdrop_and_the_font_are_the_same_in_both_files() {
let all = declarations();
let get = |name: &str| {
all.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name}")).2.clone()
};
let gradient = |text: &str| -> Backdrop {
let inner = text
.trim()
.strip_prefix("@linear-gradient(")
.and_then(|t| t.strip_suffix(')'))
.unwrap_or_else(|| panic!("a linear gradient, not {text:?}"));
let mut parts = inner.split(',').map(str::trim);
let angle: f32 = parts.next().unwrap().trim_end_matches("deg").parse().unwrap();
let stops: Vec<(Rgba, f32)> = parts
.map(|stop| {
let (colour_text, position) = stop.split_once(' ').unwrap();
let percent: f32 = position.trim().trim_end_matches('%').parse().unwrap();
(colour(colour_text), percent / 100.0)
})
.collect();
Backdrop { angle, stops: stops.try_into().expect("three stops") }
};
let (dark, light) = by_mode(&get("backdrop"));
assert_eq!(gradient(&dark), Backdrop::DARK);
assert_eq!(gradient(&light), Backdrop::LIGHT);
assert_eq!(get("font-family"), format!("\"{FONT_FAMILY}\""));
}
/// What the declarations hold that no comparison above covers, one sentence
/// each; empty when there is none: a kind of declaration this test does not
/// know, a brush other than `backdrop` or a string other than `mode` and
/// `font-family` (the two comparisons of those go by name, so a second one
/// would pass unseen), a state name that is no longer declared.
fn unknown_to_this_test(declared: &[(String, String, String)]) -> Vec<String> {
let mut problems = Vec::new();
let kinds: BTreeSet<&str> = declared
.iter()
.filter(|(name, _, _)| !STATE.contains(&name.as_str()))
.map(|(_, kind, _)| kind.as_str())
.collect();
let known = BTreeSet::from(["color", "brush", "length", "int", "duration", "string"]);
if kinds != known {
problems.push(format!("kinds of declaration {kinds:?}, this test knows {known:?}"));
}
for (kind, expected) in [("brush", &["backdrop"][..]), ("string", &["mode", "font-family"])] {
let found: BTreeSet<&str> = declared
.iter()
.filter(|(_, declared_kind, _)| declared_kind == kind)
.map(|(name, _, _)| name.as_str())
.collect();
let expected: BTreeSet<&str> = expected.iter().copied().collect();
for name in found.symmetric_difference(&expected) {
problems.push(format!(
"{name}: the <{kind}> declarations are {found:?}, this test compares {expected:?}"
));
}
}
for name in STATE {
if !declared.iter().any(|(declared, _, _)| declared == name) {
problems.push(format!("{name} is not declared"));
}
}
problems
}
#[test]
fn the_file_declares_nothing_this_test_does_not_know() {
let problems = unknown_to_this_test(&declarations());
assert!(problems.is_empty(), "{problems:#?}");
}
/// `theme.slint` with one more declaration in its `Theme` global.
fn with_declaration(declaration: &str) -> String {
let opening = "export global Theme {";
assert!(SLINT.contains(opening));
SLINT.replacen(opening, &format!("{opening}\n {declaration}"), 1)
}
#[test]
fn a_second_brush_or_string_is_not_passed_unseen() {
// Mutants of the Slint file: a token on one side only.
for (declaration, name) in [
("out property <brush> backdrop-soft: #123456;", "backdrop-soft"),
("out property <string> font-mono: \"Mono\";", "font-mono"),
] {
let mutant = declarations_of(&with_declaration(declaration));
assert!(mutant.iter().any(|(declared, _, _)| declared == name), "the mutant has {name}");
let problems = unknown_to_this_test(&mutant);
assert!(
problems.iter().any(|problem| problem.contains(name)),
"{name} goes unnoticed: {problems:#?}"
);
}
// And the file as it is has neither.
assert_eq!(unknown_to_this_test(&declarations()), Vec::<String>::new());
}