makeover_webview/build/drift/vocabulary_use.rs
1//! The vocabulary check: a hand-written rule that collides with a generated
2//! class, and generated classes no markup uses.
3
4use std::path::{Path, PathBuf};
5
6use super::{Source, drop_layers, frontend_css, layers_ordered_below_makeover, read, shown};
7use crate::Emit;
8use crate::build::rerun;
9use crate::css_lex::is_ident;
10
11/// A reviewed exception to [`Vocabulary`]: a collision the app has read and
12/// kept, with a note beside it saying why.
13///
14/// It expires when the collision does: an exception that no longer collides
15/// fails the check. It silences the class and element passes only; see
16/// [`Vocabulary`] for the cancel pass, which no exception covers.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Allow<'a> {
19 /// A hand-written rule on a generated class takes one of its properties.
20 Class {
21 /// The class, unprefixed as the stylesheet spells it.
22 class: &'a str,
23 /// The property both set.
24 property: &'a str,
25 },
26 /// A bare element rule takes a property the generated sheet sets on a class
27 /// that element carries.
28 Element {
29 /// The element the rule selects.
30 element: &'a str,
31 /// The generated class it reaches.
32 class: &'a str,
33 /// The property both set.
34 property: &'a str,
35 },
36}
37
38impl<'a> Allow<'a> {
39 /// See [`Allow::Class`].
40 pub const fn class(class: &'a str, property: &'a str) -> Self {
41 Self::Class { class, property }
42 }
43
44 /// See [`Allow::Element`].
45 pub const fn element(element: &'a str, class: &'a str, property: &'a str) -> Self {
46 Self::Element {
47 element,
48 class,
49 property,
50 }
51 }
52}
53
54/// Fail the build if a hand-written stylesheet takes a property the generated
55/// one already sets, on the same class or on an element that carries it.
56///
57/// The generated sheet sits in `@layer makeover`. App CSS beats it whatever
58/// the specificity, either by being unlayered or by sitting in a layer the
59/// app's order statement puts after `makeover`, so an app declaration for a
60/// property makeover already sets wins and the design system's value for that
61/// component stops applying.
62///
63/// Classes are compared by property, not by name: an app rule on a generated
64/// class that sets only properties the generated rule does not set passes.
65///
66/// # Three passes
67///
68/// - **Class pass.** An app rule whose subject names a generated class and
69/// sets a property the generated sheet sets on that class.
70/// [`Allow::class`] silences one `(class, property)` pair.
71/// - **Element pass.** A rule with no class in it, such as
72/// `button { color: var(--content) }`, setting a property the generated
73/// sheet sets on a class that element can carry
74/// (`crate::vocabulary::ELEMENT_CLASSES`). [`Allow::element`] silences one
75/// `(element, class, property)` triple. Not reported: a scoped rule
76/// (`.page button`), and a property the same sheet also names on that
77/// class from a rule of at least the element rule's specificity (a tie goes
78/// to the class rule). `.field` does not outrank `input[type="text"]`.
79/// - **Cancel pass.** An app rule on the bare class (`.button { color }`,
80/// no variant on its selector) setting a property the generated sheet sets
81/// on a variant arm of that class (`.button[data-tone="danger"]`,
82/// `.button:disabled`). From its later layer the bare rule beats every such
83/// arm. **No [`Allow`] silences this pass**, including an [`Allow::class`]
84/// for the same pair. The remedy is to restate each cancelled arm in the
85/// app's sheet on its own selector, after the bare rule (for example
86/// `.button[data-tone="danger"] { color: revert-layer }`), or to delete the
87/// declaration.
88///
89/// A rule inside a layer ordered before `makeover`, by [`Vocabulary::beneath`]
90/// or by the sheet's own `@layer` order statement, is not reported by any
91/// pass. A handoff with `revert-layer` on the arms makeover paints is not
92/// reported either: it is the usual remedy, a statement in the stylesheet
93/// rather than an entry in the build script.
94///
95/// # The exception list
96///
97/// An [`Allow`] names a pairing the app has reviewed and kept. An [`Allow`]
98/// that no longer collides fails the check.
99///
100/// ```no_run
101/// use makeover_webview::build::drift::{Allow, Vocabulary};
102///
103/// Vocabulary::in_frontend("frontend")
104/// .generated(&["layout.css"])
105/// // Reviewed: the card's shadow is the app's, on the hover arm only.
106/// .allow(Allow::class("card", "box-shadow"))
107/// .run(&makeover_webview::Emit::default());
108/// ```
109#[derive(Debug, Clone)]
110#[must_use = "a check does nothing until it is run"]
111pub struct Vocabulary<'a> {
112 source: Source,
113 generated: Vec<&'a str>,
114 upstream: Vec<&'a str>,
115 allowed: Vec<Allow<'a>>,
116 beneath: Vec<&'a str>,
117}
118
119impl<'a> Vocabulary<'a> {
120 /// Every `.css` under `frontend/css`, recursively.
121 pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
122 Self::from(Source::Frontend(frontend.as_ref().to_path_buf()))
123 }
124
125 /// A named list of stylesheets rather than a tree.
126 ///
127 /// For a frontend with no directory a scan can point at. A stylesheet not
128 /// on the list is not checked.
129 pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
130 Self::from(Source::files(paths))
131 }
132
133 fn from(source: Source) -> Self {
134 Self {
135 source,
136 generated: Vec::new(),
137 upstream: Vec::new(),
138 allowed: Vec::new(),
139 beneath: Vec::new(),
140 }
141 }
142
143 /// Sheets this crate writes, which are skipped. Relative to `frontend/css` for
144 /// [`in_frontend`](Self::in_frontend); matched against the end of each path
145 /// for [`files`](Self::files).
146 pub fn generated(mut self, names: &[&'a str]) -> Self {
147 self.generated.extend_from_slice(names);
148 self
149 }
150
151 /// The text of stylesheets that sit between makeover and the app and own
152 /// the classes they style as makeover owns its own.
153 ///
154 /// quasi-webview's `SCREEN_CSS` is one; the app that links both crates
155 /// hands it in. A hand-written sheet is checked against
156 /// makeover's sheet and every upstream sheet together. A file whose text
157 /// *is* an upstream sheet, the copy an app serves from its frontend, is
158 /// checked against makeover alone and never read as clashing with itself.
159 pub fn upstream(mut self, sheets: &[&'a str]) -> Self {
160 self.upstream.extend_from_slice(sheets);
161 self
162 }
163
164 /// Cascade layers the app orders before `makeover`, by name.
165 ///
166 /// A rule inside one loses to every generated rule whatever its selector,
167 /// so it cannot take a property from the design system and is not read.
168 /// For example a reset: `@layer reset, makeover, ...` with
169 /// `* { margin: 0; padding: 0 }` inside `@layer reset { }`. An order
170 /// stated only in the app's markup is not read by this check; naming the
171 /// layer here states it.
172 pub fn beneath(mut self, layers: &[&'a str]) -> Self {
173 self.beneath.extend_from_slice(layers);
174 self
175 }
176
177 /// A reviewed exception. See [`Allow`].
178 pub fn allow(mut self, allow: Allow<'a>) -> Self {
179 self.allowed.push(allow);
180 self
181 }
182
183 /// Several reviewed exceptions, for a list the app keeps as a `const`.
184 pub fn allowing(mut self, allows: impl IntoIterator<Item = Allow<'a>>) -> Self {
185 self.allowed.extend(allows);
186 self
187 }
188
189 /// Run the check against the stylesheet `opts` generates. Emits
190 /// `cargo::rerun-if-changed` for every file it read.
191 ///
192 /// # Panics
193 ///
194 /// If a directory or listed file cannot be read; if a bare-class rule
195 /// cancels a generated variant arm it does not restate (the cancel pass,
196 /// whatever the [`Allow`] list says); if any hand-written sheet takes a
197 /// generated property in the class or element pass without an [`Allow`];
198 /// or if an [`Allow`] no longer collides.
199 pub fn run(&self, opts: &Emit) {
200 let classes: Vec<(&str, &str)> = self
201 .allowed
202 .iter()
203 .filter_map(|allow| match *allow {
204 Allow::Class { class, property } => Some((class, property)),
205 Allow::Element { .. } => None,
206 })
207 .collect();
208 let elements: Vec<(&str, &str, &str)> = self
209 .allowed
210 .iter()
211 .filter_map(|allow| match *allow {
212 Allow::Element {
213 element,
214 class,
215 property,
216 } => Some((element, class, property)),
217 Allow::Class { .. } => None,
218 })
219 .collect();
220 match &self.source {
221 Source::Frontend(frontend) => {
222 let (css, files) = frontend_css(frontend);
223 let files: Vec<PathBuf> = files
224 .into_iter()
225 .filter(|p| !self.generated.contains(&shown(p, Some(&css)).as_str()))
226 .collect();
227 check_vocabulary_paths(
228 &files,
229 opts,
230 Some(frontend),
231 &self.upstream,
232 &self.beneath,
233 &classes,
234 &elements,
235 );
236 }
237 Source::Files(paths) => {
238 let files: Vec<PathBuf> = paths
239 .iter()
240 .filter(|p| !self.generated.iter().any(|name| p.ends_with(name)))
241 .cloned()
242 .collect();
243 check_vocabulary_paths(
244 &files,
245 opts,
246 None,
247 &self.upstream,
248 &self.beneath,
249 &classes,
250 &elements,
251 );
252 }
253 }
254 }
255}
256
257/// The check itself. `root`, when given, is stripped from reported paths.
258fn check_vocabulary_paths(
259 paths: &[PathBuf],
260 opts: &Emit,
261 root: Option<&Path>,
262 upstream: &[&str],
263 beneath: &[&str],
264 allowed: &[(&str, &str)],
265 allowed_elements: &[(&str, &str, &str)],
266) {
267 let sheet = crate::stylesheet(opts);
268 let makeover = crate::vocabulary::declarations_by_class(&sheet);
269 // What a hand-written sheet answers to: makeover's classes and every
270 // upstream sheet's, merged per class.
271 let mut owned = makeover.clone();
272 for sheet in upstream {
273 for (class, properties) in crate::vocabulary::declarations_by_class(sheet) {
274 owned.entry(class).or_default().extend(properties);
275 }
276 }
277 // The same two views one level down: per arm rather than per class, so a
278 // variant the generated sheet styles is not folded into its base.
279 let makeover_variants = crate::vocabulary::variants_by_class(&sheet);
280 let mut owned_variants = makeover_variants.clone();
281 for sheet in upstream {
282 for (class, arms) in crate::vocabulary::variants_by_class(sheet) {
283 let entry = owned_variants.entry(class).or_default();
284 for (arm, properties) in arms {
285 entry.entry(arm).or_default().extend(properties);
286 }
287 }
288 }
289 let mut cancels: Vec<String> = Vec::new();
290 let mut clashes: Vec<String> = Vec::new();
291 let mut seen: Vec<(String, String)> = Vec::new();
292 let mut element_clashes: Vec<String> = Vec::new();
293 let mut element_seen: Vec<(String, String, String)> = Vec::new();
294
295 for path in paths {
296 rerun(path);
297 let raw = read(path);
298 let name = shown(path, root);
299 // An upstream sheet served from the frontend answers to makeover alone:
300 // measured against itself every declaration in it would clash.
301 let (generated, variants) = if upstream.contains(&raw.as_str()) {
302 (&makeover, &makeover_variants)
303 } else {
304 (&owned, &owned_variants)
305 };
306 // A layer ordered before `makeover` cannot beat it, so its rules are
307 // not read. See `Vocabulary::beneath`.
308 let raw = drop_layers(&raw, beneath);
309 // A layer this sheet's own statement orders below makeover cannot beat
310 // it either, so no pass reports a rule there. Its pairs still count as
311 // seen, so an `Allow` naming one is not stale.
312 let own_below = layers_ordered_below_makeover(&raw);
313 let own_below: Vec<&str> = own_below.iter().map(String::as_str).collect();
314 let above = drop_layers(&raw, &own_below);
315 // Read the app's sheet the same way the crate reads its own, or the two
316 // sides are not comparable.
317 let local = crate::vocabulary::declarations_by_class(&raw);
318 let local_above = crate::vocabulary::declarations_by_class(&above);
319 for (class, properties) in &local {
320 let Some(theirs) = generated.get(class) else {
321 continue;
322 };
323 for property in properties.intersection(theirs) {
324 seen.push((class.clone(), property.clone()));
325 let wins = local_above
326 .get(class)
327 .is_some_and(|above| above.contains(property));
328 if !wins || allowed.contains(&(class.as_str(), property.as_str())) {
329 continue;
330 }
331 clashes.push(format!(" {name} .{class} {{ {property} }}"));
332 }
333 }
334
335 // The layer pass. A rule on the bare class reaches every element
336 // carrying it, and from a later layer it beats every variant the design
337 // system styles on that class, whatever their specificity. The class
338 // pass cannot see this once the pair is reviewed: an `Allow` for
339 // (button, color) written for one arm licensed cancelling
340 // `[data-tone="danger"]` too, and goingson's destructive buttons lost
341 // their tone that way. So no `Allow` silences it. The remedy is always
342 // available: restate the variant, on its own arm, in the app's sheet.
343 let bare = crate::vocabulary::bare_declarations(&above);
344 let restated = crate::vocabulary::mentions_by_arm(&raw);
345 for (class, properties) in &bare {
346 let Some(arms) = variants.get(class) else {
347 continue;
348 };
349 for property in properties {
350 let lost: Vec<&str> = arms
351 .iter()
352 .filter(|(arm, theirs)| {
353 theirs.contains(property)
354 && !restated
355 .get(arm.as_str())
356 .is_some_and(|mentioned| mentioned.contains(property))
357 })
358 .map(|(arm, _)| arm.as_str())
359 .collect();
360 if lost.is_empty() {
361 continue;
362 }
363 cancels.push(format!(
364 " {name} .{class} {{ {property} }} cancels {}",
365 lost.iter()
366 .map(|arm| format!("{arm} {{ {property} }}"))
367 .collect::<Vec<_>>()
368 .join(", ")
369 ));
370 }
371 }
372
373 // The second pass: a rule carrying no class at all, which the first one
374 // cannot see. What the app says about the class itself settles the
375 // pair, but only from a rule that outranks the element rule. Both are
376 // the app's and both are in the same layer, so this one contest is
377 // decided by specificity. `.field` does not beat `input[type="text"]`.
378 let mentioned = crate::vocabulary::mentions_by_class(&raw);
379 let by_element = crate::vocabulary::declarations_by_element(&raw);
380 let by_element_above = crate::vocabulary::declarations_by_element(&above);
381 for (element, properties) in &by_element {
382 for class in crate::vocabulary::classes_for_element(element, opts) {
383 let Some(theirs) = generated.get(&class) else {
384 continue;
385 };
386 for (property, rank) in properties {
387 if !theirs.contains(property) {
388 continue;
389 }
390 // A tie goes to the class rule: at equal specificity the
391 // later rule wins, and a remedy is written after the rule
392 // it remedies.
393 let spoken_for = mentioned
394 .get(&class)
395 .and_then(|properties| properties.get(property))
396 .is_some_and(|theirs| theirs >= rank);
397 if spoken_for {
398 continue;
399 }
400 element_seen.push((element.clone(), class.clone(), property.clone()));
401 let wins = by_element_above
402 .get(element)
403 .is_some_and(|above| above.contains_key(property));
404 if !wins
405 || allowed_elements.contains(&(
406 element.as_str(),
407 class.as_str(),
408 property.as_str(),
409 ))
410 {
411 continue;
412 }
413 element_clashes.push(format!(
414 " {name} {element} {{ {property} }} beats .{class} {{ {property} }}"
415 ));
416 }
417 }
418 }
419 }
420
421 assert!(
422 cancels.is_empty(),
423 "{} hand-written rule(s) on a bare generated class set a property the \
424 design system varies on that class by state, tone or context. The app \
425 sheet sits in a later cascade layer than @layer makeover, and layers \
426 resolve before specificity, so each of these beats every variant named \
427 beside it, everywhere:\n{}\n\nDelete the declaration, or restate each \
428 cancelled variant in the app's sheet on its own arm, after the bare rule \
429 (`color: revert-layer` hands the design system's value back). That is \
430 the remedy the cascade allows; an allowed-list entry does not cover \
431 this, because the reviewed pair is the class and the variants are \
432 what it silently takes.",
433 cancels.len(),
434 cancels.join("\n")
435 );
436
437 assert!(
438 clashes.is_empty(),
439 "{} hand-written declaration(s) take a property the generated stylesheet, \
440 or an upstream sheet named to this check, already sets on the same \
441 class. App CSS wins over @layer makeover, whether by a later layer or \
442 by being unlayered, so each of these wins over the design system \
443 silently:\n{}\n\nDelete the declaration, or, if \
444 it is a deliberate pairing on a different selector arm, add \
445 (class, property) to this check's allowed list and say why beside it. \
446 Count the consumers before deciding a divergence is worth keeping.",
447 clashes.len(),
448 clashes.join("\n")
449 );
450
451 assert!(
452 element_clashes.is_empty(),
453 "{} hand-written element rule(s) take a property the generated \
454 stylesheet sets on a class that element carries. App CSS wins over \
455 @layer makeover, whether by a later layer or by being unlayered, so a \
456 described component rendered on one of these elements loses the \
457 design system's version of that property silently, which can draw a \
458 destructive act like an ordinary one:\n{}\n\nHand the \
459 property back on the arms makeover paints \
460 (`.{{class}}:disabled {{ color: revert-layer }}`), scope the element \
461 rule so it stops reaching described markup, or add \
462 (element, class, property) to this check's allowed-elements list and \
463 say why beside it.",
464 element_clashes.len(),
465 element_clashes.join("\n")
466 );
467
468 assert_no_stale("allowed", allowed, |(class, property)| {
469 seen.contains(&((*class).to_string(), (*property).to_string()))
470 });
471 assert_no_stale(
472 "allowed-elements",
473 allowed_elements,
474 |(element, class, property)| {
475 element_seen.contains(&(
476 (*element).to_string(),
477 (*class).to_string(),
478 (*property).to_string(),
479 ))
480 },
481 );
482}
483
484/// Fail on an allowed-list entry that no longer collides with anything.
485fn assert_no_stale<T: std::fmt::Debug>(list: &str, entries: &[T], used: impl Fn(&T) -> bool) {
486 let stale: Vec<&T> = entries.iter().filter(|entry| !used(entry)).collect();
487 assert!(
488 stale.is_empty(),
489 "the {list} list declares {stale:?}, which no longer collides with \
490 anything. Delete the entries: an exception nobody is using is where the \
491 next real collision lands and reads as company."
492 );
493}
494
495/// Whether `haystack` names `class` whole, rather than as part of a longer
496/// name: `min-1` must not be read as used because `min-16` is, and `row` must
497/// not be read as used because `row-flex` or `flex-row` is.
498pub(super) fn haystack_names(haystack: &str, class: &str) -> bool {
499 haystack.match_indices(class).any(|(at, found)| {
500 haystack[..at]
501 .chars()
502 .next_back()
503 .is_none_or(|c| !is_ident(c))
504 && haystack[at + found.len()..]
505 .chars()
506 .next()
507 .is_none_or(|c| !is_ident(c))
508 })
509}
510
511/// Every maximal run of identifier characters in `haystack`: the names
512/// [`haystack_names`] would find whole, gathered in one pass.
513pub(super) fn haystack_words(haystack: &str) -> std::collections::HashSet<&str> {
514 haystack
515 .split(|c: char| !is_ident(c))
516 .filter(|word| !word.is_empty())
517 .collect()
518}
519
520/// Warn when the generated vocabulary has grown dead, and fail when it grows
521/// deader than the recorded high-water mark.
522///
523/// A generated class is unused when its name appears whole in none of the
524/// `markup` files. The check is one-sided: more unused classes than
525/// `high_water` fails; fewer warns and asks for `high_water` to be lowered.
526///
527/// `markup` is every file that can carry a class: templates, `.js`, `.html`,
528/// and any Rust that writes markup. A class is counted as used if its name
529/// appears whole in any of them, however that file builds its class strings.
530///
531/// # Panics
532///
533/// If a listed file cannot be read, or if more classes are unused than
534/// `high_water`.
535pub fn check_vocabulary_use<P: AsRef<Path>>(markup: &[P], opts: &Emit, high_water: usize) {
536 let generated = crate::vocabulary::names(opts);
537 let mut haystack = String::new();
538 for path in markup {
539 let path = path.as_ref();
540 rerun(path);
541 haystack.push_str(&read(path));
542 haystack.push('\n');
543 }
544
545 // A ladder is one piece of vocabulary, not one per rung. A column carries
546 // whichever `min-N` rung its floor lands on and a table whichever `short-N`
547 // `stacks-N`, `tiles-N` and `drop-*-N` rungs its floors need, so no site names every rung and counting each
548 // would seal the dead count at the ladder's length. A ladder is used if any
549 // rung is, and counted once if none is.
550 const LADDERS: &[&str] = &[
551 "min-",
552 "short-",
553 "stacks-",
554 "tiles-",
555 "drop-optional-",
556 "drop-secondary-",
557 ];
558 let rung_of = |class: &str| -> Option<&'static str> {
559 let name = class.strip_prefix(opts.class_prefix)?;
560 LADDERS.iter().copied().find(|ladder| {
561 name.strip_prefix(ladder)
562 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
563 })
564 };
565 // One pass over the markup, then a lookup per class. A class is an
566 // identifier, so the set holds it exactly when the haystack names it whole;
567 // anything else is searched for.
568 let words = haystack_words(&haystack);
569 let named = |class: &str| {
570 if class.chars().all(is_ident) {
571 words.contains(class)
572 } else {
573 haystack_names(&haystack, class)
574 }
575 };
576 let mut unused: Vec<String> = generated
577 .iter()
578 .filter(|class| rung_of(class).is_none() && !named(class))
579 .cloned()
580 .collect();
581 for ladder in LADDERS {
582 let rungs: Vec<&String> = generated
583 .iter()
584 .filter(|class| rung_of(class) == Some(ladder))
585 .collect();
586 if !rungs.is_empty() && !rungs.iter().any(|class| named(class)) {
587 unused.push(format!("{}{ladder}N", opts.class_prefix));
588 }
589 }
590
591 assert!(
592 unused.len() <= high_water,
593 "{} of {} generated classes are emitted by no markup, above the recorded {}. \
594 The vocabulary grew or the markup stopped using it:\n{}",
595 unused.len(),
596 generated.len(),
597 high_water,
598 unused
599 .iter()
600 .map(|c| format!(" .{c}"))
601 .collect::<Vec<_>>()
602 .join("\n")
603 );
604
605 if unused.len() < high_water {
606 println!(
607 "cargo::warning=dead makeover vocabulary is down to {} from a sealed {}; \
608 lower the seal so it cannot grow back",
609 unused.len(),
610 high_water
611 );
612 }
613}