diff --git a/.changepacks/changepack_log_numbering_order.json b/.changepacks/changepack_log_numbering_order.json new file mode 100644 index 000000000..50b941573 --- /dev/null +++ b/.changepacks/changepack_log_numbering_order.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-wasm/package.json": "Patch", + "bindings/devup-ui-binding/package.json": "Patch" + }, + "note": "Let extraction run on several threads while class names stay numbered as one by one in order would: the first name a file hands out waits for every earlier file to finish naming, and a file that names anything after its turn passed is extracted again in order. Add a core batch extractor that runs sources on worker threads, asks the module resolver on the calling thread once per import and importer, and falls back to one by one under atom hoisting. No behaviour change for existing callers: the generated CSS, class names and exported maps are byte-identical.", + "date": "2026-12-05T00:00:00.000Z" +} diff --git a/libs/binding/src/batch.rs b/libs/binding/src/batch.rs new file mode 100644 index 000000000..4549cbb80 --- /dev/null +++ b/libs/binding/src/batch.rs @@ -0,0 +1,452 @@ +//! Extract many sources at once, as extracting them one by one in their order +//! would, but on several threads. +//! +//! Worker threads take the sources in order and extract them at once, each +//! numbering classes and files only in its turn (see +//! [`css::numbering_order`]), so every number comes out as one by one. The +//! calling thread, the only one that may run the host's module resolver, +//! answers the workers' resolver requests, then commits the outputs to the +//! stylesheet in source order. An extraction that numbered out of its turn +//! sends the whole batch back to extracting one by one. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, Sender, SyncSender, channel, sync_channel}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; +use std::thread::{Builder, Scope, ScopedJoinHandle}; + +use css::numbering_order::{Snapshot, Turn}; +use extractor::{ + ExtractOption, ExtractOutput, ResolvedModule, extract, extract_with_modules, + extract_without_source_map, +}; + +use crate::output::{CssOptions, Output, SourceMapMode}; +use crate::resolver_state::{ResolverState, resolved_module}; + +/// Worker stacks: the build-time evaluator recurses deeply. +const STACK_SIZE: usize = 16 * 1024 * 1024; + +/// Past this many workers the resolver on the calling thread is the bottleneck. +const MAX_DEFAULT_THREADS: usize = 8; + +/// Workers to use when the caller names none: the cores, at most eight. +#[must_use] +pub fn default_threads() -> usize { + std::thread::available_parallelism() + .map_or(1, std::num::NonZero::get) + .min(MAX_DEFAULT_THREADS) +} + +/// One source of a batch: its name, its code and the directory its CSS goes to. +pub struct BatchSource { + pub filename: String, + pub code: String, + pub css_dir: String, +} + +/// What every source of a batch is extracted with. +pub struct BatchOptions { + /// The extraction options; each source's `css_dir` replaces theirs. + pub option: ExtractOption, + pub source_map: SourceMapMode, + /// Import the main stylesheet from emitted file CSS. + pub import_main_css_in_css: bool, + /// Worker threads to extract on; below two, the batch extracts one by one. + pub threads: usize, +} + +/// What the host's module resolver answered. +#[derive(Clone)] +pub enum HostAnswer { + /// The module the import resolves to. + Module { path: String, code: String }, + /// The resolver's own failure, reported at the import. + Failed(String), + /// The import names no module the resolver knows. + Unresolved, + /// Calling the resolver failed; the extraction fails with this error. + Transport(String), +} + +/// Asks the host to resolve an import, on the thread that holds it. +pub type Ask = Rc HostAnswer>; + +/// The outputs of a batch, in source order. Outputs keep no CSS: committing +/// the next source changes the sheet, and a batch serializes none. +pub struct Batch { + pub outputs: Vec>, + /// Whether the outputs come from worker threads: not when the batch ran + /// one by one from the start, or again after a source numbered out of turn. + pub parallel: bool, +} + +/// What a worker tells the calling thread. +enum Event { + /// Resolve an import and send the answer back. + Resolve { + specifier: String, + importer: String, + reply: SyncSender, + }, + /// A source is extracted, numbering only in its turn or not. + Extracted { + index: usize, + result: Result, + in_order: bool, + }, +} + +/// Ask the calling thread to resolve an import and wait for its answer. +fn ask_remote(events: &Sender, specifier: &str, importer: &str) -> HostAnswer { + let (reply, answer) = sync_channel(1); + let event = Event::Resolve { + specifier: specifier.to_string(), + importer: importer.to_string(), + reply, + }; + let dropped = || HostAnswer::Transport("module resolver request was dropped".to_string()); + events.send(event).map_or_else( + |_| dropped(), + |()| answer.recv().unwrap_or_else(|_| dropped()), + ) +} + +/// The host's answers in this batch, by import and importer. The resolver +/// answers alike while the batch runs, so workers ask for each import once. +type Answers = Mutex>; + +/// The host's answer for an import, asked of the calling thread only once. +fn ask_once( + answers: &Answers, + events: &Sender, + specifier: &str, + importer: &str, +) -> HostAnswer { + let key = (specifier.to_string(), importer.to_string()); + let known = answers + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(&key) + .cloned(); + known.unwrap_or_else(|| { + let answer = ask_remote(events, specifier, importer); + // A transport failure is no answer + if !matches!(answer, HostAnswer::Transport(_)) { + answers + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(key, answer.clone()); + } + answer + }) +} + +/// Resolve an import through `ask`, keeping the diagnostics a resolver failure +/// reports and the first transport failure, as a single extraction does. +fn resolve( + (diagnostics, transport): (&RefCell, &RefCell>), + ask: &Ask, + specifier: &str, + importer: &str, +) -> Option { + let request = diagnostics.borrow().request(specifier, importer)?; + let cause = match ask(specifier, importer) { + HostAnswer::Module { path, code } => match resolved_module(path, code) { + Ok(module) => { + diagnostics.borrow_mut().cache(&module, &request); + return Some(module); + } + Err(cause) => cause, + }, + HostAnswer::Failed(cause) => cause, + HostAnswer::Unresolved => return None, + HostAnswer::Transport(error) => { + transport.borrow_mut().get_or_insert(error); + return None; + } + }; + diagnostics.borrow_mut().record(&request, &cause); + None +} + +/// Extract one source, its imports resolved through `ask` when given. +fn extract_source( + source: &BatchSource, + options: &BatchOptions, + ask: Option<&Ask>, +) -> Result { + let option = ExtractOption { + css_dir: source.css_dir.clone(), + ..options.option.clone() + }; + let (filename, code) = (source.filename.as_str(), source.code.as_str()); + let source_map = matches!(options.source_map, SourceMapMode::Generate); + let Some(ask) = ask else { + let extracted = if source_map { + extract(filename, code, option) + } else { + extract_without_source_map(filename, code, option) + }; + return extracted.map_err(|error| error.to_string()); + }; + let diagnostics = Rc::new(RefCell::new(ResolverState::new(filename, code))); + let transport = Rc::new(RefCell::new(None)); + let resolver = { + let (diagnostics, transport, ask) = ( + Rc::clone(&diagnostics), + Rc::clone(&transport), + Rc::clone(ask), + ); + move |specifier: &str, importer: &str| { + resolve((&diagnostics, &transport), &ask, specifier, importer) + } + }; + let extracted = extract_with_modules(filename, code, option, source_map, &resolver); + if let Some(error) = transport.take() { + return Err(error); + } + diagnostics.borrow().check()?; + extracted.map_err(|error| error.to_string()) +} + +/// Whose turn it is to number: the first source that has not passed it on. +struct Turns { + passed: Mutex<(usize, Vec)>, + changed: Condvar, +} + +impl Turns { + fn new(sources: usize) -> Self { + Self { + passed: Mutex::new((0, vec![false; sources])), + changed: Condvar::new(), + } + } + + fn lock(&self) -> MutexGuard<'_, (usize, Vec)> { + self.passed.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Wait until every source before `index` passed its turn on. + fn wait(&self, index: usize) { + drop( + self.changed + .wait_while(self.lock(), |passed| passed.0 < index) + .unwrap_or_else(PoisonError::into_inner), + ); + } + + /// Pass the turn of `index` on. + fn pass(&self, index: usize) { + let mut passed = self.lock(); + passed.1[index] = true; + while passed.1.get(passed.0) == Some(&true) { + passed.0 += 1; + } + drop(passed); + self.changed.notify_all(); + } + + /// The turn of source `index`, for the thread that extracts it. + fn turn(self: &Arc, index: usize) -> Turn { + let (waiting, passing) = (Arc::clone(self), Arc::clone(self)); + Turn::begin(move || waiting.wait(index), move || passing.pass(index)) + } +} + +/// Extract the sources a worker takes, in order, until none are left. +fn work( + sources: &[BatchSource], + options: &BatchOptions, + (next, turns, answers): (&AtomicUsize, &Arc, &Arc), + (events, resolves): (Sender, bool), +) { + let ask = resolves.then(|| { + let (events, answers) = (events.clone(), Arc::clone(answers)); + Rc::new(move |specifier: &str, importer: &str| { + ask_once(&answers, &events, specifier, importer) + }) as Ask + }); + loop { + let index = next.fetch_add(1, Ordering::Relaxed); + let Some(source) = sources.get(index) else { + break; + }; + let turn = turns.turn(index); + let result = extract_source(source, options, ask.as_ref()); + let in_order = turn.finish(); + // The calling thread receives until every worker is done + let _ = events.send(Event::Extracted { + index, + result, + in_order, + }); + } +} + +/// Answer the workers' requests until every worker is done, returning what +/// they extracted in source order and whether all of it numbered in turn. +fn serve( + events: &Receiver, + ask: Option<&Ask>, + sources: usize, +) -> (Vec>>, bool) { + let mut extracted: Vec>> = + (0..sources).map(|_| None).collect(); + let mut in_order = true; + for event in events { + match event { + Event::Resolve { + specifier, + importer, + reply, + } => { + let answer = ask.map_or(HostAnswer::Unresolved, |ask| ask(&specifier, &importer)); + // A worker waits for every answer it asks for + let _ = reply.send(answer); + } + Event::Extracted { + index, + result, + in_order: ordered, + } => { + extracted[index] = Some(result); + in_order &= ordered; + } + } + } + (extracted, in_order) +} + +/// Start up to `threads` workers. +fn spawn<'scope>( + scope: &'scope Scope<'scope, '_>, + threads: usize, + events: &Sender, + run: &'scope (dyn Fn(Sender) + Sync), +) -> Vec> { + (0..threads) + .filter_map(|_| { + let events = events.clone(); + Builder::new() + .stack_size(STACK_SIZE) + .spawn_scoped(scope, move || run(events)) + .ok() + }) + .collect() +} + +/// Every source extracted on worker threads, or `None` when one numbered out +/// of its turn or no worker extracted it. +fn extract_parallel( + sources: &[BatchSource], + options: &BatchOptions, + ask: Option<&Ask>, +) -> Option>> { + let next = AtomicUsize::new(0); + let turns = Arc::new(Turns::new(sources.len())); + let answers = Arc::new(Answers::default()); + let resolves = ask.is_some(); + let run = |events: Sender| { + work( + sources, + options, + (&next, &turns, &answers), + (events, resolves), + ); + }; + let (extracted, in_order) = std::thread::scope(|scope| { + // Dropped here should serving unwind, so no worker waits for an answer + let (sender, events) = channel(); + let workers = spawn(scope, options.threads.min(sources.len()), &sender, &run); + drop(sender); + let served = serve(&events, ask, sources.len()); + for worker in workers { + // A worker that panicked left its source unextracted + let _ = worker.join(); + } + served + }); + in_order + .then(|| extracted.into_iter().collect::>>()) + .flatten() +} + +/// Commit an extracted source to the stylesheet, keeping no CSS. +fn commit( + source: &BatchSource, + extracted: Result, + css: CssOptions, +) -> Result { + extracted.map(|output| Output { + css: None, + ..Output::new(output, source.filename.clone(), css) + }) +} + +/// Extract the sources one after another on this thread, committing each +/// before extracting the next: committing a source can name classes too. +fn extract_sequential( + sources: &[BatchSource], + options: &BatchOptions, + ask: Option<&Ask>, + css: CssOptions, +) -> Vec> { + sources + .iter() + .map(|source| commit(source, extract_source(source, options, ask), css)) + .collect() +} + +/// What the workers extracted and that they did, or when they could not, the +/// numbering they changed put back as `snapshot` holds it and every source +/// extracted one by one. +fn or_one_by_one( + parallel: Option>, + snapshot: Snapshot, + one_by_one: impl FnOnce() -> Vec, +) -> (Vec, bool) { + parallel.map_or_else( + || { + snapshot.restore(); + (one_by_one(), false) + }, + |parallel| (parallel, true), + ) +} + +/// Extract `sources` as extracting them one by one in their order would, +/// resolving imports through `ask` on this thread. +pub fn extract_batch(sources: &[BatchSource], options: &BatchOptions, ask: Option<&Ask>) -> Batch { + let css = CssOptions { + single_css: options.option.single_css, + import_main_css: options.import_main_css_in_css, + }; + // Hoisted atoms are named from a plan the first extraction freezes + if options.threads < 2 || css::atom_hoist::atom_hoist_threshold().is_some() { + return Batch { + outputs: extract_sequential(sources, options, ask, css), + parallel: false, + }; + } + let snapshot = Snapshot::take(); + // Each worker named what committing its source names in its turn, so the + // sources are committed in order once all are extracted + let parallel = extract_parallel(sources, options, ask).map(|extracted| { + sources + .iter() + .zip(extracted) + .map(|(source, extracted)| commit(source, extracted, css)) + .collect() + }); + let (outputs, parallel) = or_one_by_one(parallel, snapshot, || { + extract_sequential(sources, options, ask, css) + }); + Batch { outputs, parallel } +} + +#[cfg(test)] +mod tests; diff --git a/libs/binding/src/batch/tests.rs b/libs/binding/src/batch/tests.rs new file mode 100644 index 000000000..b152b054c --- /dev/null +++ b/libs/binding/src/batch/tests.rs @@ -0,0 +1,37 @@ +use serial_test::serial; + +use super::*; + +#[test] +#[serial] +fn workers_that_could_not_extract_leave_the_numbering_to_one_by_one() { + crate::reset_state_internal(|| {}); + let _ = css::keyframes_to_keyframes_name("first", None); + let snapshot = Snapshot::take(); + let numbered = css::class_map::get_class_map(); + let _ = css::keyframes_to_keyframes_name("second", None); + + let extracted = or_one_by_one(None, snapshot, || vec![css::class_map::get_class_map()]); + + assert_eq!(extracted, (vec![numbered], false)); +} + +#[test] +#[serial] +fn what_workers_extracted_stands() { + crate::reset_state_internal(|| {}); + let snapshot = Snapshot::take(); + let _ = css::keyframes_to_keyframes_name("kept", None); + + let extracted = or_one_by_one(Some(vec![1]), snapshot, || vec![2]); + + assert_eq!(extracted, (vec![1], true)); + assert_eq!(css::class_map::get_class_map()[""].len(), 1); +} + +#[test] +fn the_default_workers_are_the_cores_at_most_eight() { + let threads = default_threads(); + + assert!((1..=MAX_DEFAULT_THREADS).contains(&threads)); +} diff --git a/libs/binding/src/lib.rs b/libs/binding/src/lib.rs index d1bc2549a..3cc8e36a3 100644 --- a/libs/binding/src/lib.rs +++ b/libs/binding/src/lib.rs @@ -1,5 +1,6 @@ //! Host-neutral binding orchestration; JavaScript values belong to the host adapter. +mod batch; mod css_cache; mod lazy_css; mod native_theme; @@ -8,6 +9,9 @@ mod reservation; mod resolver_state; pub mod session; +pub use batch::{ + Ask, Batch, BatchOptions, BatchSource, HostAnswer, default_threads, extract_batch, +}; pub use css::debug::{is_debug, set_debug}; pub use css::license_banner::{is_license_banner, set_license_banner}; pub use css::slot_reservation::unreserved_slot_count as get_unreserved_class_slot_count; diff --git a/libs/binding/tests/batch.rs b/libs/binding/tests/batch.rs new file mode 100644 index 000000000..48b0ba3cd --- /dev/null +++ b/libs/binding/tests/batch.rs @@ -0,0 +1,568 @@ +//! A batch extracts its sources as extracting them one by one in order does, +//! however many threads it runs on. + +use std::cell::RefCell; +use std::fmt::Write as _; +use std::rc::Rc; + +use devup_ui_binding_core::{ + Ask, BatchOptions, BatchSource, ExtractionMode, HostAnswer, Output, ResolverState, + SourceMapMode, code_extract, export_class_map_internal, export_file_map_internal, + export_sheet_internal, extract_batch, get_css, import_canonical_map_internal, + reset_state_internal, seed_file_map, set_atom_hoist, +}; +use extractor::ExtractOption; +use serial_test::serial; + +const COMPONENTS: usize = 48; +const ROUTES: usize = 6; +const BARREL: &str = "src/components/index.ts"; + +/// A large app: components behind one barrel, collapsed into its bucket, read +/// by routes, all reading shared tokens; and sources that fail, that import +/// nothing to extract, or that the file numbering does not know. +fn app() -> Vec<(String, String)> { + let mut files = vec![( + "src/tokens.ts".to_string(), + "export const tones = { a: '#123456', b: '#abcdef', c: 'red' } as const\nexport const space = { s: 4, m: 8 } as const\n".to_string(), + )]; + for index in 0..COMPONENTS { + files.push(( + format!("src/components/C{index:03}.tsx"), + format!( + "import {{ Box, css, Flex, keyframes, styled, Text }} from '@devup-ui/react' +import {{ space, tones }} from '../tokens' + +const Frame = styled('section', {{ borderRadius: {radius}, p: space.m }}) +const spin = keyframes({{ from: {{ opacity: 0 }}, to: {{ opacity: {opacity} }} }}) + +export function C{index:03}({{ active }}: {{ active?: boolean }}) {{ + return ( + + + + item {index} + + + + ) +}} +", + radius = 4 + index % 8, + gap = 2 + index % 12, + opacity = format!("0.{}", index % 9 + 1), + tone = ["a", "b", "c"][index % 3], + size = 12 + index % 10, + ), + )); + } + files.push(( + BARREL.to_string(), + (0..COMPONENTS).fold(String::new(), |mut barrel, index| { + let _ = writeln!(barrel, "export {{ C{index:03} }} from './C{index:03}'"); + barrel + }), + )); + for route in 0..ROUTES { + let names: Vec = (0..COMPONENTS / ROUTES) + .map(|offset| { + format!( + "C{:03}", + (route * COMPONENTS / ROUTES + offset) % COMPONENTS + ) + }) + .collect(); + files.push(( + format!("src/app/r{route}/page.tsx"), + format!( + "import {{ Box }} from '@devup-ui/react'\nimport {{ {} }} from '@/components'\n\nexport default function Page() {{\n return {}\n}}\n", + names.join(", "), + names.iter().fold(String::new(), |mut tags, name| { + let _ = write!(tags, "<{name} />"); + tags + }), + ), + )); + } + files.extend([ + ( + "src/app/broken.tsx".to_string(), + "import { Box } from '@devup-ui/react'\nexport const view = \n".to_string(), + ), + ( + "src/unnumbered.tsx".to_string(), + "import { Box } from '@devup-ui/react'\nexport const view = \n".to_string(), + ), + ]); + files +} + +/// Resolve an import of the app as the bundler does. +fn module(app: &[(String, String)], specifier: &str, importer: &str) -> Option<(String, String)> { + let base = if let Some(rest) = specifier.strip_prefix("@/") { + format!("src/{rest}") + } else if specifier.starts_with('.') { + let mut parts: Vec<&str> = importer.split('/').collect(); + parts.pop(); + for part in specifier.split('/') { + match part { + "." => {} + ".." => { + parts.pop(); + } + part => parts.push(part), + } + } + parts.join("/") + } else { + return None; + }; + ["", ".ts", ".tsx", "/index.ts"] + .iter() + .find_map(|extension| { + let path = format!("{base}{extension}"); + app.iter() + .find(|(filename, _)| *filename == path) + .map(|(filename, code)| (filename.clone(), code.clone())) + }) +} + +fn option() -> ExtractOption { + ExtractOption { + package: "@devup-ui/react".to_string(), + ..ExtractOption::default() + } +} + +fn css_dir(filename: &str) -> String { + format!("./{}df", "../".repeat(filename.matches('/').count())) +} + +/// The engine as the build sets it up: the components collapse into their +/// barrel's bucket, one shared file goes to the global sheet, and every file +/// but one is numbered in path order. +fn set_up(app: &[(String, String)]) { + reset_state_internal(|| {}); + import_canonical_map_internal( + app.iter() + .filter(|(filename, _)| filename.starts_with("src/components/C")) + .map(|(filename, _)| (filename.clone(), BARREL.to_string())) + .chain([( + "src/shared.tsx".to_string(), + css::file_map::GLOBAL_BUCKET.to_string(), + )]) + .collect(), + ); + let mut numbered: Vec = app + .iter() + .map(|(filename, _)| filename.clone()) + .filter(|filename| filename != "src/unnumbered.tsx") + .collect(); + numbered.sort(); + seed_file_map(&numbered); +} + +/// A source's code, map, CSS file, base-style flag and dependencies. +type Extracted = (String, Option, Option, bool, Vec); + +/// Everything a source's output and the engine state tell. +#[derive(Debug, PartialEq, Eq)] +struct Outcome { + outputs: Vec>, + sheet: String, + classes: String, + files: String, + css: Vec, +} + +fn outcome(outputs: Vec>) -> Outcome { + Outcome { + outputs: outputs + .into_iter() + .map(|output| { + output.map(|output| { + ( + output.code, + output.map, + output.css_file, + output.updated_base_style, + output.dependencies, + ) + }) + }) + .collect(), + sheet: export_sheet_internal().unwrap_or_default(), + classes: export_class_map_internal().unwrap_or_default(), + files: export_file_map_internal().unwrap_or_default(), + css: [None, Some(0), Some(1), Some(2)] + .into_iter() + .map(|file| get_css(file, false)) + .collect(), + } +} + +/// Extract the app one source after another, as a loader does. +fn one_by_one(app: &[(String, String)], source_map: bool) -> Outcome { + set_up(app); + let outputs = app + .iter() + .map(|(filename, code)| { + let diagnostics = Rc::new(RefCell::new(ResolverState::new(filename, code))); + let resolver = { + let (diagnostics, app) = (Rc::clone(&diagnostics), app.to_vec()); + move |specifier: &str, importer: &str| { + let request = diagnostics.borrow().request(specifier, importer)?; + let (path, code) = module(&app, specifier, importer)?; + let module = extractor::ResolvedModule { path, code }; + diagnostics.borrow_mut().cache(&module, &request); + Some(module) + } + }; + let check = || diagnostics.borrow().check(); + code_extract( + (filename, code), + ExtractOption { + css_dir: css_dir(filename), + ..option() + }, + ExtractionMode { + source_map: if source_map { + SourceMapMode::Generate + } else { + SourceMapMode::Skip + }, + resolver: Some(&resolver), + resolver_check: Some(&check), + import_main_css_in_css: true, + }, + ) + .map(|output| Output { + css: None, + ..output + }) + }) + .collect(); + outcome(outputs) +} + +fn sources(app: &[(String, String)]) -> Vec { + app.iter() + .map(|(filename, code)| BatchSource { + filename: filename.clone(), + code: code.clone(), + css_dir: css_dir(filename), + }) + .collect() +} + +fn resolver(app: &[(String, String)]) -> Ask { + let app = app.to_vec(); + Rc::new(move |specifier: &str, importer: &str| { + module(&app, specifier, importer).map_or(HostAnswer::Unresolved, |(path, code)| { + HostAnswer::Module { path, code } + }) + }) +} + +fn batch(app: &[(String, String)], threads: usize, source_map: bool) -> (Outcome, bool) { + set_up(app); + let batch = extract_batch( + &sources(app), + &BatchOptions { + option: option(), + source_map: if source_map { + SourceMapMode::Generate + } else { + SourceMapMode::Skip + }, + import_main_css_in_css: true, + threads, + }, + Some(&resolver(app)), + ); + (outcome(batch.outputs), batch.parallel) +} + +#[test] +#[serial] +fn a_batch_extracts_as_one_by_one_on_any_number_of_threads() { + let app = app(); + let expected = one_by_one(&app, false); + assert!( + expected.outputs.iter().any(Result::is_err), + "one source fails" + ); + assert!(expected.classes.contains(BARREL)); + + for threads in [1, 2, 3, 4, 8, 16, 64] { + for _ in 0..if threads == 8 { 8 } else { 2 } { + let (outcome, parallel) = batch(&app, threads, false); + assert_eq!(parallel, threads > 1); + assert_eq!(outcome, expected, "{threads} threads"); + } + } +} + +#[test] +#[serial] +fn a_batch_maps_sources_as_one_by_one() { + let app = app(); + let expected = one_by_one(&app, true); + assert!( + expected + .outputs + .iter() + .flatten() + .any(|output| output.1.is_some()) + ); + + let (outcome, _) = batch(&app, 4, true); + assert_eq!(outcome, expected); +} + +#[test] +#[serial] +fn a_batch_under_atom_hoisting_extracts_one_by_one() { + let app = app(); + set_up(&app); + set_atom_hoist(Some(2)); + let batch = extract_batch( + &sources(&app[..3]), + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: true, + threads: 4, + }, + None, + ); + set_atom_hoist(None); + + assert!(!batch.parallel); + assert_eq!(batch.outputs.len(), 3); +} + +#[test] +#[serial] +fn a_batch_without_a_resolver_extracts_as_one_by_one_without_one() { + let app = app(); + let sources = sources(&app); + let run = |threads| { + set_up(&app); + let batch = extract_batch( + &sources, + &BatchOptions { + option: option(), + source_map: SourceMapMode::Generate, + import_main_css_in_css: false, + threads, + }, + None, + ); + outcome(batch.outputs) + }; + + assert_eq!(run(4), run(1)); +} + +/// The output of a source reading `./tokens`, resolved through `answer`. +fn resolved_through(answer: HostAnswer, threads: usize) -> Result { + reset_state_internal(|| {}); + let answer = RefCell::new(Some(answer)); + let ask: Ask = Rc::new(move |_: &str, _: &str| { + answer.borrow_mut().take().unwrap_or(HostAnswer::Unresolved) + }); + let sources = [BatchSource { + filename: "src/view.tsx".to_string(), + code: "import { Box } from '@devup-ui/react'\nimport { tones } from './tokens'\nexport const view = \n".to_string(), + css_dir: "./df".to_string(), + }]; + extract_batch( + &sources, + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: false, + threads, + }, + Some(&ask), + ) + .outputs + .remove(0) +} + +#[test] +#[serial] +fn a_batch_reports_what_the_resolver_answers_as_one_by_one() { + for threads in [1, 2] { + let module = resolved_through( + HostAnswer::Module { + path: "src/tokens.ts".to_string(), + code: "export const tones = { a: '#123456' } as const\n".to_string(), + }, + threads, + ); + assert!(module.is_ok_and(|output| output.code.contains("className"))); + + let failed = resolved_through(HostAnswer::Failed("no tokens".to_string()), threads); + assert!(failed.is_err_and( + |error| error.contains("module resolver failed for `./tokens`") + && error.contains("no tokens") + )); + + let unnamed = resolved_through( + HostAnswer::Module { + path: String::new(), + code: String::new(), + }, + threads, + ); + assert!(unnamed.is_err_and(|error| error.contains("`path` must be a non-empty string"))); + + let transport = resolved_through(HostAnswer::Transport("gone".to_string()), threads); + assert_eq!(transport.err().as_deref(), Some("gone")); + + let unresolved = resolved_through(HostAnswer::Unresolved, threads); + assert!(unresolved.is_ok()); + } +} + +#[test] +#[serial] +fn an_empty_batch_extracts_nothing() { + reset_state_internal(|| {}); + let batch = extract_batch( + &[], + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: false, + threads: 4, + }, + None, + ); + assert!(batch.outputs.is_empty()); + assert!(batch.parallel); +} + +#[test] +#[serial] +fn workers_ask_the_resolver_once_for_each_import_of_each_source() { + let app = app(); + let run = |threads| { + set_up(&app); + let asked = Rc::new(RefCell::new(Vec::new())); + let ask: Ask = { + let (asked, resolve) = (Rc::clone(&asked), resolver(&app)); + Rc::new(move |specifier: &str, importer: &str| { + asked + .borrow_mut() + .push((specifier.to_string(), importer.to_string())); + resolve(specifier, importer) + }) + }; + let batch = extract_batch( + &sources(&app), + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: true, + threads, + }, + Some(&ask), + ); + let asked = asked.borrow().clone(); + (outcome(batch.outputs), asked) + }; + let (expected, one_by_one) = run(1); + let (outcome, parallel) = run(4); + + let mut unique = one_by_one.clone(); + unique.sort(); + unique.dedup(); + assert!( + unique.len() < one_by_one.len(), + "sources ask for an import again" + ); + let mut asked = parallel; + asked.sort(); + assert_eq!(asked, unique); + assert_eq!(outcome, expected); +} + +/// Global styles a source reaches through an import are named when the +/// source is committed, after the sources extracted before it. +#[test] +#[serial] +fn a_batch_commits_each_source_before_a_later_one_names() { + let file = |name: &str, code: &str| (name.to_string(), code.to_string()); + let mut app = vec![ + file( + "src/reset.ts", + "import { globalCss } from '@devup-ui/react' +export function reset() { + globalCss({ body: { margin: 0 }, h1: { fontSize: '2em' }, '*': { boxSizing: 'border-box' } }) +} +", + ), + file( + "src/layout.tsx", + "import { Box } from '@devup-ui/react' +import { reset } from './reset' +reset() +export const Layout = () => +", + ), + ]; + for index in 0..6 { + app.push(file( + &format!("src/page{index}.tsx"), + &format!( + "import {{ Grid, Flex }} from '@devup-ui/react' +export const Page = () => +" + ), + )); + } + let expected = one_by_one(&app, false); + + for threads in [1, 2, 4, 8] { + for _ in 0..4 { + assert_eq!(batch(&app, threads, false).0, expected, "{threads} threads"); + } + } +} + +/// A resolver that panics on the calling thread fails the batch: no worker +/// waits for an answer it can no longer get. +#[test] +#[serial] +fn a_resolver_that_panics_fails_the_batch_without_hanging() { + let app = app(); + set_up(&app); + let ask: Ask = Rc::new(|_: &str, _: &str| panic!("resolver panicked")); + let sources = sources(&app); + + let batch = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + extract_batch( + &sources, + &BatchOptions { + option: option(), + source_map: SourceMapMode::Skip, + import_main_css_in_css: true, + threads: 8, + }, + Some(&ask), + ) + })); + + assert!(batch.is_err()); +} diff --git a/libs/css/src/file_map.rs b/libs/css/src/file_map.rs index 6f23fea77..41131bfdf 100644 --- a/libs/css/src/file_map.rs +++ b/libs/css/src/file_map.rs @@ -86,8 +86,10 @@ pub fn get_file_num_by_filename(filename: &str) -> usize { // RefCell::borrow_mut contention); only fall back to the write guard on a // genuine miss. if let Some(file_num) = with_file_map(|map| map.get_by_left(filename).copied()) { + crate::numbering_order::observe(); return file_num; } + crate::numbering_order::before_numbering(); with_file_map_mut(|map| { // Re-check under the write lock in case another registration slipped in // during the brief unlocked window between the two guards. diff --git a/libs/css/src/lib.rs b/libs/css/src/lib.rs index b19d8f27d..17a904eff 100644 --- a/libs/css/src/lib.rs +++ b/libs/css/src/lib.rs @@ -12,6 +12,7 @@ pub mod file_routes; pub mod is_special_property; pub mod license_banner; mod num_to_nm_base; +pub mod numbering_order; pub mod optimize_multi_css_value; pub mod optimize_value; mod property_names; @@ -65,27 +66,29 @@ mod prefix_state { #[cfg(not(target_arch = "wasm32"))] mod prefix_state { - use std::sync::LazyLock; - use std::sync::Mutex; - static GLOBAL_PREFIX: LazyLock>> = LazyLock::new(|| Mutex::new(None)); + use std::sync::{Arc, LazyLock, Mutex}; + static GLOBAL_PREFIX: LazyLock>>> = LazyLock::new(|| Mutex::new(None)); + fn current() -> Option> { + GLOBAL_PREFIX + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } pub fn set_prefix(prefix: Option) { *GLOBAL_PREFIX .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = prefix; + .unwrap_or_else(std::sync::PoisonError::into_inner) = prefix.map(Arc::from); } pub fn get_prefix() -> Option { - GLOBAL_PREFIX - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() + current().as_deref().map(str::to_string) } - /// Run `f` with the current prefix as `&str` (empty when unset) without cloning. + /// Run `f` with the current prefix as `&str` (empty when unset) without cloning it. + /// + /// The lock is released before `f` runs: `f` names classes, which can wait + /// for an earlier file's turn, and that file names classes with the prefix too. pub(crate) fn with_prefix(f: impl FnOnce(&str) -> R) -> R { - f(GLOBAL_PREFIX - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .as_deref() - .unwrap_or_default()) + let prefix = current(); + f(prefix.as_deref().unwrap_or_default()) } } @@ -424,6 +427,7 @@ thread_local! { /// Single home for the class naming algorithm shared by keyframes, classname /// and variable-name generation. fn class_num_for_key(filename_key: &str, build_key: impl FnOnce(&mut String)) -> String { + numbering_order::before_numbering(); KEY_BUF.with(|buf| { let mut key = buf.borrow_mut(); key.clear(); @@ -779,6 +783,23 @@ mod tests { set_prefix(None); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[serial] + fn test_with_prefix_holds_no_lock_while_naming() { + // Given: a naming step that reads the prefix again (as a worker + // waiting for its turn lets an earlier file do) + let _state = test_state::TestStateGuard::new(); + set_prefix(Some("host-".to_string())); + + // When + let prefixes = with_prefix(|outer| (outer.to_string(), get_prefix())); + + // Then: the inner read does not wait on the outer one + assert_eq!(prefixes, ("host-".to_string(), Some("host-".to_string()))); + set_prefix(None); + } + #[rstest] #[case("hover", "hover")] #[case("&:hover", "_a__c_hover")] diff --git a/libs/css/src/numbering_order.rs b/libs/css/src/numbering_order.rs new file mode 100644 index 000000000..313cdd4a6 --- /dev/null +++ b/libs/css/src/numbering_order.rs @@ -0,0 +1,195 @@ +//! Number classes and files in a fixed order of extractions running at once. +//! +//! Class and file numbers are handed out first come, first served, so the +//! order extractions number in decides them. Several threads can extract at +//! once and still number as extracting one after another would, when each +//! extraction numbers only in its turn: from its first number to the point +//! where its outermost extraction has handed out its last, no other numbers. +//! +//! A thread starts an extraction's turn with [`Turn::begin`]. Its first +//! number waits for the turn, and [`numbering_done`], which the extractor calls +//! once the outermost extraction can hand out no more, names what committing +//! its styles to the stylesheet will and passes the turn on, as ending the +//! turn does. A number taken after that is out of order, and +//! [`Turn::finish`] reports it. + +use std::cell::{Cell, RefCell}; +use std::marker::PhantomData; +use std::rc::Rc; + +use crate::class_map::{ClassMap, get_class_map, set_class_map}; +use crate::file_map::{FileMap, get_file_map, set_file_map}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Phase { + /// Has not numbered yet + Before, + /// Numbers in its turn + Numbering, + /// Passed its turn on + Passed, + /// Numbered after passing its turn on + OutOfOrder, +} + +struct Ordered { + phase: Phase, + wait: Box, + pass: Box, +} + +impl Ordered { + fn pass_on(&mut self) { + if matches!(self.phase, Phase::Before | Phase::Numbering) { + (self.pass)(); + self.phase = Phase::Passed; + } + } +} + +thread_local! { + static ORDERED: RefCell> = const { RefCell::new(None) }; + /// How many extractions run inside one another on this thread + static DEPTH: Cell = const { Cell::new(0) }; +} + +/// One extraction's turn to number on this thread. +#[must_use] +pub struct Turn { + thread_bound: PhantomData>, +} + +impl Turn { + /// Start an extraction whose first number calls `wait`, which returns once + /// it is the extraction's turn, and which calls `pass` once to pass the + /// turn on, by the end at the latest. + pub fn begin(wait: impl Fn() + 'static, pass: impl Fn() + 'static) -> Self { + ORDERED.set(Some(Ordered { + phase: Phase::Before, + wait: Box::new(wait), + pass: Box::new(pass), + })); + Self { + thread_bound: PhantomData, + } + } + + /// End the turn, passing it on if it was not, and return whether the + /// extraction numbered only in its turn. + pub fn finish(self) -> bool { + ORDERED.with_borrow_mut(|ordered| { + ordered.as_mut().is_none_or(|ordered| { + ordered.pass_on(); + ordered.phase != Phase::OutOfOrder + }) + }) + } +} + +impl Drop for Turn { + fn drop(&mut self) { + if let Some(mut ordered) = ORDERED.take() { + ordered.pass_on(); + } + } +} + +/// Wait for this thread's turn before handing out a number. +pub(crate) fn before_numbering() { + ORDERED.with_borrow_mut(|ordered| { + if let Some(ordered) = ordered { + match ordered.phase { + Phase::Before => { + (ordered.wait)(); + ordered.phase = Phase::Numbering; + } + Phase::Numbering | Phase::OutOfOrder => {} + Phase::Passed => ordered.phase = Phase::OutOfOrder, + } + } + }); +} + +/// Note that this thread read a number already handed out. +/// +/// Before the turn it was handed out by an extraction ordered earlier, as +/// only those number before this turn; after it, maybe by a later one. +pub(crate) fn observe() { + ORDERED.with_borrow_mut(|ordered| { + if let Some(ordered) = ordered + && ordered.phase == Phase::Passed + { + ordered.phase = Phase::OutOfOrder; + } + }); +} + +/// The outermost extraction on this thread hands out no more numbers but +/// what `name_committed` names: in its turn, run it, then pass the turn on. +/// +/// Committing the extraction's styles names classes too; naming them in the +/// turn leaves the commit, which can come after later extractions, nothing +/// new to name. +pub fn numbering_done(name_committed: impl FnOnce()) { + let in_turn = DEPTH.get() == 1 + && ORDERED.with_borrow(|ordered| { + ordered + .as_ref() + .is_some_and(|ordered| matches!(ordered.phase, Phase::Before | Phase::Numbering)) + }); + if in_turn { + name_committed(); + ORDERED.with_borrow_mut(|ordered| { + if let Some(ordered) = ordered { + ordered.pass_on(); + } + }); + } +} + +/// Marks an extraction running on this thread, inside any it runs within. +#[must_use] +pub struct Extracting { + thread_bound: PhantomData>, +} + +/// Enter an extraction; only the outermost one passes the turn on. +pub fn extracting() -> Extracting { + DEPTH.set(DEPTH.get() + 1); + Extracting { + thread_bound: PhantomData, + } +} + +impl Drop for Extracting { + fn drop(&mut self) { + DEPTH.set(DEPTH.get() - 1); + } +} + +/// The class and file numbering as it was, to number again from. +pub struct Snapshot { + classes: ClassMap, + files: FileMap, + reservation: crate::slot_reservation::State, +} + +impl Snapshot { + pub fn take() -> Self { + Self { + classes: get_class_map(), + files: get_file_map(), + reservation: crate::slot_reservation::current_state(), + } + } + + /// Make the numbering what it was when taken. + pub fn restore(self) { + set_class_map(self.classes); + set_file_map(self.files); + crate::slot_reservation::replace_state(self.reservation); + } +} + +#[cfg(test)] +mod tests; diff --git a/libs/css/src/numbering_order/tests.rs b/libs/css/src/numbering_order/tests.rs new file mode 100644 index 000000000..e0f1a0438 --- /dev/null +++ b/libs/css/src/numbering_order/tests.rs @@ -0,0 +1,172 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use serial_test::serial; + +use super::*; +use crate::file_map::get_file_num_by_filename; +use crate::keyframes_to_keyframes_name; +use crate::test_state::TestStateGuard; + +/// A turn that records when it waits and passes. +fn recorded_turn() -> (Turn, Rc>>) { + let events = Rc::new(RefCell::new(Vec::new())); + let (waits, passes) = (Rc::clone(&events), Rc::clone(&events)); + let turn = Turn::begin( + move || waits.borrow_mut().push("wait"), + move || passes.borrow_mut().push("pass"), + ); + (turn, events) +} + +#[test] +#[serial] +fn the_first_number_waits_for_the_turn_and_the_outermost_extraction_passes_it() { + let _state = TestStateGuard::new(); + let (turn, events) = recorded_turn(); + let outer = extracting(); + assert!(events.borrow().is_empty()); + + let _ = keyframes_to_keyframes_name("x", None); + let _ = keyframes_to_keyframes_name("y", None); + assert_eq!(*events.borrow(), ["wait"]); + let inner = extracting(); + numbering_done(|| {}); + assert_eq!( + *events.borrow(), + ["wait"], + "a nested extraction keeps the turn" + ); + drop(inner); + numbering_done(|| {}); + assert_eq!(*events.borrow(), ["wait", "pass"]); + drop(outer); + + assert!(turn.finish()); + assert_eq!(*events.borrow(), ["wait", "pass"]); +} + +#[test] +#[serial] +fn a_file_number_handed_out_waits_for_the_turn_but_one_read_does_not() { + let _state = TestStateGuard::new(); + let _ = get_file_num_by_filename("a.tsx"); + let (turn, events) = recorded_turn(); + + assert_eq!(get_file_num_by_filename("a.tsx"), 0); + assert!(events.borrow().is_empty()); + assert_eq!(get_file_num_by_filename("b.tsx"), 1); + assert_eq!(*events.borrow(), ["wait"]); + + assert!(turn.finish()); + assert_eq!(*events.borrow(), ["wait", "pass"]); +} + +#[test] +#[serial] +fn numbering_after_passing_the_turn_is_out_of_order() { + let _state = TestStateGuard::new(); + let (turn, _) = recorded_turn(); + let _extracting = extracting(); + numbering_done(|| {}); + let _ = keyframes_to_keyframes_name("x", None); + let _ = keyframes_to_keyframes_name("y", None); + + assert!(!turn.finish()); +} + +#[test] +#[serial] +fn reading_a_file_number_after_passing_the_turn_is_out_of_order() { + let _state = TestStateGuard::new(); + let _ = get_file_num_by_filename("a.tsx"); + let (turn, events) = recorded_turn(); + let _extracting = extracting(); + numbering_done(|| {}); + let _ = get_file_num_by_filename("a.tsx"); + + assert!(!turn.finish()); + assert_eq!(*events.borrow(), ["pass"]); +} + +#[test] +#[serial] +fn a_turn_that_never_numbers_passes_once_it_ends() { + let _state = TestStateGuard::new(); + let (turn, events) = recorded_turn(); + drop(turn); + + assert_eq!(*events.borrow(), ["pass"]); + let _ = keyframes_to_keyframes_name("x", None); + assert_eq!( + *events.borrow(), + ["pass"], + "numbers outside a turn wait for none" + ); +} + +#[test] +#[serial] +fn a_turn_ended_by_a_later_one_numbered_in_order() { + let _state = TestStateGuard::new(); + let (outer, _) = recorded_turn(); + let (inner, events) = recorded_turn(); + drop(inner); + + assert!(outer.finish()); + assert_eq!(*events.borrow(), ["pass"]); +} + +#[test] +#[serial] +fn a_snapshot_restores_the_numbering_it_was_taken_of() { + let _state = TestStateGuard::new(); + crate::slot_reservation::ScratchSlots::default().commit(); + let _ = get_file_num_by_filename("a.tsx"); + let _ = keyframes_to_keyframes_name("x", None); + let snapshot = Snapshot::take(); + let (classes, files, misses) = ( + get_class_map(), + get_file_map(), + crate::slot_reservation::unreserved_slot_count(), + ); + + let _ = get_file_num_by_filename("b.tsx"); + let _ = keyframes_to_keyframes_name("y", None); + assert_ne!(crate::slot_reservation::unreserved_slot_count(), misses); + snapshot.restore(); + + assert_eq!(get_class_map(), classes); + assert_eq!(get_file_map(), files); + assert_eq!(crate::slot_reservation::unreserved_slot_count(), misses); +} + +#[test] +#[serial] +fn the_outermost_extraction_names_what_it_commits_in_its_turn_only() { + let _state = TestStateGuard::new(); + let named = Rc::new(RefCell::new(0)); + let name = || { + let named = Rc::clone(&named); + move || *named.borrow_mut() += 1 + }; + numbering_done(name()); + assert_eq!(*named.borrow(), 0, "no turn"); + + let (turn, events) = recorded_turn(); + let outer = extracting(); + let inner = extracting(); + numbering_done(name()); + assert_eq!(*named.borrow(), 0, "a nested extraction"); + drop(inner); + numbering_done(|| { + *named.borrow_mut() += 1; + let _ = keyframes_to_keyframes_name("committed", None); + }); + assert_eq!(*named.borrow(), 1); + assert_eq!(*events.borrow(), ["wait", "pass"]); + numbering_done(name()); + assert_eq!(*named.borrow(), 1, "a turn passed on"); + drop(outer); + assert!(turn.finish()); +} diff --git a/libs/css/src/slot_reservation.rs b/libs/css/src/slot_reservation.rs index 6fbce61b2..fbdd8d6db 100644 --- a/libs/css/src/slot_reservation.rs +++ b/libs/css/src/slot_reservation.rs @@ -45,6 +45,10 @@ pub fn reset() { with_state(|state| *state = State::default()); } +pub(crate) fn current_state() -> State { + with_state(|state| *state) +} + pub(crate) fn replace_state(replacement: State) -> State { with_state(|state| std::mem::replace(state, replacement)) } diff --git a/libs/extractor/src/lib.rs b/libs/extractor/src/lib.rs index 94c8658e7..f386efb0e 100644 --- a/libs/extractor/src/lib.rs +++ b/libs/extractor/src/lib.rs @@ -488,6 +488,7 @@ fn extract_with_source_map( if let ExtractTarget::Native(target) = option.target { return native::extract(filename, code, &option.package, target, source_map); } + let _extracting = css::numbering_order::extracting(); extract_source(filename, code, None, None, option, source_map, resolver) } @@ -1092,6 +1093,10 @@ fn extract_source( message += &changed_notes(&message, filename, source, &edits, &inlined.changed); return Err(message.into()); } + // Generating the code names nothing more + css::numbering_order::numbering_done(|| { + name_as_committed(visitor.styles.styles(), filename, option.single_css); + }); let codegen_options = if source_map { CodegenOptions { source_map_path: Some(PathBuf::from(filename)), @@ -1142,6 +1147,19 @@ fn extract_source( }) } +/// Name the classes of `styles` as committing them to the stylesheet does: +/// in their order, in the global bucket for a single or global stylesheet and +/// in the file's bucket otherwise. +fn name_as_committed(styles: &FxHashSet, filename: &str, single_css: bool) { + let _atom_mode = css::atom_hoist::AtomModeGuard::new(single_css); + let scope = (!(single_css || is_global(filename))).then(|| canonical(filename)); + let mut ordered: Vec<&ExtractStyleValue> = styles.iter().collect(); + ordered.sort_unstable(); + for style in ordered { + let _ = style.extract(scope.as_deref()); + } +} + /// Build the shared `devup-ui.css` main-css path for a given css directory. /// /// Single source of truth for the `"{css_dir}/devup-ui.css"` literal, used both diff --git a/libs/extractor/src/style_collector.rs b/libs/extractor/src/style_collector.rs index d9dbe95c8..5cdca75a8 100644 --- a/libs/extractor/src/style_collector.rs +++ b/libs/extractor/src/style_collector.rs @@ -74,6 +74,12 @@ impl StyleCollector { self.styles.is_empty() && self.layers.is_empty() } + /// The styles collected so far. + #[must_use] + pub const fn styles(&self) -> &FxHashSet { + &self.styles + } + /// The styles of `file`, with the order of its layers when it uses any #[must_use] pub fn into_styles(mut self, file: &str) -> FxHashSet {