//! [`crate::transform_runner`]'s counterpart for the inline-atomic function //! (`crates/layout/src/inline_atomic.rs`, `specs/inline-atomic.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 line boxes to //! cross-check against, so geometry-regression-free is this function's whole admission //! gate too. //! //! Every other function runs at its own admitted candidate rather than its baseline, the //! same choice `crate::transform_runner` makes and for the same reason: this corpus's //! documents give every box an explicit width and height, but the container's own width, //! its padding and border resolution and its auto height are still decided by the width, //! percentage and height functions, and a case must not fail because one of those got //! the geometry around the line boxes wrong. Only where the atomic inlines land 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::inline_atomic::InlineAtomicResolver; 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 /// inline-atomic function. Mirrors `crate::transform_runner::candidate_dump`, generalized /// over which resolver runs. pub fn candidate_dump(html: &str, resolver: InlineAtomicResolver) -> 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: layout::generated_transform_resolve, inline_atomic_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: InlineAtomicResolver) -> (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: InlineAtomicResolver, 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, InlineAtomicResolver)], 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::transform_runner::evaluate` // gives for the same reason. Easier to hit here than in most functions: a // candidate that indexes its own `placements` by line rather than by box // panics on the first case that breaks a line. 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: InlineAtomicResolver, 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 inline-atomic candidate crate's `main.rs` calls /// (`crate::candidate_crate::write_for` with `Seam::InlineAtomic`), the same /// environment-variable contract `crate::transform_runner::main` uses. pub fn main(registry: &[(&str, InlineAtomicResolver)]) -> 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 layout::inline_atomic::{ InlineAtomicInputs, InlineAtomicOutputs, InlinePlacement, LineBox, }; /// A one-line, left-aligned, baseline-only implementation: enough to place the /// `OneLineEqualHeights` recipe correctly, used only to check this runner's own /// scoring plumbing. It never breaks a line and ignores `vertical-align` and /// `text-align`. Not registered anywhere the generation loop reads. fn resolve_one_line(inputs: &InlineAtomicInputs) -> InlineAtomicOutputs { let tallest = inputs.inlines.iter().map(|i| i.margin_box_height).fold(0.0, f64::max); let height = tallest.max(inputs.line_height); let mut x = 0.0; let mut placements = Vec::with_capacity(inputs.inlines.len()); for inline in &inputs.inlines { placements.push(InlinePlacement { x, y: height - inline.margin_box_height }); x += inline.margin_box_width; } let lines = if inputs.inlines.is_empty() { Vec::new() } else { vec![LineBox { top: 0.0, height, baseline: height }] }; let last_baseline = lines.last().map(|line| line.top + line.baseline); let total_height = if lines.is_empty() { 0.0 } else { height }; InlineAtomicOutputs { placements, lines, total_height, last_baseline } } 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 one_line_document() -> String { format!( "
" ) } #[test] fn the_baseline_stacks_two_atomic_inlines_vertically() { let html = one_line_document(); let dump = candidate_dump(&html, layout::inline_atomic::resolve_baseline); let a = &dump.nodes[find_index(&html, "a")]; let b = &dump.nodes[find_index(&html, "b")]; assert_eq!(relative_offset(&dump, a), (0.0, 0.0)); assert_eq!(relative_offset(&dump, b), (0.0, 30.0), "under the first box, not beside it"); } #[test] fn a_candidate_that_builds_a_line_puts_them_side_by_side() { let html = one_line_document(); let dump = candidate_dump(&html, resolve_one_line); let a = &dump.nodes[find_index(&html, "a")]; let b = &dump.nodes[find_index(&html, "b")]; assert_eq!(relative_offset(&dump, a), (0.0, 0.0)); assert_eq!(relative_offset(&dump, b), (60.0, 0.0), "beside the first box, on the same line"); assert_eq!((b.bounding.w, b.bounding.h), (60.0, 30.0), "placing a box never resizes it"); } /// The container's auto height is the resolver's total height (CSS 2.1 10.6.3), so /// which resolver runs changes the container's own geometry too, not just its /// children's. fn container_height(html: &str, resolver: InlineAtomicResolver) -> f64 { candidate_dump(html, resolver).nodes[find_index(html, "c")].bounding.h } #[test] fn the_containers_auto_height_follows_the_resolvers_total() { let html = one_line_document(); assert_eq!(container_height(&html, layout::inline_atomic::resolve_baseline), 60.0, "two stacked boxes"); assert_eq!(container_height(&html, resolve_one_line), 30.0, "one line box, as tall as its content"); } /// A box on a line is still laid out as a block formatting context root inside, so /// its own children stack exactly as they would anywhere else. #[test] fn an_atomic_inlines_own_children_still_stack() { let html = format!( "
" ); let dump = candidate_dump(&html, resolve_one_line); let x = &dump.nodes[find_index(&html, "x")]; let y = &dump.nodes[find_index(&html, "y")]; assert_eq!(relative_offset(&dump, x), (0.0, 0.0)); assert_eq!(relative_offset(&dump, y), (0.0, 20.0), "stacked, not put on a line of their own"); } /// 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: &InlineAtomicInputs) -> InlineAtomicOutputs { panic!("candidate reached an input shape it cannot handle") } let html = one_line_document(); let reference = candidate_dump(&html, resolve_one_line); let case = CachedCase { case_id: "panic-isolation".to_string(), seed: 0, categories: vec!["OneLineEqualHeights".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 InlineAtomicResolver), ("one_line", resolve_one_line as InlineAtomicResolver), ], &[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, "one_line", "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"); } }