use std::path::{Path, PathBuf};
use super::{Source, drop_layers, frontend_css, layers_ordered_below_makeover, read, shown};
use crate::Emit;
use crate::build::rerun;
use crate::css_lex::is_ident;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Allow<'a> {
Class {
class: &'a str,
property: &'a str,
},
Element {
element: &'a str,
class: &'a str,
property: &'a str,
},
}
impl<'a> Allow<'a> {
pub const fn class(class: &'a str, property: &'a str) -> Self {
Self::Class { class, property }
}
pub const fn element(element: &'a str, class: &'a str, property: &'a str) -> Self {
Self::Element {
element,
class,
property,
}
}
}
#[derive(Debug, Clone)]
#[must_use = "a check does nothing until it is run"]
pub struct Vocabulary<'a> {
source: Source,
generated: Vec<&'a str>,
upstream: Vec<&'a str>,
allowed: Vec<Allow<'a>>,
beneath: Vec<&'a str>,
}
impl<'a> Vocabulary<'a> {
pub fn in_frontend(frontend: impl AsRef<Path>) -> Self {
Self::from(Source::Frontend(frontend.as_ref().to_path_buf()))
}
pub fn files<P: AsRef<Path>>(paths: &[P]) -> Self {
Self::from(Source::files(paths))
}
fn from(source: Source) -> Self {
Self {
source,
generated: Vec::new(),
upstream: Vec::new(),
allowed: Vec::new(),
beneath: Vec::new(),
}
}
pub fn generated(mut self, names: &[&'a str]) -> Self {
self.generated.extend_from_slice(names);
self
}
pub fn upstream(mut self, sheets: &[&'a str]) -> Self {
self.upstream.extend_from_slice(sheets);
self
}
pub fn beneath(mut self, layers: &[&'a str]) -> Self {
self.beneath.extend_from_slice(layers);
self
}
pub fn allow(mut self, allow: Allow<'a>) -> Self {
self.allowed.push(allow);
self
}
pub fn allowing(mut self, allows: impl IntoIterator<Item = Allow<'a>>) -> Self {
self.allowed.extend(allows);
self
}
pub fn run(&self, opts: &Emit) {
let classes: Vec<(&str, &str)> = self
.allowed
.iter()
.filter_map(|allow| match *allow {
Allow::Class { class, property } => Some((class, property)),
Allow::Element { .. } => None,
})
.collect();
let elements: Vec<(&str, &str, &str)> = self
.allowed
.iter()
.filter_map(|allow| match *allow {
Allow::Element {
element,
class,
property,
} => Some((element, class, property)),
Allow::Class { .. } => None,
})
.collect();
match &self.source {
Source::Frontend(frontend) => {
let (css, files) = frontend_css(frontend);
let files: Vec<PathBuf> = files
.into_iter()
.filter(|p| !self.generated.contains(&shown(p, Some(&css)).as_str()))
.collect();
check_vocabulary_paths(
&files,
opts,
Some(frontend),
&self.upstream,
&self.beneath,
&classes,
&elements,
);
}
Source::Files(paths) => {
let files: Vec<PathBuf> = paths
.iter()
.filter(|p| !self.generated.iter().any(|name| p.ends_with(name)))
.cloned()
.collect();
check_vocabulary_paths(
&files,
opts,
None,
&self.upstream,
&self.beneath,
&classes,
&elements,
);
}
}
}
}
fn check_vocabulary_paths(
paths: &[PathBuf],
opts: &Emit,
root: Option<&Path>,
upstream: &[&str],
beneath: &[&str],
allowed: &[(&str, &str)],
allowed_elements: &[(&str, &str, &str)],
) {
let sheet = crate::stylesheet(opts);
let makeover = crate::vocabulary::declarations_by_class(&sheet);
let mut owned = makeover.clone();
for sheet in upstream {
for (class, properties) in crate::vocabulary::declarations_by_class(sheet) {
owned.entry(class).or_default().extend(properties);
}
}
let makeover_variants = crate::vocabulary::variants_by_class(&sheet);
let mut owned_variants = makeover_variants.clone();
for sheet in upstream {
for (class, arms) in crate::vocabulary::variants_by_class(sheet) {
let entry = owned_variants.entry(class).or_default();
for (arm, properties) in arms {
entry.entry(arm).or_default().extend(properties);
}
}
}
let mut cancels: Vec<String> = Vec::new();
let mut clashes: Vec<String> = Vec::new();
let mut seen: Vec<(String, String)> = Vec::new();
let mut element_clashes: Vec<String> = Vec::new();
let mut element_seen: Vec<(String, String, String)> = Vec::new();
for path in paths {
rerun(path);
let raw = read(path);
let name = shown(path, root);
let (generated, variants) = if upstream.contains(&raw.as_str()) {
(&makeover, &makeover_variants)
} else {
(&owned, &owned_variants)
};
let raw = drop_layers(&raw, beneath);
let own_below = layers_ordered_below_makeover(&raw);
let own_below: Vec<&str> = own_below.iter().map(String::as_str).collect();
let above = drop_layers(&raw, &own_below);
let local = crate::vocabulary::declarations_by_class(&raw);
let local_above = crate::vocabulary::declarations_by_class(&above);
for (class, properties) in &local {
let Some(theirs) = generated.get(class) else {
continue;
};
for property in properties.intersection(theirs) {
seen.push((class.clone(), property.clone()));
let wins = local_above
.get(class)
.is_some_and(|above| above.contains(property));
if !wins || allowed.contains(&(class.as_str(), property.as_str())) {
continue;
}
clashes.push(format!(" {name} .{class} {{ {property} }}"));
}
}
let bare = crate::vocabulary::bare_declarations(&above);
let restated = crate::vocabulary::mentions_by_arm(&raw);
for (class, properties) in &bare {
let Some(arms) = variants.get(class) else {
continue;
};
for property in properties {
let lost: Vec<&str> = arms
.iter()
.filter(|(arm, theirs)| {
theirs.contains(property)
&& !restated
.get(arm.as_str())
.is_some_and(|mentioned| mentioned.contains(property))
})
.map(|(arm, _)| arm.as_str())
.collect();
if lost.is_empty() {
continue;
}
cancels.push(format!(
" {name} .{class} {{ {property} }} cancels {}",
lost.iter()
.map(|arm| format!("{arm} {{ {property} }}"))
.collect::<Vec<_>>()
.join(", ")
));
}
}
let mentioned = crate::vocabulary::mentions_by_class(&raw);
let by_element = crate::vocabulary::declarations_by_element(&raw);
let by_element_above = crate::vocabulary::declarations_by_element(&above);
for (element, properties) in &by_element {
for class in crate::vocabulary::classes_for_element(element, opts) {
let Some(theirs) = generated.get(&class) else {
continue;
};
for (property, rank) in properties {
if !theirs.contains(property) {
continue;
}
let spoken_for = mentioned
.get(&class)
.and_then(|properties| properties.get(property))
.is_some_and(|theirs| theirs >= rank);
if spoken_for {
continue;
}
element_seen.push((element.clone(), class.clone(), property.clone()));
let wins = by_element_above
.get(element)
.is_some_and(|above| above.contains_key(property));
if !wins
|| allowed_elements.contains(&(
element.as_str(),
class.as_str(),
property.as_str(),
))
{
continue;
}
element_clashes.push(format!(
" {name} {element} {{ {property} }} beats .{class} {{ {property} }}"
));
}
}
}
}
assert!(
cancels.is_empty(),
"{} hand-written rule(s) on a bare generated class set a property the \
design system varies on that class by state, tone or context. The app \
sheet sits in a later cascade layer than @layer makeover, and layers \
resolve before specificity, so each of these beats every variant named \
beside it, everywhere:\n{}\n\nDelete the declaration, or restate each \
cancelled variant in the app's sheet on its own arm, after the bare rule \
(`color: revert-layer` hands the design system's value back). That is \
the remedy the cascade allows; an allowed-list entry does not cover \
this, because the reviewed pair is the class and the variants are \
what it silently takes.",
cancels.len(),
cancels.join("\n")
);
assert!(
clashes.is_empty(),
"{} hand-written declaration(s) take a property the generated stylesheet, \
or an upstream sheet named to this check, already sets on the same \
class. App CSS wins over @layer makeover, whether by a later layer or \
by being unlayered, so each of these wins over the design system \
silently:\n{}\n\nDelete the declaration, or, if \
it is a deliberate pairing on a different selector arm, add \
(class, property) to this check's allowed list and say why beside it. \
Count the consumers before deciding a divergence is worth keeping.",
clashes.len(),
clashes.join("\n")
);
assert!(
element_clashes.is_empty(),
"{} hand-written element rule(s) take a property the generated \
stylesheet sets on a class that element carries. App CSS wins over \
@layer makeover, whether by a later layer or by being unlayered, so a \
described component rendered on one of these elements loses the \
design system's version of that property silently, which can draw a \
destructive act like an ordinary one:\n{}\n\nHand the \
property back on the arms makeover paints \
(`.{{class}}:disabled {{ color: revert-layer }}`), scope the element \
rule so it stops reaching described markup, or add \
(element, class, property) to this check's allowed-elements list and \
say why beside it.",
element_clashes.len(),
element_clashes.join("\n")
);
assert_no_stale("allowed", allowed, |(class, property)| {
seen.contains(&((*class).to_string(), (*property).to_string()))
});
assert_no_stale(
"allowed-elements",
allowed_elements,
|(element, class, property)| {
element_seen.contains(&(
(*element).to_string(),
(*class).to_string(),
(*property).to_string(),
))
},
);
}
fn assert_no_stale<T: std::fmt::Debug>(list: &str, entries: &[T], used: impl Fn(&T) -> bool) {
let stale: Vec<&T> = entries.iter().filter(|entry| !used(entry)).collect();
assert!(
stale.is_empty(),
"the {list} list declares {stale:?}, which no longer collides with \
anything. Delete the entries: an exception nobody is using is where the \
next real collision lands and reads as company."
);
}
pub(super) fn haystack_names(haystack: &str, class: &str) -> bool {
haystack.match_indices(class).any(|(at, found)| {
haystack[..at]
.chars()
.next_back()
.is_none_or(|c| !is_ident(c))
&& haystack[at + found.len()..]
.chars()
.next()
.is_none_or(|c| !is_ident(c))
})
}
pub(super) fn haystack_words(haystack: &str) -> std::collections::HashSet<&str> {
haystack
.split(|c: char| !is_ident(c))
.filter(|word| !word.is_empty())
.collect()
}
pub fn check_vocabulary_use<P: AsRef<Path>>(markup: &[P], opts: &Emit, high_water: usize) {
let generated = crate::vocabulary::names(opts);
let mut haystack = String::new();
for path in markup {
let path = path.as_ref();
rerun(path);
haystack.push_str(&read(path));
haystack.push('\n');
}
const LADDERS: &[&str] = &[
"min-",
"short-",
"stacks-",
"tiles-",
"drop-optional-",
"drop-secondary-",
];
let rung_of = |class: &str| -> Option<&'static str> {
let name = class.strip_prefix(opts.class_prefix)?;
LADDERS.iter().copied().find(|ladder| {
name.strip_prefix(ladder)
.is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
})
};
let words = haystack_words(&haystack);
let named = |class: &str| {
if class.chars().all(is_ident) {
words.contains(class)
} else {
haystack_names(&haystack, class)
}
};
let mut unused: Vec<String> = generated
.iter()
.filter(|class| rung_of(class).is_none() && !named(class))
.cloned()
.collect();
for ladder in LADDERS {
let rungs: Vec<&String> = generated
.iter()
.filter(|class| rung_of(class) == Some(ladder))
.collect();
if !rungs.is_empty() && !rungs.iter().any(|class| named(class)) {
unused.push(format!("{}{ladder}N", opts.class_prefix));
}
}
assert!(
unused.len() <= high_water,
"{} of {} generated classes are emitted by no markup, above the recorded {}. \
The vocabulary grew or the markup stopped using it:\n{}",
unused.len(),
generated.len(),
high_water,
unused
.iter()
.map(|c| format!(" .{c}"))
.collect::<Vec<_>>()
.join("\n")
);
if unused.len() < high_water {
println!(
"cargo::warning=dead makeover vocabulary is down to {} from a sealed {}; \
lower the seal so it cannot grow back",
unused.len(),
high_water
);
}
}