//! [`crate::absolute_runner`]'s counterpart for the transform function //! (`crates/layout/src/transform.rs`, `specs/transforms2d.md`). Structurally identical: //! same scoring, same regression-set admission gate, no extra intermediate-fact check the //! way `crate::margin_runner` adds one against `crates/logic`'s rules -- there is no //! analogous rules engine for transforms to cross-check against, so geometry-regression- //! free is this function's whole admission gate too. //! //! Unlike `crate::absolute_runner`, every other function here runs at its own admitted //! candidate rather than its baseline: this corpus's documents set explicit widths and //! heights, but they also stack ordinary in-flow siblings whose placement the width, //! margin, height and percentage functions decide, and a case must not fail because one //! of those got the untransformed geometry wrong. Only the transform matrix is under //! test. use std::collections::BTreeMap; use std::fs; use std::path::PathBuf; use anyhow::{bail, Context, Result}; use dom::Document; use harness::compare::{ compare, relative_offset, CaseComparison, CaseReport, Consensus, Metric, VoteMeasurement, }; use harness::dump::{Dump, Node as DumpNode, Rect, Viewport, TOLERANCE_PX}; use layout::boxtree::BoxTree; use layout::fragment; use layout::transform::TransformResolver; use crate::groundtruth::CachedCase; use crate::runner::{CandidateReport, CaseGeometryDiff, CategoryTally, Report}; /// The harness's fixed viewport, matching `crate::runner::VIEWPORT_WIDTH`. const VIEWPORT_WIDTH: f64 = 800.0; const VIEWPORT_HEIGHT: f64 = 600.0; /// Renders `html` through the real layout path with every other function held at its own /// admitted candidate (this module's own doc comment) and `resolver` standing in for the /// transform function. Mirrors `crate::absolute_runner::candidate_dump`, generalized over /// which resolver runs. pub fn candidate_dump(html: &str, resolver: TransformResolver) -> Dump { let document = Document::parse(html); let elements = document.elements_in_document_order(); let tree = BoxTree::build(&document); let root_fragment = fragment::layout_with_resolvers( &document, &tree, (VIEWPORT_WIDTH, VIEWPORT_HEIGHT), &fragment::Resolvers { width_resolver: layout::generated_width_resolve, margin_classify: layout::generated_margin_classify, margin_combine: layout::generated_margin_combine, percentage_resolver: layout::generated_percentage_resolve, absolute_resolver: layout::generated_absolute_resolve, float_resolver: layout::generated_float_resolve, relpos_resolver: layout::generated_relpos_resolve, height_resolver: layout::generated_height_resolve, containing_block_resolver: layout::generated_containing_block_resolve, transform_resolver: resolver, ..fragment::Resolvers::baselines() }, ); let mut rects: BTreeMap = BTreeMap::new(); root_fragment.walk_absolute(0.0, 0.0, &mut |node, x, y, w, h| { rects.insert(node, Rect { x, y, w, h }); }); let mut index_of: BTreeMap = BTreeMap::new(); for (i, &el) in elements.iter().enumerate() { index_of.insert(el, i); } let nodes = elements .iter() .enumerate() .map(|(index, el)| { let parent = el.dom_parent().map(|p| index_of[&p] as i64).unwrap_or(-1); let mut depth = 0u32; let mut cur = *el; while let Some(p) = cur.dom_parent() { depth += 1; cur = p; } let rect = rects.get(el).copied(); DumpNode { index, parent, tag: el.tag(), depth, bounding: rect.unwrap_or(Rect { x: 0.0, y: 0.0, w: 0.0, h: 0.0 }), rects: rect.map(|r| vec![r]).unwrap_or_default(), scroll: None, style: Default::default(), } }) .collect(); Dump { engine: "candidate".to_string(), engine_version: "0".to_string(), viewport: Viewport { width: 800, height: 600 }, overflowed: false, nodes, } } fn majority_value(m: &VoteMeasurement) -> Option { match &m.consensus { Consensus::Split => None, Consensus::Unanimous => m.values.values().next().copied(), Consensus::Majority { outlier } => { m.values.iter().find(|(engine, _)| *engine != outlier).map(|(_, v)| *v) } } } fn candidate_value(candidate: &Dump, m: &VoteMeasurement) -> Option { let node = candidate.nodes.get(m.node_index)?; Some(match m.metric { Metric::Width => node.bounding.w, Metric::Height => node.bounding.h, Metric::OffsetX => relative_offset(candidate, node).0, Metric::OffsetY => relative_offset(candidate, node).1, Metric::FragmentCount => node.rects.len() as f64, Metric::FragmentWidth(i) => node.rects.get(i)?.w, Metric::FragmentHeight(i) => node.rects.get(i)?.h, }) } fn agrees_with_vote(candidate: &Dump, vote_report: &harness::compare::VoteReport) -> bool { vote_report.measurements.iter().filter(|m| m.is_trustworthy()).all(|m| { let Some(reference) = majority_value(m) else { return true }; match candidate_value(candidate, m) { Some(v) => (v - reference).abs() <= TOLERANCE_PX, None => false, } }) } #[derive(Debug, Clone, Copy, PartialEq)] enum Outcome { Passed, Failed, Untrustworthy, } /// Scores one case and keeps the per-node numeric error alongside the verdict, the same /// contract as `crate::runner::score_case`. The [`CaseReport`] is `None` when the case /// never reached geometry comparison -- a discarded case, or node sequences that do not /// line up at all. fn score_case(case: &CachedCase, resolver: TransformResolver) -> (Outcome, Option) { let Some(reference) = case.dumps.get("chromium").or_else(|| case.dumps.values().next()) else { return (Outcome::Untrustworthy, None); }; let candidate = candidate_dump(&case.html, resolver); match compare(&candidate, reference) { CaseComparison::Discarded(_) => (Outcome::Untrustworthy, None), CaseComparison::ShapeMismatch(_) => (Outcome::Failed, None), CaseComparison::Compared(pairwise) => { let outcome = match case.vote() { Ok(vote_report) => { if agrees_with_vote(&candidate, &vote_report) { Outcome::Passed } else { Outcome::Failed } } Err(_) => { if pairwise.passed { Outcome::Passed } else { Outcome::Failed } } }; (outcome, Some(pairwise)) } } } pub fn passing_case_ids(resolver: TransformResolver, cases: &[CachedCase]) -> Vec { cases .iter() .filter(|case| score_case(case, resolver).0 == Outcome::Passed) .map(|case| case.case_id.clone()) .collect() } pub fn evaluate( registry: &[(&str, TransformResolver)], cases: &[CachedCase], regression_set: Option<&[String]>, ) -> Report { let candidates = registry .iter() .filter_map(|(name, resolver)| { // A candidate that panics mid-corpus would otherwise unwind out of this loop // and take the whole batch's process down with it, losing every other // candidate's score -- the same isolation `crate::absolute_runner::evaluate` // gives for the same reason. std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { score_candidate(name, *resolver, cases, regression_set) })) .map_err(|_| { println!("{name}: panicked while scoring, dropped from the batch"); }) .ok() }) .collect(); Report { candidates } } /// One candidate's pass over the whole corpus. Split out of [`evaluate`] so a panicking /// candidate can be caught and dropped without unwinding past the others. fn score_candidate( name: &str, resolver: TransformResolver, cases: &[CachedCase], regression_set: Option<&[String]>, ) -> CandidateReport { let mut cases_run = 0u64; let mut cases_passed = 0u64; let mut passed_ids: Vec = Vec::new(); let mut per_category: BTreeMap = BTreeMap::new(); let mut failing_case_diffs: Vec = Vec::new(); for case in cases { let (outcome, case_report) = score_case(case, resolver); if outcome == Outcome::Untrustworthy { continue; } cases_run += 1; let passed = outcome == Outcome::Passed; if passed { cases_passed += 1; passed_ids.push(case.case_id.clone()); } else if let Some(report) = &case_report { failing_case_diffs.push(CaseGeometryDiff::from_case_report(&case.case_id, report)); } for category in &case.categories { let tally = per_category.entry(category.clone()).or_default(); tally.total += 1; if passed { tally.passed += 1; } } } let regressed_cases: Vec = regression_set .unwrap_or(&[]) .iter() .filter(|id| !passed_ids.contains(id)) .cloned() .collect(); CandidateReport { name: name.to_string(), cases_run, cases_passed, admitted: regressed_cases.is_empty(), regressed_cases, per_category, passed_case_ids: passed_ids, failing_case_diffs, } } /// Entry point a generated transform candidate crate's `main.rs` calls /// (`crate::candidate_crate::write_for` with `Seam::Transform`), the same /// environment-variable contract `crate::absolute_runner::main` uses. pub fn main(registry: &[(&str, TransformResolver)]) -> Result<()> { let cache_dir = PathBuf::from( std::env::var("GENERATION_CACHE_DIR") .context("GENERATION_CACHE_DIR must name the ground-truth cache directory")?, ); let cases = crate::groundtruth::load_all(&cache_dir)?; if cases.is_empty() { bail!("no cached cases under {}; run the ground_truth_cache binary first", cache_dir.display()); } let regression_set: Option> = match std::env::var("GENERATION_REGRESSION_SET") { Ok(path) => { let json = fs::read_to_string(&path).with_context(|| format!("reading {path}"))?; Some(serde_json::from_str(&json).with_context(|| format!("parsing {path}"))?) } Err(_) => None, }; let report = evaluate(registry, &cases, regression_set.as_deref()); let json = serde_json::to_string_pretty(&report)?; if let Ok(out) = std::env::var("GENERATION_REPORT_OUT") { fs::write(&out, &json).with_context(|| format!("writing {out}"))?; } println!("{json}"); Ok(()) } #[cfg(test)] mod tests { use super::*; use dom::computed::{LengthPercentage, TransformFunction}; use layout::transform::{TransformInputs, TransformOutputs, IDENTITY}; /// A `translate()`-only implementation, origin ignored (a translation does not depend /// on the origin, so ignoring it is still correct for this one function) -- enough to /// score the `TranslatePx` recipe correctly, used only to check this runner's own /// scoring plumbing. Not registered anywhere the generation loop reads. fn resolve_translate_only(inputs: &TransformInputs) -> TransformOutputs { let resolve = |v: LengthPercentage, basis: f64| match v { LengthPercentage::Length(px) => px, LengthPercentage::Percentage(p) => p * basis, LengthPercentage::Unresolved => 0.0, }; let mut matrix = IDENTITY; for function in &inputs.functions { if let TransformFunction::Translate { x, y } = function { let tx = resolve(*x, inputs.border_box_width); let ty = resolve(*y, inputs.border_box_height); matrix = layout::transform::compose(matrix, [1.0, 0.0, 0.0, 1.0, tx, ty]); } } TransformOutputs { matrix } } const RESET: &str = "* { margin: 0; padding: 0; border: 0; box-sizing: content-box; }\nhtml, body { display: block; }\n"; fn find_index(html: &str, class: &str) -> usize { let document = Document::parse(html); document .elements_in_document_order() .into_iter() .enumerate() .find(|(_, e)| document.nodes()[e.index()].as_element().unwrap().attr("class") == Some(class)) .map(|(i, _)| i) .unwrap_or_else(|| panic!("no element with class={class:?}")) } fn translated_document() -> String { format!( "
" ) } #[test] fn baseline_leaves_a_translated_box_where_normal_flow_put_it() { let html = translated_document(); let dump = candidate_dump(&html, layout::transform::resolve_baseline); let a = &dump.nodes[find_index(&html, "a")]; assert_eq!(relative_offset(&dump, a), (0.0, 0.0), "the translation is ignored"); assert_eq!((a.bounding.w, a.bounding.h), (120.0, 80.0)); } #[test] fn a_candidate_that_reads_translate_moves_the_box_without_resizing_it() { let html = translated_document(); let dump = candidate_dump(&html, resolve_translate_only); let a = &dump.nodes[find_index(&html, "a")]; assert_eq!(relative_offset(&dump, a), (40.0, 25.0)); assert_eq!((a.bounding.w, a.bounding.h), (120.0, 80.0), "a translation never resizes"); } /// CSS Transforms 1's "does not affect the flow", measured through the real layout /// path: the sibling after a translated box stays exactly where the untransformed /// engine put it. #[test] fn a_transformed_box_does_not_move_its_siblings() { let html = format!( "
" ); let untransformed = candidate_dump(&html, layout::transform::resolve_baseline); let translated = candidate_dump(&html, resolve_translate_only); let b = find_index(&html, "b"); assert_eq!( translated.nodes[b].bounding.y, untransformed.nodes[b].bounding.y, "the following sibling is placed as if the transform were not there" ); } /// A descendant of a transformed box moves with it, through its ancestor's matrix. #[test] fn a_descendant_of_a_transformed_box_moves_with_it() { let html = format!( "
" ); let untransformed = candidate_dump(&html, layout::transform::resolve_baseline); let translated = candidate_dump(&html, resolve_translate_only); let d = find_index(&html, "d"); assert_eq!(translated.nodes[d].bounding.x - untransformed.nodes[d].bounding.x, 60.0); assert_eq!(translated.nodes[d].bounding.y - untransformed.nodes[d].bounding.y, 30.0); } /// One candidate panicking partway through the corpus must not lose the other /// candidates' scores -- `evaluate` catches and drops it, the rest of the batch /// still runs and reports normally. #[test] fn a_panicking_candidate_is_dropped_and_the_rest_of_the_batch_still_scores() { fn resolve_panics(_inputs: &TransformInputs) -> TransformOutputs { panic!("candidate reached an input shape it cannot handle") } let html = translated_document(); let reference = candidate_dump(&html, resolve_translate_only); let case = CachedCase { case_id: "panic-isolation".to_string(), seed: 0, categories: vec!["TranslatePx".to_string()], html, dumps: BTreeMap::from([("chromium".to_string(), reference)]), errors: BTreeMap::new(), }; // Swap in a silent panic hook so the deliberate panic below doesn't print. let previous_hook = std::panic::take_hook(); std::panic::set_hook(Box::new(|_| {})); let report = evaluate( &[ ("panicking", resolve_panics as TransformResolver), ("translate_only", resolve_translate_only as TransformResolver), ], &[case], None, ); std::panic::set_hook(previous_hook); assert_eq!(report.candidates.len(), 1, "the panicking candidate is dropped, not just failed"); assert_eq!(report.candidates[0].name, "translate_only", "the surviving candidate is the one that didn't panic"); assert_eq!(report.candidates[0].cases_run, 1, "the surviving candidate still scores the one case"); } }