Skip to content

Truly independent web browser

169 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

//! Builds computed style group payloads directly from a drive's computed
//! longhand table.
//!
//! One call replaces the per-group marshalling loops the C++ style consumer
//! used to run: for every applied group it gathers the group's values from
//! the table (with a sparse override span for effective values the table does
//! not hold, like the animated overlay), resolves the color and opacity
//! sidecars natively, and runs the existing group builders, so the sharing
//! rules - adopt the parent's payload on equality, fall back to the process's
//! default payload - are exactly the ones the marshalled calls used.

use crate::css::style::ViewLonghands;
use crate::css::style_value::{
    BorderRadiusPayload, CalculatedPayload, ColorSchemePayload, GridTemplateAreaPayload, GridTrackPlacementPayload,
    GridTrackSizeListPayload, PositionPayload, RatioPayload, RectPayload, ScrollbarColorPayload, ShadowPayload,
    TransformationPayload,
};
use ak::math;
use std::collections::HashMap;
use std::ffi::c_void;

use crate::css::animated_overlay::AnimatedOverlay;
use crate::css::calc::{resolve_calculated_flex_without_context, resolve_calculated_integer_without_context};
use crate::css::color_resolution::{ColorResolutionInput, PREFERRED_COLOR_SCHEME_DARK, Rgba, accent_color, to_color};
use crate::css::computed_value_types::{
    AnchorValues, AnimationValues, BackgroundValues, BorderValues, ComputedClipEdge, ComputedColorOrAuto,
    ComputedCursor, ComputedFilter, ComputedFilterOperation, ComputedGridArea, ComputedGridPlacement,
    ComputedGridPlacementKind, ComputedGridTrackBreadth, ComputedGridTrackEntry, ComputedGridTrackEntryKind,
    ComputedGridTrackList, ComputedLengthBox, ComputedLengthPercentageOrAuto, ComputedOverflowClipMargin,
    ComputedOverflowClipMarginSide, ComputedPositionTryFallback, ComputedResolvedTransform, ComputedScrollbarColor,
    ComputedShadow, ComputedSize, ComputedSizeKind, ComputedStyleValueHandle, ComputedSvgDash, ComputedSvgPaint,
    ComputedTextIndent, ComputedTextUnderlineOffset, ComputedTextUnderlinePosition, ContentValues, EffectsValues,
    FontValues, GRID_NO_INDEX, GridValues, InheritedListTableValues, InheritedSVGValues, InheritedTextValues,
    InheritedUIValues, MaskValues, MiscInteractionValues, MiscLayoutValues, RetainedComputedCursorList,
    RetainedComputedFilterOperationList, RetainedComputedResolvedTransformList, RetainedComputedShadowList,
    RetainedComputedSvgDashList, RetainedGridAreaList, RetainedGridNameIndexList, RetainedGridTrackEntryList,
    RetainedPositionAreaList, RetainedPositionTryFallbackList, RetainedWillChangePropertyList, SVGResetValues,
    StyleColor, TransformValues,
};
use crate::css::computed_values::{
    GroupFieldKind, GroupReads, GroupShares, GroupValueEntry, GroupValueLayout, GroupValues, LonghandID,
    MAX_GROUP_FIELD_COUNT, build_sizing_group, build_style_group, build_svg_reset_group_payload,
    group_field_descriptors, rust_build_alignment_group, rust_build_grid_group, rust_build_surround_group,
    rust_build_text_reset_group,
};
use crate::css::css_enums::keyword;
use crate::css::css_pixels::CssPixels;
use crate::css::property_metadata::property_id;
use crate::css::retained_fly_string::{RetainedUtf16FlyString, RetainedUtf16FlyStringList};
use crate::css::style_value::{GridTrackEntryKind, RetainedGridTrackEntry, RetainedStyleValueData, StyleValueData};

/// The style groups' indices, which `computed_value_types` exports to the host: the C++
/// StyleGroupIndex numbering, which the host static-asserts these against.
pub(crate) mod group_index {
    pub const INHERITED_LIST_TABLE: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_LIST_TABLE;
    pub const INHERITED_UI: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_UI;
    pub const INHERITED_SVG: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_SVG;
    pub const INHERITED_TEXT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_TEXT;
    pub const FONT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_FONT;
    pub const ANIMATION: usize = 5;
    pub const SVG_RESET: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_SVG_RESET;
    pub const GRID: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_GRID;
    pub const ANCHOR: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_ANCHOR;
    pub const EFFECTS: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_EFFECTS;
    pub const MASK: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_MASK;
    pub const TEXT_RESET: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_TEXT_RESET;
    pub const CONTENT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_CONTENT;
    pub const TRANSFORM: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_TRANSFORM;
    pub const BACKGROUND: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_BACKGROUND;
    pub const BORDER: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_BORDER;
    pub const ALIGNMENT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_ALIGNMENT;
    pub const MISC_LAYOUT: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_MISC_LAYOUT;
    pub const MISC_INTERACTION: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_MISC_INTERACTION;
    pub const SIZING: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_SIZING;
    pub const SURROUND: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_SURROUND;
    pub const BOX: usize = crate::css::computed_value_types::STYLE_GROUP_INDEX_BOX;
    pub const COUNT: usize = 22;
}

/// What one table-driven group build reads beside the table: the color resolution input (whose current color is the
/// element's own resolved color), the used color-scheme, the animated overlay over the table, and platform font data.
pub(crate) struct GroupBuildInputs<'a> {
    pub color_input: &'a ColorResolutionInput<'a>,
    /// The used color-scheme code (PreferredColorScheme underlying value).
    pub used_color_scheme: u8,
    /// The raw bits of the Display value before the box type transformation, which the table does not hold.
    pub box_display_before_transformation_raw: u32,
    pub font: Option<&'a FfiFontGroupBuildInputs>,
    pub defaults: &'a crate::css::computed_values::DefaultGroups,
}

/// Platform font resources and derived facts supplied to the Rust-owned font
/// group builder. The pointers borrow objects the caller keeps live for the
/// call; the built group retains the cascade list itself.
#[repr(C)]
pub struct FfiFontGroupBuildInputs {
    pub font_size_raw: i32,
    /// The computed font size, unrounded, which the lengths relative to it scale.
    pub font_size: f64,
    pub line_height_used_raw: i32,
    pub font_variant_emoji: u8,
    pub font_ascent: f32,
    pub font_descent: f32,
    pub font_x_height: f32,
    pub font_cap_height: f32,
    pub font_zero_advance: f32,
    pub first_available_font: *const c_void,
    pub font_cascade_list: *const c_void,
    pub font_weight: f64,
    pub font_width: f64,
    pub math_shift: u8,
    pub math_style: u8,
    pub math_depth: i32,
}

/// Where a group build reads an element's computed longhand values from: exactly the values
/// `ComputedStyleWorkingSet::property()` returns during a group build.
pub(crate) enum LonghandSource<'a> {
    /// An element's longhands, of a table or of a record, joined with their effective-value
    /// overrides: the animated overlay where its values win, and the recorded
    /// currentcolor-dependent specified values.
    Longhands {
        longhands: ViewLonghands<'a>,
        animated_overlay: Option<&'a AnimatedOverlay>,
    },
    /// The element's computed values by group, before its groups are built.
    Values {
        values: &'a GroupValues<'a>,
        /// Where known, the values the build may read, which its group's cache key covers: a read
        /// of another value aborts.
        reads: Option<&'a GroupReads>,
    },
}

/// The gathered entries of one group, which has at most `MAX_GROUP_FIELD_COUNT` fields.
type GroupValueEntries<'a> = smallvec::SmallVec<[GroupValueEntry<'a>; MAX_GROUP_FIELD_COUNT]>;

impl<'a> LonghandSource<'a> {
    fn handle(&self, property_id: u16) -> &'a RetainedStyleValueData {
        match self {
            Self::Longhands {
                longhands,
                animated_overlay,
            } => longhands.effective_value(*animated_overlay, property_id),
            Self::Values { values, reads } => {
                // NB: A build reads the element's color to resolve `currentcolor`, which the key
                //     covers as the resolved current color.
                if let Some(reads) = reads
                    && property_id != property_id::COLOR
                    && !GroupValueLayout::reads(reads, GroupValueLayout::get().place(LonghandID::new(property_id)))
                {
                    eprintln!("a style group build reads longhand {property_id}, which its key does not cover");
                    std::process::abort();
                }
                values.effective_value(property_id)
            }
        }
    }

    fn value(&self, property_id: u16) -> Option<&'a StyleValueData> {
        self.handle(property_id).optional_data()
    }

    fn animated_overlay(&self) -> Option<&'a AnimatedOverlay> {
        match self {
            Self::Longhands { animated_overlay, .. } => *animated_overlay,
            Self::Values { .. } => None,
        }
    }

    fn effective_zoom(&self) -> f32 {
        match self {
            Self::Longhands { longhands, .. } => longhands.effective_zoom(),
            Self::Values { values, .. } => values.facts().effective_zoom(),
        }
    }

    /// What a style holding these values holds as bits beside its groups.
    pub(crate) fn style_bits(&self) -> crate::css::computed_value_types::StyleBits {
        match self {
            Self::Longhands { .. } => crate::css::computed_value_types::StyleBits::of_values(
                |property| self.handle(property),
                self.effective_zoom(),
            ),
            Self::Values { values, .. } => values.style_bits(),
        }
    }

    fn display_before_box_type_transformation(&self) -> u32 {
        match self {
            Self::Longhands { longhands, .. } => longhands.display_before_box_type_transformation(),
            Self::Values { values, .. } => values.facts().display_before_box_type_transformation(),
        }
    }

    fn effective_color_scheme(&self) -> i16 {
        match self {
            Self::Longhands { longhands, .. } => longhands.effective_color_scheme(),
            Self::Values { values, .. } => values.facts().effective_color_scheme(),
        }
    }

    /// https://drafts.csswg.org/css-ui/#appearance-disabling-properties
    /// Whether an author declaration disables the element's native appearance.
    fn native_appearance_disabled(&self) -> bool {
        match self {
            Self::Longhands { longhands, .. } => {
                longhands.dependency_flags() & crate::css::computed_longhand_table::NATIVE_APPEARANCE_DISABLED != 0
            }
            Self::Values { values, .. } => values.facts().native_appearance_disabled(),
        }
    }

    /// The physical sides whose margins the user agent's style sheet sets, in a quirks-mode document, and no animation
    /// of the element overrides.
    fn user_agent_margin_sides(&self) -> u8 {
        match self {
            Self::Longhands {
                longhands,
                animated_overlay,
            } => {
                let sides = longhands.user_agent_margin_sides();
                let Some(overlay) = animated_overlay.filter(|_| sides != 0) else {
                    return sides;
                };
                let (writing_mode, direction) = crate::css::style_compute::writing_mode_and_direction_of(
                    Some(self.handle(property_id::WRITING_MODE)),
                    Some(self.handle(property_id::DIRECTION)),
                );
                sides & !margin_sides_animated_by(overlay, writing_mode, direction)
            }
            Self::Values { values, .. } => values.facts().user_agent_margin_sides(),
        }
    }
}

/// Whether `property` is a margin longhand, physical or flow-relative.
pub(crate) fn is_margin_longhand(property: u16) -> bool {
    matches!(
        property,
        property_id::MARGIN_TOP
            | property_id::MARGIN_RIGHT
            | property_id::MARGIN_BOTTOM
            | property_id::MARGIN_LEFT
            | property_id::MARGIN_BLOCK_START
            | property_id::MARGIN_BLOCK_END
            | property_id::MARGIN_INLINE_START
            | property_id::MARGIN_INLINE_END
    )
}

/// The physical sides, as `user_agent_margin_side` bits, whose margins `overlay` animates, itself or through their
/// flow-relative counterpart in the given writing mode and direction.
fn margin_sides_animated_by(overlay: &AnimatedOverlay, writing_mode: u8, direction: u8) -> u8 {
    use crate::css::computed_value_types::user_agent_margin_side as side;
    [
        (property_id::MARGIN_TOP, side::TOP),
        (property_id::MARGIN_RIGHT, side::RIGHT),
        (property_id::MARGIN_BOTTOM, side::BOTTOM),
        (property_id::MARGIN_LEFT, side::LEFT),
    ]
    .into_iter()
    .filter(|&(physical, _)| {
        let flow_relative = crate::css::style_compute::map_physical_to_logical_alias(physical, writing_mode, direction);
        overlay.get(physical).is_some() || overlay.get(flow_relative).is_some()
    })
    .fold(0, |sides, (_, bit)| sides | bit)
}

/// The C++ Color::value() bit layout.
fn packed_color(color: Rgba) -> u32 {
    (u32::from(color.a) << 24) | (u32::from(color.r) << 16) | (u32::from(color.g) << 8) | u32::from(color.b)
}

/// The groups that hold plain `currentcolor` as a [`StyleColor`] wherever they hold a color, which
/// depend on the element's color only through a value whose color is more than plain `currentcolor`.
pub(crate) const GROUPS_HOLDING_CURRENT_COLOR_FOR_THEIR_READER: u32 = (1 << group_index::BORDER)
    | (1 << group_index::MISC_LAYOUT)
    | (1 << group_index::TEXT_RESET)
    | (1 << group_index::BACKGROUND)
    | (1 << group_index::SVG_RESET)
    | (1 << group_index::INHERITED_UI)
    | (1 << group_index::INHERITED_SVG)
    | (1 << group_index::EFFECTS);

/// Whether a group holds `property`'s value `data` as `currentcolor` for its reader to resolve,
/// rather than resolving it against the element's color.
pub(crate) fn group_holds_current_color_for_its_reader(property: u16, data: Option<&StyleValueData>) -> bool {
    // A shadow without a color is `currentcolor` too, and a layer whose color reads no
    // `currentcolor` reads nothing of the element's color.
    if property == property_id::BOX_SHADOW {
        return match data {
            Some(StyleValueData::ValueList { values, .. }) => {
                values.as_slice().iter().all(|layer| match layer.data() {
                    StyleValueData::Shadow(shadow) => match shadow.color.optional_data() {
                        None => true,
                        Some(StyleValueData::Keyword { keyword }) if *keyword == keyword::CURRENTCOLOR => true,
                        Some(color) => !crate::css::style_value::value_depends_on_current_color(color),
                    },
                    _ => false,
                })
            }
            _ => false,
        };
    }
    matches!(
        property,
        property_id::BORDER_TOP_COLOR
            | property_id::BORDER_RIGHT_COLOR
            | property_id::BORDER_BOTTOM_COLOR
            | property_id::BORDER_LEFT_COLOR
            | property_id::OUTLINE_COLOR
            | property_id::COLUMN_RULE_COLOR
            | property_id::TEXT_DECORATION_COLOR
            | property_id::BACKGROUND_COLOR
            | property_id::STOP_COLOR
            | property_id::FLOOD_COLOR
            | property_id::CARET_COLOR
            | property_id::ACCENT_COLOR
            | property_id::FILL
            | property_id::STROKE
    ) && matches!(data, Some(StyleValueData::Keyword { keyword }) if *keyword == keyword::CURRENTCOLOR)
}

/// The groups an element's color reaches through the colors it inherits, which it holds no record of having
/// declared: a color reading `currentcolor` that is more than plain `currentcolor` resolves against the color of the
/// element holding it, not the parent's. The other inherited groups hold the color itself, and rebuild with it.
pub(crate) fn groups_reading_current_color_through_inherited_values<'a>(
    value: impl Fn(u16) -> Option<&'a StyleValueData>,
) -> u32 {
    let reads_current_color = |property: u16| {
        value(property).is_some_and(|data| {
            crate::css::style_value::value_depends_on_current_color(data)
                && !group_holds_current_color_for_its_reader(property, Some(data))
        })
    };
    let mut groups = 0;
    if [
        property_id::CARET_COLOR,
        property_id::ACCENT_COLOR,
        property_id::SCROLLBAR_COLOR,
    ]
    .into_iter()
    .any(reads_current_color)
    {
        groups |= 1 << group_index::INHERITED_UI;
    }
    if [property_id::FILL, property_id::STROKE]
        .into_iter()
        .any(reads_current_color)
    {
        groups |= 1 << group_index::INHERITED_SVG;
    }
    groups
}

/// The computed color `data` is, as a group holds it: `currentcolor` stays for the group's reader
/// to resolve against the element's color.
fn style_color(data: &StyleValueData, input: &ColorResolutionInput) -> Option<StyleColor> {
    if let StyleValueData::Keyword { keyword: code } = data
        && *code == keyword::CURRENTCOLOR
    {
        return Some(StyleColor::CURRENT_COLOR);
    }
    to_color(data, input).map(|color| StyleColor::rgba(packed_color(color)))
}

/// The resolved color the C++ sidecar loops produced for one color-kind
/// field, or None when the value needs the C++ path.
fn resolved_color(input: &ColorResolutionInput, property: u16, data: &StyleValueData) -> Option<u32> {
    // The element's own color is resolved by the caller against the incoming
    // context (whose currentcolor is the parent's), not re-resolved here.
    if property == property_id::COLOR {
        return input.current_color.map(packed_color);
    }
    if let StyleValueData::Keyword { keyword: code } = data {
        // An auto accent-color is the system accent color for the used scheme.
        if property == property_id::ACCENT_COLOR && *code == keyword::AUTO {
            return Some(packed_color(accent_color(
                input.scheme == Some(PREFERRED_COLOR_SCHEME_DARK),
            )));
        }
    }
    to_color(data, input).map(packed_color)
}

/// The resolved number for opacity-normalized and superellipse fields, whose
/// computed values wrap an absolutized plain number - or, for superellipse
/// corner shapes, a calculation resolvable without context, matching the C++
/// number_from_style_value the population path used.
fn resolved_wrapped_number(data: &StyleValueData) -> Option<f64> {
    let inner = match data {
        StyleValueData::OpacityValue { value } => value.data(),
        StyleValueData::Superellipse { parameter } => parameter.data(),
        _ => return None,
    };
    match inner {
        StyleValueData::Number { value } => Some(*value),
        StyleValueData::Calculated { .. } => crate::css::calc::resolve_calculated_number_without_context(inner),
        _ => None,
    }
}

/// Gathers one group's descriptor entries from the table, resolving the
/// color and number sidecars the descriptor kinds ask for.
fn gather_group_entries<'a>(
    group_index: usize,
    values: &LonghandSource<'a>,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
) -> Option<GroupValueEntries<'a>> {
    let descriptors = group_field_descriptors(group_index);
    assert!(descriptors.len() <= MAX_GROUP_FIELD_COUNT);
    let mut entries = GroupValueEntries::new();
    for descriptor in descriptors {
        let handle = values.handle(descriptor.property_id);
        let data = handle.optional_data()?;
        let mut entry = GroupValueEntry {
            data: handle,
            resolved_color: 0,
            has_resolved_color: false,
            resolved_number: 0.0,
            has_resolved_number: false,
        };
        match descriptor.kind {
            GroupFieldKind::Color | GroupFieldKind::HeldColor | GroupFieldKind::HeldColorOrKeyword(_) => {
                if let Some(color) = resolved_color(input, descriptor.property_id, data) {
                    entry.resolved_color = color;
                    entry.has_resolved_color = true;
                }
            }
            GroupFieldKind::ResolvedF32 | GroupFieldKind::ResolvedF64 => {
                if let Some(number) = resolved_wrapped_number(data) {
                    entry.resolved_number = number;
                    entry.has_resolved_number = true;
                }
            }
            GroupFieldKind::ResolvedU8 => {
                // The only resolved-u8 field is the used color-scheme.
                entry.resolved_number = f64::from(used_color_scheme);
                entry.has_resolved_number = true;
            }
            _ => {}
        }
        entries.push(entry);
    }
    Some(entries)
}

/// Builds one descriptor-driven group through `build_style_group`,
/// gathering the entries from the table instead of a marshalled span.
fn build_generic_group(
    group_index: usize,
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index, values, input, used_color_scheme) else {
        return std::ptr::null();
    };
    build_style_group(group_index, &entries, parent)
}

fn build_surround_group(values: &LonghandSource, parent: GroupShares<'_>) -> *const c_void {
    let position_anchor = match values.value(property_id::POSITION_ANCHOR) {
        Some(StyleValueData::CustomIdent { .. }) => Some(values.handle(property_id::POSITION_ANCHOR)),
        _ => None,
    };
    rust_build_surround_group(
        group_index::SURROUND,
        values.handle(property_id::TOP),
        values.handle(property_id::RIGHT),
        values.handle(property_id::BOTTOM),
        values.handle(property_id::LEFT),
        values.handle(property_id::MARGIN_TOP),
        values.handle(property_id::MARGIN_RIGHT),
        values.handle(property_id::MARGIN_BOTTOM),
        values.handle(property_id::MARGIN_LEFT),
        values.handle(property_id::PADDING_TOP),
        values.handle(property_id::PADDING_RIGHT),
        values.handle(property_id::PADDING_BOTTOM),
        values.handle(property_id::PADDING_LEFT),
        position_anchor,
        parent,
    )
}

fn build_alignment_group(values: &LonghandSource, parent: GroupShares<'_>) -> *const c_void {
    let number = |property: u16| required_number(values.value(property).expect("the table holds the flex factor"));
    let flex_grow = number(property_id::FLEX_GROW);
    let flex_shrink = number(property_id::FLEX_SHRINK);
    let webkit_box_flex = number(property_id::_WEBKIT_BOX_FLEX);
    let order = required_integer(values.value(property_id::ORDER).expect("the table holds order"));
    let webkit_box_ordinal_group = required_integer(
        values
            .value(property_id::_WEBKIT_BOX_ORDINAL_GROUP)
            .expect("the table holds the ordinal group"),
    );
    rust_build_alignment_group(
        group_index::ALIGNMENT,
        values.handle(property_id::_WEBKIT_BOX_ORIENT),
        values.handle(property_id::_WEBKIT_BOX_ALIGN),
        values.handle(property_id::_WEBKIT_BOX_PACK),
        values.handle(property_id::FLEX_DIRECTION),
        values.handle(property_id::FLEX_WRAP),
        values.handle(property_id::FLEX_BASIS),
        flex_grow,
        flex_shrink,
        webkit_box_flex,
        order,
        webkit_box_ordinal_group,
        values.handle(property_id::ALIGN_CONTENT),
        values.handle(property_id::ALIGN_ITEMS),
        values.handle(property_id::ALIGN_SELF),
        values.handle(property_id::JUSTIFY_CONTENT),
        values.handle(property_id::JUSTIFY_ITEMS),
        values.handle(property_id::JUSTIFY_SELF),
        values.handle(property_id::COLUMN_GAP),
        values.handle(property_id::ROW_GAP),
        parent,
    )
}

fn build_svg_reset_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    parent: GroupShares<'_>,
) -> *const c_void {
    let color = |property: u16| {
        style_color(
            values.value(property).expect("the table holds the computed color"),
            input,
        )
        .expect("a computed SVG reset color resolves in the Rust color context")
    };
    let opacity = |property: u16| {
        resolved_wrapped_number(values.value(property).expect("the table holds the computed opacity"))
            .expect("a computed SVG reset opacity resolves")
    };
    let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
    let alignment_baseline = values
        .value(property_id::ALIGNMENT_BASELINE)
        .and_then(keyword_of)
        .and_then(crate::css::css_enums::keyword_to_baseline_metric);
    let built = SVGResetValues {
        cx: retained(property_id::CX),
        cy: retained(property_id::CY),
        d: retained(property_id::D),
        r: retained(property_id::R),
        rx: ComputedLengthPercentageOrAuto::from_data(values.handle(property_id::RX)),
        ry: ComputedLengthPercentageOrAuto::from_data(values.handle(property_id::RY)),
        x: retained(property_id::X),
        y: retained(property_id::Y),
        stop_color: color(property_id::STOP_COLOR),
        stop_opacity: opacity(property_id::STOP_OPACITY) as f32,
        flood_color: color(property_id::FLOOD_COLOR),
        flood_opacity: opacity(property_id::FLOOD_OPACITY) as f32,
        vector_effect: required_keyword_code(
            values,
            property_id::VECTOR_EFFECT,
            crate::css::css_enums::keyword_to_vector_effect,
        ),
        has_alignment_baseline: alignment_baseline.is_some(),
        alignment_baseline: alignment_baseline.unwrap_or(0),
    };
    build_svg_reset_group_payload(group_index::SVG_RESET, built, parent)
}

/// The name table, name-index spans, track entries and named areas one grid
/// group build accumulates: the Rust twin of the GridGroupBuilderArena the
/// C++ marshalled build used, interning by raw fly-string word since fly
/// strings are interned.
struct GridGroupArena {
    names: Vec<RetainedUtf16FlyString>,
    indices_by_raw: HashMap<usize, u32>,
    name_indices: Vec<u32>,
    entries: Vec<ComputedGridTrackEntry>,
    areas: Vec<ComputedGridArea>,
}

impl GridGroupArena {
    fn new() -> Self {
        Self {
            names: Vec::new(),
            indices_by_raw: HashMap::new(),
            name_indices: Vec::new(),
            entries: Vec::new(),
            areas: Vec::new(),
        }
    }

    /// Interns one name, taking ownership of the passed reference; a
    /// duplicate drops its surplus reference on return.
    fn intern_retained(&mut self, name: RetainedUtf16FlyString) -> u32 {
        let raw = name.raw();
        assert_ne!(raw, 0, "cannot intern the no-name sentinel");
        if let Some(index) = self.indices_by_raw.get(&raw) {
            return *index;
        }
        let index = self.names.len() as u32;
        self.names.push(name);
        self.indices_by_raw.insert(raw, index);
        index
    }

    fn intern_borrowed(&mut self, name: &crate::css::css_string::CssString) -> u32 {
        self.intern_retained(name.to_fly_string())
    }
}

fn auto_grid_track_breadth() -> ComputedGridTrackBreadth {
    ComputedGridTrackBreadth {
        is_flex: false,
        flex_factor: 0.0,
        size: ComputedSize::keyword(ComputedSizeKind::Auto),
    }
}

/// One track breadth from its computed grid-size value, with the C++
/// GridSize lowering: flex values - including calc that resolves to flex -
/// carry their fr factor, everything else maps through the shared computed
/// size representation.
fn grid_track_breadth(handle: &RetainedStyleValueData) -> ComputedGridTrackBreadth {
    let data = handle.data();
    let flex_factor = match data {
        StyleValueData::Flex { value, unit } => {
            Some(value * crate::css::calc::FLEX_UNIT_CANONICAL_RATIOS[*unit as usize])
        }
        StyleValueData::Calculated { .. } => resolve_calculated_flex_without_context(data),
        _ => None,
    };
    if let Some(flex_factor) = flex_factor {
        return ComputedGridTrackBreadth {
            is_flex: true,
            flex_factor,
            size: ComputedSize::keyword(ComputedSizeKind::Auto),
        };
    }
    let size = ComputedSize::from_data(handle);
    assert!(size.kind != ComputedSizeKind::None, "a grid size cannot be none");
    ComputedGridTrackBreadth {
        is_flex: false,
        flex_factor: 0.0,
        size,
    }
}

/// The C++ int_from_style_value: a plain integer, or a calculation that must
/// resolve to one with no external context.
fn grid_integer(data: &StyleValueData) -> Option<i32> {
    match data {
        StyleValueData::Integer { value } => Some(*value),
        StyleValueData::Calculated { .. } => resolve_calculated_integer_without_context(data),
        _ => None,
    }
}

fn build_grid_track_list(
    is_subgrid: bool,
    preserves_line_name_sets: bool,
    source_entries: &[RetainedGridTrackEntry],
    arena: &mut GridGroupArena,
) -> Option<ComputedGridTrackList> {
    let mut result = ComputedGridTrackList {
        is_subgrid,
        preserves_line_name_sets,
        first_entry: GRID_NO_INDEX,
    };
    let mut previous_entry = GRID_NO_INDEX;

    for source in source_entries {
        let entry_index = arena.entries.len() as u32;
        arena.entries.push(ComputedGridTrackEntry {
            kind: ComputedGridTrackEntryKind::LineNames as u8,
            next_sibling: GRID_NO_INDEX,
            name_index_start: 0,
            name_index_count: 0,
            size: auto_grid_track_breadth(),
            min_size: auto_grid_track_breadth(),
            max_size: auto_grid_track_breadth(),
            repeat_type: 0,
            repeat_count: 0,
            repeat_list: ComputedGridTrackList {
                is_subgrid: false,
                preserves_line_name_sets: false,
                first_entry: GRID_NO_INDEX,
            },
        });

        if result.first_entry == GRID_NO_INDEX {
            result.first_entry = entry_index;
        }
        if previous_entry != GRID_NO_INDEX {
            arena.entries[previous_entry as usize].next_sibling = entry_index;
        }
        previous_entry = entry_index;

        match source.kind {
            GridTrackEntryKind::LineNames => {
                let name_index_start = arena.name_indices.len();
                for name in source.names.as_slice() {
                    let index = arena.intern_borrowed(name);
                    arena.name_indices.push(index);
                }
                let entry = &mut arena.entries[entry_index as usize];
                entry.name_index_start = name_index_start;
                entry.name_index_count = arena.name_indices.len() - name_index_start;
            }
            GridTrackEntryKind::Size => {
                let size = grid_track_breadth(&source.size_value);
                let entry = &mut arena.entries[entry_index as usize];
                entry.kind = ComputedGridTrackEntryKind::TrackSize as u8;
                entry.size = size;
            }
            GridTrackEntryKind::MinMax => {
                let min_size = grid_track_breadth(&source.min_value);
                let max_size = grid_track_breadth(&source.max_value);
                let entry = &mut arena.entries[entry_index as usize];
                entry.kind = ComputedGridTrackEntryKind::MinMax as u8;
                entry.min_size = min_size;
                entry.max_size = max_size;
            }
            GridTrackEntryKind::Repeat => {
                // The repeat-type codes are pinned by static asserts beside
                // the C++ GridRepeatType enum: auto-fit 0, auto-fill 1,
                // fixed 2. Only a fixed repeat carries a count.
                const GRID_REPEAT_TYPE_FIXED: u8 = 2;
                let repeat_list = build_grid_track_list(
                    source.repeat_is_subgrid,
                    source.repeat_preserve_line_name_sets,
                    source.repeat_entries(),
                    arena,
                )?;
                let repeat_count = if source.repeat_type == GRID_REPEAT_TYPE_FIXED {
                    grid_integer(source.repeat_count.data())? as usize
                } else {
                    0
                };
                let entry = &mut arena.entries[entry_index as usize];
                entry.kind = ComputedGridTrackEntryKind::Repeat as u8;
                entry.repeat_type = source.repeat_type;
                entry.repeat_count = repeat_count;
                entry.repeat_list = repeat_list;
            }
        }
    }
    Some(result)
}

fn build_grid_placement(data: &StyleValueData, arena: &mut GridGroupArena) -> Option<ComputedGridPlacement> {
    let StyleValueData::GridTrackPlacement(grid_track_placement_payload) = data else {
        return None;
    };
    let GridTrackPlacementPayload {
        kind,
        value,
        has_name,
        name,
        implicit_start_name,
        implicit_end_name,
    } = &**grid_track_placement_payload;
    let mut result = ComputedGridPlacement {
        kind: ComputedGridPlacementKind::Auto as u8,
        has_line_number: false,
        line_number: 0,
        has_name: false,
        name_index: GRID_NO_INDEX,
        implicit_start_name_index: GRID_NO_INDEX,
        implicit_end_name_index: GRID_NO_INDEX,
    };
    match kind {
        0 => {}
        1 => {
            result.kind = ComputedGridPlacementKind::Span as u8;
            result.has_line_number = true;
            result.line_number = grid_integer(value.optional_data()?)?;
            if *has_name {
                result.has_name = true;
                result.name_index = arena.intern_borrowed(name);
            }
        }
        _ => {
            result.kind = ComputedGridPlacementKind::Line as u8;
            if let Some(line_number) = value.optional_data() {
                result.has_line_number = true;
                result.line_number = grid_integer(line_number)?;
            }
            if *has_name {
                result.has_name = true;
                result.name_index = arena.intern_borrowed(name);
                result.implicit_start_name_index = arena.intern_borrowed(implicit_start_name);
                result.implicit_end_name_index = arena.intern_borrowed(implicit_end_name);
            }
        }
    }
    Some(result)
}

/// Builds the grid group payload from the table's computed track lists,
/// template areas and placements, in the C++ marshalled build's interning
/// order so the arena layout stays deterministic.
fn build_grid_group(values: &LonghandSource, parent: GroupShares<'_>) -> *const c_void {
    // An all-initial grid shares the default payload directly, with
    // its empty style value handles, exactly as the descriptor constraints
    // used to. A value is initial by what it holds, so that equal tables build
    // equal payloads.
    const GRID_PROPERTIES: [u16; 9] = [
        property_id::GRID_TEMPLATE_COLUMNS,
        property_id::GRID_TEMPLATE_ROWS,
        property_id::GRID_AUTO_COLUMNS,
        property_id::GRID_AUTO_ROWS,
        property_id::GRID_TEMPLATE_AREAS,
        property_id::GRID_COLUMN_START,
        property_id::GRID_COLUMN_END,
        property_id::GRID_ROW_START,
        property_id::GRID_ROW_END,
    ];
    let all_initial = GRID_PROPERTIES.iter().all(|property| {
        crate::css::style_value::retained_style_values_equal(
            values.handle(*property),
            crate::css::style_compute::initial_value_handle(*property),
        )
    });
    if all_initial {
        return crate::css::computed_values::share_default_group_payload(group_index::GRID, parent);
    }

    let mut arena = GridGroupArena::new();

    let track_list = |arena: &mut GridGroupArena, property: u16| -> Option<ComputedGridTrackList> {
        match values.value(property)? {
            StyleValueData::GridTrackSizeList(grid_track_size_list_payload) => {
                let GridTrackSizeListPayload {
                    is_subgrid,
                    preserve_line_name_sets,
                    entries,
                } = &**grid_track_size_list_payload;
                build_grid_track_list(*is_subgrid, *preserve_line_name_sets, entries.as_slice(), arena)
            }
            _ => None,
        }
    };
    let Some(template_columns) = track_list(&mut arena, property_id::GRID_TEMPLATE_COLUMNS) else {
        return std::ptr::null();
    };
    let Some(template_rows) = track_list(&mut arena, property_id::GRID_TEMPLATE_ROWS) else {
        return std::ptr::null();
    };
    let Some(auto_columns) = track_list(&mut arena, property_id::GRID_AUTO_COLUMNS) else {
        return std::ptr::null();
    };
    let Some(auto_rows) = track_list(&mut arena, property_id::GRID_AUTO_ROWS) else {
        return std::ptr::null();
    };

    let Some(StyleValueData::GridTemplateArea(grid_template_area_payload)) =
        values.value(property_id::GRID_TEMPLATE_AREAS)
    else {
        return std::ptr::null();
    };
    let GridTemplateAreaPayload { grid_areas, .. } = &**grid_template_area_payload;
    for area in grid_areas.as_slice() {
        let [row_start, row_end, column_start, column_end] = area.grid_lines();
        let name_index = arena.intern_borrowed(area.name());
        let implicit_start_name_index = arena.intern_borrowed(area.implicit_start_name());
        let implicit_end_name_index = arena.intern_borrowed(area.implicit_end_name());
        arena.areas.push(ComputedGridArea {
            name_index,
            implicit_start_name_index,
            implicit_end_name_index,
            row_start,
            row_end,
            column_start,
            column_end,
        });
    }

    let placement = |arena: &mut GridGroupArena, property: u16| -> Option<ComputedGridPlacement> {
        build_grid_placement(values.value(property)?, arena)
    };
    let Some(column_start) = placement(&mut arena, property_id::GRID_COLUMN_START) else {
        return std::ptr::null();
    };
    let Some(column_end) = placement(&mut arena, property_id::GRID_COLUMN_END) else {
        return std::ptr::null();
    };
    let Some(row_start) = placement(&mut arena, property_id::GRID_ROW_START) else {
        return std::ptr::null();
    };
    let Some(row_end) = placement(&mut arena, property_id::GRID_ROW_END) else {
        return std::ptr::null();
    };

    let retained_slot = |property: u16| ComputedStyleValueHandle::from_retained(values.handle(property));
    let built = GridValues {
        names: RetainedUtf16FlyStringList::from_vec(arena.names),
        name_indices: RetainedGridNameIndexList::from_vec(arena.name_indices),
        entries: RetainedGridTrackEntryList::from_vec(arena.entries),
        areas: RetainedGridAreaList::from_vec(arena.areas),
        template_columns,
        template_rows,
        auto_columns,
        auto_rows,
        column_start,
        column_end,
        row_start,
        row_end,
        grid_template_columns_style_value: retained_slot(property_id::GRID_TEMPLATE_COLUMNS),
        grid_template_rows_style_value: retained_slot(property_id::GRID_TEMPLATE_ROWS),
        grid_auto_columns_style_value: retained_slot(property_id::GRID_AUTO_COLUMNS),
        grid_auto_rows_style_value: retained_slot(property_id::GRID_AUTO_ROWS),
        grid_template_areas_style_value: retained_slot(property_id::GRID_TEMPLATE_AREAS),
        grid_column_start_style_value: retained_slot(property_id::GRID_COLUMN_START),
        grid_column_end_style_value: retained_slot(property_id::GRID_COLUMN_END),
        grid_row_start_style_value: retained_slot(property_id::GRID_ROW_START),
        grid_row_end_style_value: retained_slot(property_id::GRID_ROW_END),
        fit_tolerance_style_value: retained_slot(property_id::FIT_TOLERANCE),
    };
    rust_build_grid_group(group_index::GRID, built, parent)
}

// --- Transform and effects lowering ---------------------------------------
//
// The paint-ready forms the C++ fallback used to build from wrapper reads -
// baked matrices, resolved filter operations, shadow data - are computed here
// from the table slots. The members that genuinely need C++ (style value
// wrappers, LengthPercentage slots for reference-box-dependent percentages)
// travel as retained handles in an assembly struct that a registered C++
// assembler transcribes into the payload.

/// The C++ TransformFunctionParameterType codes the generated parameter
/// table uses.
pub(crate) const TRANSFORM_PARAMETER_ANGLE: u8 = 0;
pub(crate) const TRANSFORM_PARAMETER_LENGTH: u8 = 1;
pub(crate) const TRANSFORM_PARAMETER_LENGTH_NONE: u8 = 2;
pub(crate) const TRANSFORM_PARAMETER_LENGTH_PERCENTAGE: u8 = 3;
pub(crate) const TRANSFORM_PARAMETER_NUMBER: u8 = 4;
pub(crate) const TRANSFORM_PARAMETER_NUMBER_PERCENTAGE: u8 = 5;

pub(crate) fn angle_unit_index(name: &str) -> usize {
    crate::css::calc::ANGLE_UNIT_NAMES
        .iter()
        .position(|unit| *unit == name)
        .expect("the angle unit table names every unit")
}

/// The C++ Angle::to_radians: the ratio between the value's unit and rad,
/// times the value.
pub(crate) fn angle_value_to_radians(value: f64, unit: u8) -> f64 {
    let rad = angle_unit_index("rad");
    if unit as usize == rad {
        return value;
    }
    (crate::css::calc::ANGLE_UNIT_CANONICAL_RATIOS[unit as usize] / crate::css::calc::ANGLE_UNIT_CANONICAL_RATIOS[rad])
        * value
}

/// An angle in radians, with the C++ conversion order: calc resolves to canonical degrees first.
/// None for a value that is not an angle or a calculation that resolves without context.
pub(crate) fn angle_radians(data: &StyleValueData) -> Option<f64> {
    match data {
        StyleValueData::Angle { value, unit } => Some(angle_value_to_radians(*value, *unit)),
        StyleValueData::Calculated { .. } => {
            let degrees = crate::css::calc::resolve_calculated_angle_without_context(data)?;
            Some(angle_value_to_radians(degrees, angle_unit_index("deg") as u8))
        }
        _ => None,
    }
}

/// An angle-typed transform argument in radians.
pub(crate) fn transform_angle_radians(data: &StyleValueData) -> f64 {
    if let StyleValueData::Angle { value, unit } = data {
        let period = match crate::css::calc::ANGLE_UNIT_NAMES[*unit as usize] {
            "deg" => 360.0,
            "grad" => 400.0,
            "rad" => std::f64::consts::TAU,
            "turn" => 1.0,
            _ => unreachable!("the angle unit table names every unit"),
        };
        // NB: Reduce literal angles before unit conversion, which can round away their periodic equivalence.
        return angle_value_to_radians(value % period, *unit);
    }
    let degrees = angle_degrees(data)
        .expect("a computed transform angle is an angle or a calculation that resolves without context");
    // NB: Calculated angles resolve in canonical degrees.
    (degrees % 360.0).to_radians()
}

/// An angle in degrees. None for a value that is not an angle or a calculation that resolves
/// without context.
pub(crate) fn angle_degrees(data: &StyleValueData) -> Option<f64> {
    match data {
        StyleValueData::Angle { value, unit } => {
            Some(crate::css::calc::ANGLE_UNIT_CANONICAL_RATIOS[*unit as usize] * value)
        }
        StyleValueData::Calculated { .. } => crate::css::calc::resolve_calculated_angle_without_context(data),
        _ => None,
    }
}

/// The C++ Length::from_style_value followed by absolute_length_to_px_without_rounding: a
/// percentage resolves against the basis when there is one, and calc against it or zero. None for
/// a value that is not an absolute length, a percentage or a calculation that resolves.
pub(crate) fn length_px_unrounded(data: &StyleValueData, percentage_basis_px: Option<f64>) -> Option<f64> {
    match data {
        StyleValueData::Length { value, unit } => {
            let ratio = crate::css::style_compute::LENGTH_UNIT_CANONICAL_PX_RATIOS[*unit as usize];
            ratio.is_finite().then_some(ratio * value)
        }
        StyleValueData::Percentage { value } => percentage_basis_px.map(|basis| basis * value / 100.0),
        StyleValueData::Calculated { .. } => {
            crate::css::calc::resolve_calculated_length_without_context(data, percentage_basis_px.unwrap_or(0.0))
        }
        _ => None,
    }
}

/// A computed length in px, unrounded.
fn length_to_px_unrounded(data: &StyleValueData) -> f64 {
    length_px_unrounded(data, None)
        .expect("a computed length is absolute or a calculation that resolves without context")
}

/// The C++ Length::absolute_length_to_px: the unrounded pixels quantized to
/// CSSPixels.
fn length_to_css_pixels(data: &StyleValueData) -> CssPixels {
    CssPixels::nearest_value_for(length_to_px_unrounded(data))
}

/// The C++ number_from_style_value with a percentage basis of one.
fn transform_number(data: &StyleValueData) -> f64 {
    match data {
        StyleValueData::Number { value } => *value,
        StyleValueData::Percentage { value } => value * 0.01,
        StyleValueData::Calculated { .. } => {
            if let Some(number) = crate::css::calc::resolve_calculated_number_without_context(data) {
                return number;
            }
            crate::css::calc::resolve_calculated_percentage_without_context(data)
                .expect("a computed transform number resolves without context")
                * 0.01
        }
        _ => unreachable!("a computed transform number is a number, percentage or calculation"),
    }
}

fn value_contains_percentage(data: &StyleValueData) -> bool {
    match data {
        StyleValueData::Percentage { .. } => true,
        StyleValueData::Calculated(calculated_payload) => {
            let CalculatedPayload { rust_calculation, .. } = &**calculated_payload;
            rust_calculation.node().contains_percentage()
        }
        _ => false,
    }
}

fn matrix_identity() -> [f32; 16] {
    [
        1.0, 0.0, 0.0, 0.0, //
        0.0, 1.0, 0.0, 0.0, //
        0.0, 0.0, 1.0, 0.0, //
        0.0, 0.0, 0.0, 1.0,
    ]
}

fn matrix_translation(x: f32, y: f32, z: f32) -> [f32; 16] {
    [
        1.0, 0.0, 0.0, x, //
        0.0, 1.0, 0.0, y, //
        0.0, 0.0, 1.0, z, //
        0.0, 0.0, 0.0, 1.0,
    ]
}

fn matrix_scale(x: f32, y: f32, z: f32) -> [f32; 16] {
    [
        x, 0.0, 0.0, 0.0, //
        0.0, y, 0.0, 0.0, //
        0.0, 0.0, z, 0.0, //
        0.0, 0.0, 0.0, 1.0,
    ]
}

fn matrix_perspective(distance: f32) -> [f32; 16] {
    [
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        0.0,
        1.0,
        0.0,
        0.0,
        0.0,
        -1.0 / distance,
        1.0,
    ]
}

fn matrix_rotation(axis: [f32; 3], angle: f32) -> [f32; 16] {
    let rows = libgfx_rust::rotation_matrix(axis, angle).elements;
    std::array::from_fn(|index| rows[index / 4][index % 4])
}

/// The matrix of one transform function whose values resolve without a box: computed values,
/// whose percentage-bearing translate values lower into per-axis slots instead, or the absolute
/// values DOMMatrix accepts.
pub(crate) fn transformation_to_matrix(
    function: u8,
    values: &[crate::css::style_value::RetainedStyleValueData],
) -> [f32; 16] {
    use crate::css::serialize::transform_function as functions;

    let parameters = crate::css::serialize::TRANSFORM_FUNCTION_PARAMETER_TYPES[function as usize];
    let count = values.len();
    let get_value = |index: usize| -> f32 {
        let data = values[index].data();
        match parameters[index] {
            TRANSFORM_PARAMETER_ANGLE => transform_angle_radians(data) as f32,
            TRANSFORM_PARAMETER_LENGTH | TRANSFORM_PARAMETER_LENGTH_NONE | TRANSFORM_PARAMETER_LENGTH_PERCENTAGE => {
                length_to_css_pixels(data).to_float()
            }
            TRANSFORM_PARAMETER_NUMBER | TRANSFORM_PARAMETER_NUMBER_PERCENTAGE => transform_number(data) as f32,
            _ => unreachable!("the parameter table holds only known parameter types"),
        }
    };

    match function {
        functions::PERSPECTIVE => {
            // https://drafts.csswg.org/css-transforms-2/#perspective
            if count == 1 {
                if matches!(values[0].data(), StyleValueData::Keyword { keyword: code } if *code == keyword::NONE) {
                    return matrix_identity();
                }
                // A depth below 1px acts as 1px for rendering and for the
                // resolved transform value.
                let distance = get_value(0);
                return matrix_perspective(distance.max(1.0));
            }
        }
        functions::MATRIX => {
            if count == 6 {
                let m: Vec<f32> = (0..6).map(get_value).collect();
                return [
                    m[0], m[2], 0.0, m[4], //
                    m[1], m[3], 0.0, m[5], //
                    0.0, 0.0, 1.0, 0.0, //
                    0.0, 0.0, 0.0, 1.0,
                ];
            }
        }
        functions::MATRIX3D => {
            if count == 16 {
                let m: Vec<f32> = (0..16).map(get_value).collect();
                return [
                    m[0], m[4], m[8], m[12], //
                    m[1], m[5], m[9], m[13], //
                    m[2], m[6], m[10], m[14], //
                    m[3], m[7], m[11], m[15],
                ];
            }
        }
        functions::TRANSLATE => {
            if count == 1 {
                return matrix_translation(get_value(0), 0.0, 0.0);
            }
            if count == 2 {
                return matrix_translation(get_value(0), get_value(1), 0.0);
            }
        }
        functions::TRANSLATE3D => {
            if count == 3 {
                return matrix_translation(get_value(0), get_value(1), get_value(2));
            }
        }
        functions::TRANSLATE_X => {
            if count == 1 {
                return matrix_translation(get_value(0), 0.0, 0.0);
            }
        }
        functions::TRANSLATE_Y => {
            if count == 1 {
                return matrix_translation(0.0, get_value(0), 0.0);
            }
        }
        functions::TRANSLATE_Z => {
            if count == 1 {
                return matrix_translation(0.0, 0.0, get_value(0));
            }
        }
        functions::SCALE => {
            if count == 1 {
                let scale = get_value(0);
                return matrix_scale(scale, scale, 1.0);
            }
            if count == 2 {
                return matrix_scale(get_value(0), get_value(1), 1.0);
            }
        }
        functions::SCALE3D => {
            if count == 3 {
                return matrix_scale(get_value(0), get_value(1), get_value(2));
            }
        }
        functions::SCALE_X => {
            if count == 1 {
                return matrix_scale(get_value(0), 1.0, 1.0);
            }
        }
        functions::SCALE_Y => {
            if count == 1 {
                return matrix_scale(1.0, get_value(0), 1.0);
            }
        }
        functions::SCALE_Z => {
            if count == 1 {
                return matrix_scale(1.0, 1.0, get_value(0));
            }
        }
        functions::ROTATE3D => {
            if count == 4 {
                let axis = [get_value(0), get_value(1), get_value(2)];
                // The Gfx VectorN dot accumulates in component order.
                let length_squared = axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2];
                let length = length_squared.sqrt();
                let epsilon = 1e-5f32;
                if length < epsilon {
                    return matrix_identity();
                }
                let inverse_length = 1.0 / length;
                let normalized = [
                    axis[0] * inverse_length,
                    axis[1] * inverse_length,
                    axis[2] * inverse_length,
                ];
                return matrix_rotation(normalized, get_value(3));
            }
        }
        functions::ROTATE_X => {
            if count == 1 {
                return matrix_rotation([1.0, 0.0, 0.0], get_value(0));
            }
        }
        functions::ROTATE_Y => {
            if count == 1 {
                return matrix_rotation([0.0, 1.0, 0.0], get_value(0));
            }
        }
        functions::ROTATE | functions::ROTATE_Z => {
            if count == 1 {
                return matrix_rotation([0.0, 0.0, 1.0], get_value(0));
            }
        }
        functions::SKEW => {
            if count == 1 {
                let mut matrix = matrix_identity();
                matrix[1] = math::tan(get_value(0));
                return matrix;
            }
            if count == 2 {
                let mut matrix = matrix_identity();
                matrix[1] = math::tan(get_value(0));
                matrix[4] = math::tan(get_value(1));
                return matrix;
            }
        }
        functions::SKEW_X => {
            if count == 1 {
                let mut matrix = matrix_identity();
                matrix[1] = math::tan(get_value(0));
                return matrix;
            }
        }
        functions::SKEW_Y if count == 1 => {
            let mut matrix = matrix_identity();
            matrix[4] = math::tan(get_value(0));
            return matrix;
        }
        _ => {}
    }
    // An unhandled function and argument-count combination is the identity.
    matrix_identity()
}

/// The abstract matrix of a parsed `transform` value or of one transform function, as DOMMatrix
/// parses a string into one: the product of the functions' matrices, and whether every function is
/// two-dimensional. False when a function needs a box or a font to resolve: a relative length, a
/// percentage of a length, a calculation that does not simplify, or a tree-counting function.
/// https://drafts.fxtf.org/geometry/#parse-a-string-into-an-abstract-matrix
/// The matrix is written to the 16 floats of `out_matrix`, row by row.
#[unsafe(no_mangle)]
pub extern "C" fn rust_transform_list_to_abstract_matrix(
    value: &StyleValueData,
    out_matrix: ak::SpanMut<'_, f32>,
    out_is_2d: &mut bool,
) -> bool {
    use crate::css::serialize::transform_function as functions;

    // The keyword none is no function at all.
    let transform_list = match value {
        StyleValueData::ValueList { values, .. } => values.as_slice(),
        _ => &[],
    };
    let single_function = matches!(value, StyleValueData::Transformation { .. }).then_some(value);
    let mut matrix = libgfx_rust::FloatMatrix4x4::identity();
    let mut is_2d = true;
    for function in transform_list
        .iter()
        .map(|function| function.data())
        .chain(single_function)
    {
        let StyleValueData::Transformation(transformation_payload) = function else {
            return false;
        };
        let TransformationPayload {
            transform_function,
            values,
            matrix_values,
            ..
        } = &**transformation_payload;
        let values = if matrix_values.as_slice().is_empty() {
            values.as_slice()
        } else {
            matrix_values.as_slice()
        };
        let parameters = crate::css::serialize::TRANSFORM_FUNCTION_PARAMETER_TYPES[*transform_function as usize];
        if !values
            .iter()
            .zip(parameters)
            .all(|(value, &parameter)| resolves_without_a_box(parameter, value.data()))
        {
            return false;
        }
        // https://drafts.csswg.org/css-transforms-1/#two-d-transform-functions
        is_2d &= matches!(
            *transform_function,
            functions::MATRIX
                | functions::TRANSLATE
                | functions::TRANSLATE_X
                | functions::TRANSLATE_Y
                | functions::SCALE
                | functions::SCALE_X
                | functions::SCALE_Y
                | functions::ROTATE
                | functions::SKEW
                | functions::SKEW_X
                | functions::SKEW_Y
        );
        let function_matrix = transformation_to_matrix(*transform_function, values);
        matrix = matrix.multiplied(libgfx_rust::FloatMatrix4x4 {
            elements: std::array::from_fn(|row| std::array::from_fn(|column| function_matrix[row * 4 + column])),
        });
    }
    out_matrix.into_slice().copy_from_slice(matrix.elements.as_flattened());
    *out_is_2d = is_2d;
    true
}

fn resolves_without_a_box(parameter: u8, value: &StyleValueData) -> bool {
    match value {
        StyleValueData::Length { value, unit } => {
            crate::css::style_compute::absolute_length_to_px(*value, *unit).is_some()
        }
        StyleValueData::Percentage { .. } => parameter != TRANSFORM_PARAMETER_LENGTH_PERCENTAGE,
        StyleValueData::Calculated { .. } => {
            crate::css::calc::resolve_calculated_canonically(value, None).is_some()
                && !(parameter == TRANSFORM_PARAMETER_LENGTH_PERCENTAGE && value_contains_percentage(value))
        }
        StyleValueData::TreeCountingFunction { .. } => !matches!(
            parameter,
            TRANSFORM_PARAMETER_NUMBER | TRANSFORM_PARAMETER_NUMBER_PERCENTAGE
        ),
        _ => true,
    }
}

fn baked_matrix_entry(matrix: [f32; 16]) -> ComputedResolvedTransform {
    ComputedResolvedTransform {
        is_translate: false,
        matrix,
        x_px: 0.0,
        y_px: 0.0,
        z_px: 0.0,
        x_percentage: ComputedStyleValueHandle::empty(),
        y_percentage: ComputedStyleValueHandle::empty(),
    }
}

/// The TransformationStyleValue::to_resolved_transform port: only the
/// translate family takes length-percentages, so a percentage-bearing
/// translate keeps per-axis slots and everything else bakes into a matrix.
fn lower_transformation(data: &StyleValueData) -> ComputedResolvedTransform {
    use crate::css::serialize::transform_function as functions;

    let StyleValueData::Transformation(transformation_payload) = data else {
        unreachable!("a computed transform function is a transformation value");
    };
    let TransformationPayload {
        transform_function,
        values,
        matrix_values,
        ..
    } = &**transformation_payload;
    let function = *transform_function;
    let values = if matrix_values.as_slice().is_empty() {
        values.as_slice()
    } else {
        matrix_values.as_slice()
    };
    let parameters = crate::css::serialize::TRANSFORM_FUNCTION_PARAMETER_TYPES[function as usize];

    let axis_needs_reference_box = |index: usize| {
        index < values.len()
            && parameters[index] == TRANSFORM_PARAMETER_LENGTH_PERCENTAGE
            && value_contains_percentage(values[index].data())
    };
    let lower_axis = |index: usize| -> (f32, ComputedStyleValueHandle) {
        if index >= values.len() {
            return (0.0, ComputedStyleValueHandle::empty());
        }
        let value = &values[index];
        if axis_needs_reference_box(index) {
            return (0.0, ComputedStyleValueHandle::from_retained(value));
        }
        (
            length_to_css_pixels(value.data()).to_float(),
            ComputedStyleValueHandle::empty(),
        )
    };
    let translate_entry =
        |x: (f32, ComputedStyleValueHandle), y: (f32, ComputedStyleValueHandle), z: f32| ComputedResolvedTransform {
            is_translate: true,
            matrix: matrix_identity(),
            x_px: x.0,
            y_px: y.0,
            z_px: z,
            x_percentage: x.1,
            y_percentage: y.1,
        };

    match function {
        functions::TRANSLATE => {
            if (values.len() == 1 || values.len() == 2) && (axis_needs_reference_box(0) || axis_needs_reference_box(1))
            {
                return translate_entry(lower_axis(0), lower_axis(1), 0.0);
            }
        }
        functions::TRANSLATE3D => {
            if values.len() == 3 && (axis_needs_reference_box(0) || axis_needs_reference_box(1)) {
                let z = length_to_css_pixels(values[2].data()).to_float();
                return translate_entry(lower_axis(0), lower_axis(1), z);
            }
        }
        functions::TRANSLATE_X => {
            if values.len() == 1 && axis_needs_reference_box(0) {
                return translate_entry(lower_axis(0), (0.0, ComputedStyleValueHandle::empty()), 0.0);
            }
        }
        functions::TRANSLATE_Y if values.len() == 1 && axis_needs_reference_box(0) => {
            return translate_entry((0.0, ComputedStyleValueHandle::empty()), lower_axis(0), 0.0);
        }
        _ => {}
    }

    baked_matrix_entry(transformation_to_matrix(function, values))
}

/// Builds the complete transform payload in Rust, including paint-ready
/// matrices and retained computed-value handles.
fn build_transform_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index::TRANSFORM, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    let retained = |property: u16| -> ComputedStyleValueHandle {
        match values.value(property) {
            Some(_) => ComputedStyleValueHandle::from_retained(values.handle(property)),
            None => ComputedStyleValueHandle::empty(),
        }
    };

    let mut resolved: Vec<ComputedResolvedTransform> = Vec::new();
    // Pre-lower in the order the transformation matrix accumulates them:
    // translate, rotate, scale, then the transform property's functions.
    let mut individual = |property: u16| -> ComputedStyleValueHandle {
        match values.value(property) {
            Some(data @ StyleValueData::Transformation { .. }) => {
                resolved.push(lower_transformation(data));
                retained(property)
            }
            _ => ComputedStyleValueHandle::empty(),
        }
    };
    let translate = individual(property_id::TRANSLATE);
    let rotate = individual(property_id::ROTATE);
    let scale = individual(property_id::SCALE);

    let transform_list = match values.value(property_id::TRANSFORM) {
        Some(StyleValueData::ValueList { values: list, .. }) => {
            for value in list.as_slice() {
                resolved.push(lower_transformation(value.data()));
            }
            retained(property_id::TRANSFORM)
        }
        _ => ComputedStyleValueHandle::empty(),
    };

    let (transform_origin_x, transform_origin_y, transform_origin_z) = match values.value(property_id::TRANSFORM_ORIGIN)
    {
        Some(StyleValueData::ValueList { values: list, .. }) if list.as_slice().len() == 3 => {
            let offsets = list.as_slice();
            (
                ComputedStyleValueHandle::from_retained(&offsets[0]),
                ComputedStyleValueHandle::from_retained(&offsets[1]),
                ComputedStyleValueHandle::from_retained(&offsets[2]),
            )
        }
        _ => unreachable!("computed transform-origin is a three-value list"),
    };

    let (has_perspective, perspective_px) = match values.value(property_id::PERSPECTIVE) {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::NONE => (false, 0),
        Some(data) => (true, length_to_css_pixels(data).raw_value()),
        None => (false, 0),
    };

    let Some(StyleValueData::Position(position_payload)) = values.value(property_id::PERSPECTIVE_ORIGIN) else {
        unreachable!("computed perspective-origin is a position value");
    };
    let PositionPayload { edge_x, edge_y } = &**position_payload;
    let position_offset = |edge: &crate::css::style_value::RetainedStyleValueData| {
        let StyleValueData::Edge { offset, .. } = edge.data() else {
            unreachable!("computed position component is an edge value");
        };
        ComputedStyleValueHandle::from_retained(offset)
    };
    let has_offset_path = values
        .value(property_id::OFFSET_PATH)
        .is_some_and(|value| !crate::css::style_value::is_none_keyword(value));

    let perspective_origin_x = position_offset(edge_x);
    let perspective_origin_y = position_offset(edge_y);

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::TRANSFORM,
        &entries,
        |payload: &mut TransformValues| {
            payload.transformations = transform_list;
            payload.resolved_transforms = RetainedComputedResolvedTransformList::from_vec(resolved);
            payload.transform_origin_x = transform_origin_x;
            payload.transform_origin_y = transform_origin_y;
            payload.transform_origin_z = transform_origin_z;
            payload.rotate = rotate;
            payload.translate = translate;
            payload.scale = scale;
            payload.has_perspective = has_perspective;
            payload.perspective_px = perspective_px;
            payload.perspective_origin_x = perspective_origin_x;
            payload.perspective_origin_y = perspective_origin_y;
            payload.has_offset_path = has_offset_path;
            payload.offset_path = retained(property_id::OFFSET_PATH);
            payload.offset_distance = retained(property_id::OFFSET_DISTANCE);
            payload.offset_position = retained(property_id::OFFSET_POSITION);
            payload.offset_anchor = retained(property_id::OFFSET_ANCHOR);
            payload.offset_rotate = retained(property_id::OFFSET_ROTATE);
        },
        parent,
    )
}

/// The shared prefix of every color style value variant.
fn color_base_of(data: &StyleValueData) -> Option<&crate::css::style_value::ColorBase> {
    data.color_base()
}

/// The C++ shadow color-syntax classification: non-color values are legacy,
/// the named color-function types split into the legacy rgb/hsl/hwb family
/// and the modern rest, and untyped colors carry their own syntax flag.
fn shadow_color_syntax(color: Option<&StyleValueData>) -> u8 {
    // The C++ ColorStyleValue::ColorType codes, pinned by static asserts in
    // ComputedValues.cpp.

    let Some(base) = color.and_then(color_base_of) else {
        return COLOR_SYNTAX_LEGACY;
    };
    if !base.has_color_type {
        return base.color_syntax;
    }
    match base.color_type {
        COLOR_TYPE_RGB | COLOR_TYPE_HSL | COLOR_TYPE_HWB => COLOR_SYNTAX_LEGACY,
        _ => COLOR_SYNTAX_MODERN,
    }
}

/// Lowers one filter property's computed value: the operations bake against
/// the element's colors, and only the url() element lookup stays per paint.
/// Returns the operations plus the retained list handle; a value that is not
/// a filter list lowers to none, as the C++ extractor did.
fn lower_filter_operations(
    values: &LonghandSource,
    property: u16,
    input: &ColorResolutionInput,
) -> (Vec<ComputedFilterOperation>, ComputedStyleValueHandle) {
    const FILTER_KIND_BLUR: u8 = 0;
    const FILTER_KIND_DROP_SHADOW: u8 = 1;
    const FILTER_KIND_HUE_ROTATE: u8 = 2;
    const FILTER_KIND_COLOR: u8 = 3;
    const FILTER_KIND_URL: u8 = 4;
    // The C++ StyleValueList::Separator::Space code.
    const SEPARATOR_SPACE: u8 = 0;

    let Some(StyleValueData::ValueList {
        values: list,
        separator,
        ..
    }) = values.value(property)
    else {
        return (Vec::new(), ComputedStyleValueHandle::empty());
    };
    let list = list.as_slice();
    // The C++ is_filter_style_value_list check: a non-empty space-separated
    // list of filter functions and url() references.
    if list.is_empty()
        || *separator != SEPARATOR_SPACE
        || !list
            .iter()
            .all(|value| matches!(value.data(), StyleValueData::Filter { .. } | StyleValueData::Url { .. }))
    {
        return (Vec::new(), ComputedStyleValueHandle::empty());
    }

    let empty_operation = || ComputedFilterOperation {
        kind: 0,
        color_operation: 0,
        amount: 0.0,
        shadow_offset_x: 0,
        shadow_offset_y: 0,
        shadow_radius: 0,
        shadow_color: 0,
        url_value: ComputedStyleValueHandle::empty(),
    };
    let mut operations = Vec::with_capacity(list.len());
    for value in list {
        match value.data() {
            StyleValueData::Url { .. } => {
                operations.push(ComputedFilterOperation {
                    kind: FILTER_KIND_URL,
                    url_value: ComputedStyleValueHandle::from_retained(value),
                    ..empty_operation()
                });
            }
            StyleValueData::Filter {
                kind,
                color_operation,
                value: filter_value,
            } => match *kind {
                FILTER_KIND_BLUR => {
                    operations.push(ComputedFilterOperation {
                        kind: FILTER_KIND_BLUR,
                        amount: length_to_px_unrounded(filter_value.data()) as f32,
                        ..empty_operation()
                    });
                }
                FILTER_KIND_DROP_SHADOW => {
                    let StyleValueData::Shadow(shadow_payload) = filter_value.data() else {
                        unreachable!("a computed drop-shadow filter holds a shadow value");
                    };
                    let ShadowPayload {
                        color,
                        offset_x,
                        offset_y,
                        blur_radius,
                        ..
                    } = &**shadow_payload;
                    let fallback = input.current_color.unwrap_or(Rgba {
                        r: 0,
                        g: 0,
                        b: 0,
                        a: 255,
                    });
                    let resolved_color = color
                        .optional_data()
                        .and_then(|color| to_color(color, input))
                        .unwrap_or(fallback);
                    operations.push(ComputedFilterOperation {
                        kind: FILTER_KIND_DROP_SHADOW,
                        shadow_offset_x: length_to_css_pixels(offset_x.data()).raw_value(),
                        shadow_offset_y: length_to_css_pixels(offset_y.data()).raw_value(),
                        shadow_radius: blur_radius
                            .optional_data()
                            .map_or(0, |radius| length_to_css_pixels(radius).raw_value()),
                        shadow_color: packed_color(resolved_color),
                        ..empty_operation()
                    });
                }
                FILTER_KIND_HUE_ROTATE => {
                    operations.push(ComputedFilterOperation {
                        kind: FILTER_KIND_HUE_ROTATE,
                        amount: angle_degrees(filter_value.data()).expect(
                            "a computed filter angle is an angle or a calculation that resolves without context",
                        ) as f32,
                        ..empty_operation()
                    });
                }
                FILTER_KIND_COLOR => {
                    operations.push(ComputedFilterOperation {
                        kind: FILTER_KIND_COLOR,
                        color_operation: *color_operation,
                        amount: transform_number(filter_value.data()) as f32,
                        ..empty_operation()
                    });
                }
                _ => unreachable!("the filter kind codes cover every filter function"),
            },
            _ => unreachable!("the filter list was checked above"),
        }
    }
    (
        operations,
        ComputedStyleValueHandle::from_retained(values.handle(property)),
    )
}

fn lower_shadow_layers(values: &LonghandSource, property: u16, input: &ColorResolutionInput) -> Vec<ComputedShadow> {
    let Some(StyleValueData::ValueList { values: list, .. }) = values.value(property) else {
        // A computed shadow list is the none keyword or a value list.
        return Vec::new();
    };
    let mut shadows = Vec::with_capacity(list.as_slice().len());
    for value in list.as_slice() {
        let StyleValueData::Shadow(shadow_payload) = value.data() else {
            unreachable!("a computed box-shadow layer is a shadow value");
        };
        let ShadowPayload {
            color,
            offset_x,
            offset_y,
            blur_radius,
            spread_distance,
            placement,
            ..
        } = &**shadow_payload;
        // A missing color is `currentcolor`, which the shadow's reader resolves.
        let held_color = match color.optional_data() {
            Some(color) => style_color(color, input).expect("a computed shadow color resolves"),
            None => StyleColor::CURRENT_COLOR,
        };
        shadows.push(ComputedShadow {
            offset_x: length_to_css_pixels(offset_x.data()).raw_value(),
            offset_y: length_to_css_pixels(offset_y.data()).raw_value(),
            blur_radius: blur_radius
                .optional_data()
                .map_or(0, |radius| length_to_css_pixels(radius).raw_value()),
            spread_distance: spread_distance
                .optional_data()
                .map_or(0, |spread| length_to_css_pixels(spread).raw_value()),
            color: held_color,
            color_syntax: shadow_color_syntax(color.optional_data()),
            placement: u32::from(*placement),
        });
    }
    shadows
}

fn lower_clip_edge(data: &StyleValueData) -> ComputedClipEdge {
    match data {
        StyleValueData::Keyword { keyword: code } if *code == keyword::AUTO => ComputedClipEdge {
            is_auto: true,
            value: 0.0,
            unit: crate::css::style_compute::px_length_unit(),
        },
        StyleValueData::Length { value, unit } => ComputedClipEdge {
            is_auto: false,
            value: *value,
            unit: *unit,
        },
        StyleValueData::Calculated { .. } => ComputedClipEdge {
            is_auto: false,
            value: crate::css::calc::resolve_calculated_length_without_context(data, 0.0)
                .expect("a computed clip edge resolves without context"),
            unit: crate::css::style_compute::px_length_unit(),
        },
        _ => unreachable!("a computed clip edge is auto, a length or a calculation"),
    }
}

/// Builds the complete effects payload in Rust.
fn build_effects_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index::EFFECTS, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    let (filter_operations, filter_list) = lower_filter_operations(values, property_id::FILTER, input);
    let (backdrop_operations, backdrop_list) = lower_filter_operations(values, property_id::BACKDROP_FILTER, input);
    let shadows = lower_shadow_layers(values, property_id::BOX_SHADOW, input);

    let auto_edge = || ComputedClipEdge {
        is_auto: true,
        value: 0.0,
        unit: crate::css::style_compute::px_length_unit(),
    };
    let (clip_is_rect, clip_edges) = match values.value(property_id::CLIP) {
        Some(StyleValueData::Rect(rect_payload)) => {
            let RectPayload {
                top,
                right,
                bottom,
                left,
            } = &**rect_payload;
            (
                true,
                [
                    lower_clip_edge(top.data()),
                    lower_clip_edge(right.data()),
                    lower_clip_edge(bottom.data()),
                    lower_clip_edge(left.data()),
                ],
            )
        }
        _ => (false, [auto_edge(), auto_edge(), auto_edge(), auto_edge()]),
    };

    let filter = ComputedFilter {
        filter_list,
        operations: RetainedComputedFilterOperationList::from_vec(filter_operations),
    };
    let backdrop_filter = ComputedFilter {
        filter_list: backdrop_list,
        operations: RetainedComputedFilterOperationList::from_vec(backdrop_operations),
    };
    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::EFFECTS,
        &entries,
        |payload: &mut EffectsValues| {
            payload.filter = filter;
            payload.backdrop_filter = backdrop_filter;
            payload.box_shadows = RetainedComputedShadowList::from_vec(shadows);
            payload.clip_is_rect = clip_is_rect;
            payload.clip_edges = clip_edges;
            payload.opacity_style_value = ComputedStyleValueHandle::from_retained(values.handle(property_id::OPACITY));
            payload.filter_style_value = ComputedStyleValueHandle::from_retained(values.handle(property_id::FILTER));
            payload.backdrop_filter_style_value =
                ComputedStyleValueHandle::from_retained(values.handle(property_id::BACKDROP_FILTER));
            payload.mix_blend_mode_style_value =
                ComputedStyleValueHandle::from_retained(values.handle(property_id::MIX_BLEND_MODE));
            payload.isolation_style_value =
                ComputedStyleValueHandle::from_retained(values.handle(property_id::ISOLATION));
            payload.box_shadow_style_value =
                ComputedStyleValueHandle::from_retained(values.handle(property_id::BOX_SHADOW));
            payload.clip_style_value = ComputedStyleValueHandle::from_retained(values.handle(property_id::CLIP));
        },
        parent,
    )
}

// --- Border lowering -------------------------------------------------------
//
// The border walks the C++ extractors ran over minted wrappers lower here
// from the table slots. Enum-mapped keywords become their C++ enum codes;
// wrapper-backed members travel as retained canonical handles.

/// The comma-separated computed items of a repeatable-list property: the
/// list's elements, or the single value itself.
fn repeatable_items<'a>(values: &LonghandSource<'a>, property: u16) -> Vec<&'a RetainedStyleValueData> {
    match values.value(property) {
        Some(StyleValueData::ValueList { values: list, .. }) => list.as_slice().iter().collect(),
        _ => vec![values.handle(property)],
    }
}

fn keyword_of(data: &StyleValueData) -> Option<u16> {
    match data {
        StyleValueData::Keyword { keyword } => Some(*keyword),
        _ => None,
    }
}

fn border_radius_is_initial(data: &StyleValueData) -> bool {
    let StyleValueData::BorderRadius(border_radius_payload) = data else {
        return false;
    };
    let BorderRadiusPayload {
        horizontal_radius,
        vertical_radius,
        ..
    } = &**border_radius_payload;
    let is_zero_px = |radius: &crate::css::style_value::RetainedStyleValueData| matches!(radius.data(), StyleValueData::Length { value, unit } if *value == 0.0 && *unit == crate::css::style_compute::px_length_unit());
    is_zero_px(horizontal_radius) && is_zero_px(vertical_radius)
}

/// Builds the background group from retained canonical computed values.
fn build_background_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index::BACKGROUND, values, input, used_color_scheme) else {
        return std::ptr::null();
    };
    let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
    let background_color = style_color(
        values
            .value(property_id::BACKGROUND_COLOR)
            .expect("background-color has a computed value"),
        input,
    )
    .expect("a computed background-color resolves in Rust");
    let image_items = repeatable_items(values, property_id::BACKGROUND_IMAGE);
    let clip_items = repeatable_items(values, property_id::BACKGROUND_CLIP);
    let final_clip = clip_items[(image_items.len() - 1) % clip_items.len()].data();
    let background_color_clip = keyword_of(final_clip)
        .and_then(crate::css::css_enums::keyword_to_background_box)
        .expect("a computed background-clip keyword maps to its enum");

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::BACKGROUND,
        &entries,
        |payload: &mut BackgroundValues| {
            payload.background_color = background_color;
            payload.background_color_style_value = retained(property_id::BACKGROUND_COLOR);
            payload.background_color_clip = background_color_clip;
            payload.background_image = retained(property_id::BACKGROUND_IMAGE);
            payload.background_attachment = retained(property_id::BACKGROUND_ATTACHMENT);
            payload.background_blend_mode = retained(property_id::BACKGROUND_BLEND_MODE);
            payload.background_clip = retained(property_id::BACKGROUND_CLIP);
            payload.background_origin = retained(property_id::BACKGROUND_ORIGIN);
            payload.background_position_x = retained(property_id::BACKGROUND_POSITION_X);
            payload.background_position_y = retained(property_id::BACKGROUND_POSITION_Y);
            payload.background_repeat = retained(property_id::BACKGROUND_REPEAT);
            payload.background_size = retained(property_id::BACKGROUND_SIZE);
        },
        parent,
    )
}

/// Builds the mask group from retained canonical computed values.
fn build_mask_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index::MASK, values, input, used_color_scheme) else {
        return std::ptr::null();
    };
    let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::MASK,
        &entries,
        |payload: &mut MaskValues| {
            payload.mask_image = retained(property_id::MASK_IMAGE);
            payload.mask_type = retained(property_id::MASK_TYPE);
            payload.clip_path = retained(property_id::CLIP_PATH);
            payload.mask_mode = retained(property_id::MASK_MODE);
            payload.mask_repeat = retained(property_id::MASK_REPEAT);
            payload.mask_position = retained(property_id::MASK_POSITION);
            payload.mask_clip = retained(property_id::MASK_CLIP);
            payload.mask_origin = retained(property_id::MASK_ORIGIN);
            payload.mask_size = retained(property_id::MASK_SIZE);
            payload.mask_composite = retained(property_id::MASK_COMPOSITE);
        },
        parent,
    )
}

/// Builds the border group from layout-facing side facts and retained
/// canonical values for the C++ presentation views.
fn build_border_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let generic = build_generic_group(group_index::BORDER, values, input, used_color_scheme, parent);
    if !generic.is_null() {
        return generic;
    }
    let Some(entries) = gather_group_entries(group_index::BORDER, values, input, used_color_scheme) else {
        return std::ptr::null();
    };
    let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
    let has_noninitial_border_radii = [
        property_id::BORDER_BOTTOM_LEFT_RADIUS,
        property_id::BORDER_BOTTOM_RIGHT_RADIUS,
        property_id::BORDER_TOP_LEFT_RADIUS,
        property_id::BORDER_TOP_RIGHT_RADIUS,
    ]
    .into_iter()
    .any(|property| !border_radius_is_initial(values.value(property).expect("a border radius has a computed value")));
    let side = |style_property: u16, width_property: u16, color_property: u16| {
        let style_keyword = values
            .value(style_property)
            .and_then(keyword_of)
            .unwrap_or_else(|| unreachable!("a computed border style is a keyword"));
        let line_style = crate::css::css_enums::keyword_to_line_style(style_keyword)
            .unwrap_or_else(|| unreachable!("a computed border style maps to a line style"));
        let computed_width = length_to_css_pixels(
            values
                .value(width_property)
                .expect("a computed border width has a value"),
        );
        crate::css::computed_value_types::ComputedBorderSide {
            color: style_color(
                values
                    .value(color_property)
                    .expect("a computed border color has a value"),
                input,
            )
            .expect("a computed border color resolves in Rust"),
            line_style,
            // LineStyle::None and LineStyle::Hidden.
            width: if line_style == 0 || line_style == 1 {
                crate::css::css_pixels::CssPixels::default()
            } else {
                computed_width
            },
        }
    };

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::BORDER,
        &entries,
        |payload: &mut BorderValues| {
            payload.border_left = side(
                property_id::BORDER_LEFT_STYLE,
                property_id::BORDER_LEFT_WIDTH,
                property_id::BORDER_LEFT_COLOR,
            );
            payload.border_top = side(
                property_id::BORDER_TOP_STYLE,
                property_id::BORDER_TOP_WIDTH,
                property_id::BORDER_TOP_COLOR,
            );
            payload.border_right = side(
                property_id::BORDER_RIGHT_STYLE,
                property_id::BORDER_RIGHT_WIDTH,
                property_id::BORDER_RIGHT_COLOR,
            );
            payload.border_bottom = side(
                property_id::BORDER_BOTTOM_STYLE,
                property_id::BORDER_BOTTOM_WIDTH,
                property_id::BORDER_BOTTOM_COLOR,
            );
            payload.border_left_color_style_value = retained(property_id::BORDER_LEFT_COLOR);
            payload.border_top_color_style_value = retained(property_id::BORDER_TOP_COLOR);
            payload.border_right_color_style_value = retained(property_id::BORDER_RIGHT_COLOR);
            payload.border_bottom_color_style_value = retained(property_id::BORDER_BOTTOM_COLOR);
            payload.border_left_computed_width = length_to_css_pixels(
                values
                    .value(property_id::BORDER_LEFT_WIDTH)
                    .expect("border-left-width has a computed value"),
            );
            payload.border_top_computed_width = length_to_css_pixels(
                values
                    .value(property_id::BORDER_TOP_WIDTH)
                    .expect("border-top-width has a computed value"),
            );
            payload.border_right_computed_width = length_to_css_pixels(
                values
                    .value(property_id::BORDER_RIGHT_WIDTH)
                    .expect("border-right-width has a computed value"),
            );
            payload.border_bottom_computed_width = length_to_css_pixels(
                values
                    .value(property_id::BORDER_BOTTOM_WIDTH)
                    .expect("border-bottom-width has a computed value"),
            );
            payload.border_bottom_left_radius = retained(property_id::BORDER_BOTTOM_LEFT_RADIUS);
            payload.border_bottom_right_radius = retained(property_id::BORDER_BOTTOM_RIGHT_RADIUS);
            payload.border_top_left_radius = retained(property_id::BORDER_TOP_LEFT_RADIUS);
            payload.border_top_right_radius = retained(property_id::BORDER_TOP_RIGHT_RADIUS);
            payload.has_noninitial_border_radii = has_noninitial_border_radii;
            payload.border_image_source = retained(property_id::BORDER_IMAGE_SOURCE);
            payload.border_shape = retained(property_id::BORDER_SHAPE);
            payload.border_image_slice = retained(property_id::BORDER_IMAGE_SLICE);
            payload.border_image_width = retained(property_id::BORDER_IMAGE_WIDTH);
            payload.border_image_outset = retained(property_id::BORDER_IMAGE_OUTSET);
            payload.border_image_repeat = retained(property_id::BORDER_IMAGE_REPEAT);
        },
        parent,
    )
}

// --- SVG, list and content lowering -----------------------------------------

use crate::css::computed_value_types::{SVG_PAINT_COLOR, SVG_PAINT_NONE, SVG_PAINT_URL};
use crate::css::value_codes::*;

fn lower_svg_paint(values: &LonghandSource, property: u16, input: &ColorResolutionInput) -> ComputedSvgPaint {
    let mut paint = ComputedSvgPaint {
        kind: SVG_PAINT_NONE,
        url: ComputedStyleValueHandle::empty(),
        has_color: false,
        color: StyleColor::rgba(0),
    };
    let data = values.value(property).expect("the table holds the paint property");
    match data {
        StyleValueData::Keyword { keyword: code } if *code == keyword::NONE => paint,
        StyleValueData::ValueList { values: list, .. } if list.as_slice().len() == 2 => {
            let components = list.as_slice();
            paint.kind = SVG_PAINT_URL;
            paint.url = ComputedStyleValueHandle::from_retained(&components[0]);
            match components[1].data() {
                StyleValueData::EmptyOptional => paint,
                StyleValueData::Keyword { keyword: code } if *code == keyword::NONE => paint,
                fallback => {
                    paint.has_color = true;
                    paint.color = style_color(fallback, input).expect("a computed SVG paint fallback is a color");
                    paint
                }
            }
        }
        _ => {
            paint.kind = SVG_PAINT_COLOR;
            paint.has_color = true;
            paint.color = style_color(data, input).expect("a computed SVG paint is none, a color, or a URL paint");
            paint
        }
    }
}

fn lower_svg_length_percentage_or_number(values: &LonghandSource, property: u16) -> ComputedStyleValueHandle {
    let data = values.value(property).expect("the table holds the property");
    let number = match data {
        StyleValueData::Number { value } => Some(*value),
        data @ StyleValueData::Calculated { .. } => crate::css::calc::resolve_calculated_number_without_context(data),
        _ => None,
    };
    match number {
        // FIXME: Converting to pixels isn't really correct - values should be in "user units"
        //        https://svgwg.org/svg2-draft/coords.html#TermUserUnits
        Some(number) => ComputedStyleValueHandle::length(number),
        None => ComputedStyleValueHandle::from_retained(values.handle(property)),
    }
}

/// Builds the complete inherited SVG payload in Rust.
fn build_inherited_svg_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index::INHERITED_SVG, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    // stroke-dasharray: none is the empty list; everything else is a list of
    // lengths, percentages, numbers and calculations.
    let mut dashes: Vec<ComputedSvgDash> = Vec::new();
    if let Some(StyleValueData::ValueList { values: list, .. }) = values.value(property_id::STROKE_DASHARRAY) {
        for item in list.as_slice() {
            let data = item.data();
            let number = match data {
                StyleValueData::Number { value } => Some(*value),
                data @ StyleValueData::Calculated { .. } => {
                    crate::css::calc::resolve_calculated_number_without_context(data)
                }
                _ => None,
            };
            dashes.push(match number {
                Some(number) => ComputedSvgDash {
                    is_number: true,
                    number,
                    value: ComputedStyleValueHandle::empty(),
                },
                None => ComputedSvgDash {
                    is_number: false,
                    number: 0.0,
                    value: ComputedStyleValueHandle::from_retained(item),
                },
            });
        }
    }

    // paint-order, with the omitted-keyword completion the extractor used.
    use crate::css::css_enums::paint_order;
    let mut order = [paint_order::FILL, paint_order::STROKE, paint_order::MARKERS];
    let serialization_length: u8;
    let mut is_normal = false;
    match values.value(property_id::PAINT_ORDER) {
        Some(StyleValueData::Keyword { keyword: code }) => {
            is_normal = *code == keyword::NORMAL;
            serialization_length = if is_normal { 0 } else { 1 };
            if !is_normal {
                match crate::css::css_enums::keyword_to_paint_order(*code)
                    .expect("a computed paint-order keyword maps to its enum")
                {
                    paint_order::FILL => {}
                    paint_order::STROKE => order = [paint_order::STROKE, paint_order::FILL, paint_order::MARKERS],
                    paint_order::MARKERS => order = [paint_order::MARKERS, paint_order::FILL, paint_order::STROKE],
                    _ => unreachable!("the paint-order codes cover every keyword"),
                }
            }
        }
        Some(StyleValueData::ValueList { values: list, .. }) => {
            // The third keyword is omitted by the shortest-serialization
            // principle; the code sum infers it.
            let items = list.as_slice();
            assert!(items.len() == 2, "a computed paint-order list holds two keywords");
            serialization_length = items.len() as u8;
            let mut sum = 0u8;
            for (index, item) in items.iter().enumerate() {
                let code = keyword_of(item.data())
                    .and_then(crate::css::css_enums::keyword_to_paint_order)
                    .expect("a computed paint-order item maps to its enum");
                sum += code;
                order[index] = code;
            }
            assert!(sum <= 3, "paint-order keywords cannot repeat");
            order[2] = 3 - sum;
        }
        _ => unreachable!("a computed paint-order is a keyword or a list"),
    }

    let dominant_baseline = values
        .value(property_id::DOMINANT_BASELINE)
        .and_then(keyword_of)
        .and_then(crate::css::css_enums::keyword_to_baseline_metric);

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::INHERITED_SVG,
        &entries,
        |payload: &mut InheritedSVGValues| {
            payload.fill = lower_svg_paint(values, property_id::FILL, input);
            payload.stroke = lower_svg_paint(values, property_id::STROKE, input);
            payload.stroke_dasharray = RetainedComputedSvgDashList::from_vec(dashes);
            payload.stroke_dashoffset = lower_svg_length_percentage_or_number(values, property_id::STROKE_DASHOFFSET);
            payload.stroke_width = lower_svg_length_percentage_or_number(values, property_id::STROKE_WIDTH);
            payload.paint_order = order;
            payload.paint_order_serialization_length = serialization_length;
            payload.paint_order_is_normal = is_normal;
            payload.has_dominant_baseline = dominant_baseline.is_some();
            payload.dominant_baseline = dominant_baseline.unwrap_or(0);
        },
        parent,
    )
}

/// Builds the inherited list group from canonical values without leaving
/// Rust. Counter-style scope resolution remains a consumer-side operation.
fn build_inherited_list_table_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let generic = build_generic_group(
        group_index::INHERITED_LIST_TABLE,
        values,
        input,
        used_color_scheme,
        parent,
    );
    if !generic.is_null() {
        return generic;
    }
    let Some(entries) = gather_group_entries(group_index::INHERITED_LIST_TABLE, values, input, used_color_scheme)
    else {
        return std::ptr::null();
    };

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::INHERITED_LIST_TABLE,
        &entries,
        |payload: &mut InheritedListTableValues| {
            let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
            payload.list_style_type = retained(property_id::LIST_STYLE_TYPE);
            payload.list_style_image = retained(property_id::LIST_STYLE_IMAGE);
            payload.quotes = retained(property_id::QUOTES);
            // NB: Computed border-spacing is a pair of absolute pixel lengths.
            let spacing_component = |data: &StyleValueData| -> i32 {
                match data {
                    StyleValueData::Length { value, unit } if *unit == crate::css::style_compute::px_length_unit() => {
                        crate::css::css_pixels::CssPixels::nearest_value_for(*value).raw_value()
                    }
                    _ => panic!("computed border-spacing component is not an absolute pixel length"),
                }
            };
            let components = match values.value(property_id::BORDER_SPACING) {
                Some(StyleValueData::ValueList { values, .. }) if values.as_slice().len() == 2 => values.as_slice(),
                _ => panic!("computed border-spacing is not a pair"),
            };
            payload.border_spacing_horizontal = spacing_component(components[0].data());
            payload.border_spacing_vertical = spacing_component(components[1].data());
        },
        parent,
    )
}

/// Builds the content group from its canonical values without leaving Rust.
fn build_content_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let generic = build_generic_group(group_index::CONTENT, values, input, used_color_scheme, parent);
    if !generic.is_null() {
        return generic;
    }
    let Some(entries) = gather_group_entries(group_index::CONTENT, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::CONTENT,
        &entries,
        |payload: &mut ContentValues| {
            let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
            payload.content = retained(property_id::CONTENT);
            payload.counter_increment = retained(property_id::COUNTER_INCREMENT);
            payload.counter_reset = retained(property_id::COUNTER_RESET);
            payload.counter_set = retained(property_id::COUNTER_SET);
        },
        parent,
    )
}

// --- Inherited UI, inherited text and misc lowering -------------------------

/// Builds the complete inherited UI payload in Rust.
fn build_inherited_ui_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index::INHERITED_UI, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    // An auto caret-color is the element's own color, which its reader resolves like
    // `currentcolor`; an auto accent-color is the system accent color for the used scheme.
    let color_or_auto = |property: u16, auto: StyleColor| -> ComputedColorOrAuto {
        let data = values.value(property).expect("the table holds the color property");
        let is_auto = matches!(data, StyleValueData::Keyword { keyword: code } if *code == keyword::AUTO);
        ComputedColorOrAuto {
            is_auto,
            color: match is_auto {
                true => auto,
                false => style_color(data, input).expect("computed UI colors are resolvable in Rust"),
            },
        }
    };
    let caret_color = color_or_auto(property_id::CARET_COLOR, StyleColor::CURRENT_COLOR);
    let accent_color = color_or_auto(
        property_id::ACCENT_COLOR,
        StyleColor::rgba(packed_color(accent_color(
            input.scheme == Some(PREFERRED_COLOR_SCHEME_DARK),
        ))),
    );

    // The cursor list, with the extractor's rules: unmappable keywords are
    // skipped, and an empty result is the predefined auto cursor.
    let mut cursors: Vec<ComputedCursor> = Vec::new();
    let mut push_cursor = |data: &StyleValueData, handle: &RetainedStyleValueData| match data {
        StyleValueData::Cursor { .. } => cursors.push(ComputedCursor {
            is_cursor_value: true,
            cursor: ComputedStyleValueHandle::from_retained(handle),
            predefined: 0,
        }),
        _ => {
            if let Some(predefined) = keyword_of(data).and_then(crate::css::css_enums::keyword_to_cursor_predefined) {
                cursors.push(ComputedCursor {
                    is_cursor_value: false,
                    cursor: ComputedStyleValueHandle::empty(),
                    predefined,
                });
            }
        }
    };
    match values.value(property_id::CURSOR) {
        Some(StyleValueData::ValueList { values: list, .. }) => {
            for item in list.as_slice() {
                push_cursor(item.data(), item);
            }
        }
        Some(data) => push_cursor(data, values.handle(property_id::CURSOR)),
        None => {}
    }
    if cursors.is_empty() {
        cursors.push(ComputedCursor {
            is_cursor_value: false,
            cursor: ComputedStyleValueHandle::empty(),
            predefined: crate::css::css_enums::cursor_predefined::AUTO,
        });
    }

    let scrollbar_color = if let Some(StyleValueData::ScrollbarColor(scrollbar_color_payload)) =
        values.value(property_id::SCROLLBAR_COLOR)
    {
        let ScrollbarColorPayload {
            thumb_color,
            track_color,
        } = &**scrollbar_color_payload;
        ComputedScrollbarColor {
            thumb_color: packed_color(
                to_color(thumb_color.data(), input).expect("computed scrollbar colors are resolvable in Rust"),
            ),
            track_color: packed_color(
                to_color(track_color.data(), input).expect("computed scrollbar colors are resolvable in Rust"),
            ),
            is_auto: false,
        }
    } else {
        ComputedScrollbarColor {
            thumb_color: 0,
            track_color: 0,
            is_auto: true,
        }
    };

    let Some(StyleValueData::ColorScheme(color_scheme_payload)) = values.value(property_id::COLOR_SCHEME) else {
        unreachable!("a computed color-scheme is a color-scheme value");
    };
    let ColorSchemePayload { schemes, only, .. } = &**color_scheme_payload;
    let color_schemes =
        RetainedUtf16FlyStringList::from_vec(schemes.as_slice().iter().map(|name| name.to_fly_string()).collect());

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::INHERITED_UI,
        &entries,
        |payload: &mut InheritedUIValues| {
            payload.caret_color = caret_color;
            payload.accent_color = accent_color;
            payload.cursor = RetainedComputedCursorList::from_vec(cursors);
            payload.scrollbar_color = scrollbar_color;
            payload.color_schemes = color_schemes;
            payload.color_scheme_only = *only;
        },
        parent,
    )
}

/// Resolves a computed length-percentage against the element's font size.
fn font_relative_length_to_css_pixels(data: &StyleValueData, input: &ColorResolutionInput) -> CssPixels {
    let context = input
        .length
        .expect("inherited text builds with a length resolution context");
    let font_size = context.font_metrics.font_size;
    let pixels = match data {
        StyleValueData::Length { value, unit } => {
            let result = crate::css::style_compute::absolutize_length(*value, *unit as usize, context);
            assert!(result.handled, "a computed inherited-text length is resolvable");
            result.px
        }
        StyleValueData::Percentage { value } => value * font_size / 100.0,
        StyleValueData::Calculated { .. } => {
            crate::css::calc::resolve_calculated_length_percentage_with_context(data, font_size, context)
                .expect("a computed inherited-text calculation resolves to a length")
        }
        _ => unreachable!("an inherited-text length is a length, percentage, or calculation"),
    };
    CssPixels::nearest_value_for(pixels)
}

/// Builds the complete inherited text payload in Rust.
fn build_inherited_text_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index::INHERITED_TEXT, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    let text_shadows = lower_shadow_layers(values, property_id::TEXT_SHADOW, input);

    let Some(StyleValueData::TextUnderlinePosition { horizontal, vertical }) =
        values.value(property_id::TEXT_UNDERLINE_POSITION)
    else {
        unreachable!("a computed text-underline-position is a text-underline-position value");
    };

    let underline_offset_data = values
        .value(property_id::TEXT_UNDERLINE_OFFSET)
        .expect("the table holds text-underline-offset");
    let underline_offset_is_auto =
        matches!(underline_offset_data, StyleValueData::Keyword { keyword: code } if *code == keyword::AUTO);

    let Some(StyleValueData::TextIndent {
        length_percentage,
        hanging,
        each_line,
    }) = values.value(property_id::TEXT_INDENT)
    else {
        unreachable!("a computed text-indent is a text-indent value");
    };

    // tab-size: a number, or a length in CSSPixels, with calculations
    // resolving by their declared type.
    let tab_size_data = values.value(property_id::TAB_SIZE).expect("the table holds tab-size");
    let (tab_size_is_number, tab_size_number, tab_size_px) = match tab_size_data {
        StyleValueData::Number { value } => (true, *value, 0),
        data @ StyleValueData::Calculated { .. } => {
            match crate::css::calc::resolve_calculated_number_without_context(data) {
                Some(number) => (true, number, 0),
                None => (false, 0.0, length_to_css_pixels(data).raw_value()),
            }
        }
        data => (false, 0.0, length_to_css_pixels(data).raw_value()),
    };

    let spacing = |property| {
        let data = values.value(property).expect("the table holds the spacing property");
        if matches!(data, StyleValueData::Keyword { keyword: code } if *code == keyword::NORMAL) {
            CssPixels::default()
        } else {
            font_relative_length_to_css_pixels(data, input)
        }
    };
    let word_spacing = spacing(property_id::WORD_SPACING);
    let letter_spacing = spacing(property_id::LETTER_SPACING);
    let underline_offset_used = if underline_offset_is_auto {
        CssPixels::from_integer(2)
    } else {
        font_relative_length_to_css_pixels(underline_offset_data, input)
    };

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::INHERITED_TEXT,
        &entries,
        |payload: &mut InheritedTextValues| {
            payload.text_shadow = RetainedComputedShadowList::from_vec(text_shadows);
            payload.text_underline_position = ComputedTextUnderlinePosition {
                horizontal: *horizontal,
                vertical: *vertical,
            };
            payload.text_underline_offset = ComputedTextUnderlineOffset {
                used_value: underline_offset_used,
                is_auto: underline_offset_is_auto,
                value: if underline_offset_is_auto {
                    ComputedStyleValueHandle::empty()
                } else {
                    ComputedStyleValueHandle::from_retained(values.handle(property_id::TEXT_UNDERLINE_OFFSET))
                },
            };
            payload.text_indent = ComputedTextIndent {
                length_percentage: ComputedStyleValueHandle::from_retained(length_percentage),
                each_line: *each_line,
                hanging: *hanging,
            };
            payload.tab_size_is_number = tab_size_is_number;
            payload.tab_size_number = tab_size_number;
            payload.tab_size_length = CssPixels::from_raw(tab_size_px);
            payload.word_spacing = word_spacing;
            payload.letter_spacing = letter_spacing;
        },
        parent,
    )
}

/// Builds the misc layout group entirely from Rust-owned canonical values.
fn build_misc_layout_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let native_appearance_disabled = values.native_appearance_disabled();
    let user_agent_margin_sides = values.user_agent_margin_sides();

    // NB: The generic builder only decodes property values, which leaves native_appearance_disabled and
    //     user_agent_margin_sides at their defaults.
    if !native_appearance_disabled && user_agent_margin_sides == 0 {
        let generic = build_generic_group(group_index::MISC_LAYOUT, values, input, used_color_scheme, parent);
        if !generic.is_null() {
            return generic;
        }
    }

    let Some(entries) = gather_group_entries(group_index::MISC_LAYOUT, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    let resolve_length = |data: &StyleValueData| -> Option<CssPixels> {
        let pixels = match data {
            StyleValueData::Length { value, unit } => crate::css::style_compute::absolute_length_to_px(*value, *unit),
            StyleValueData::Calculated { .. } => {
                crate::css::calc::resolve_calculated_length_with_context(data, input.length?)
            }
            _ => None,
        }?;
        Some(CssPixels::nearest_value_for(pixels))
    };

    let overflow_clip_margin_side = |property: u16| -> ComputedOverflowClipMarginSide {
        match values.value(property) {
            Some(StyleValueData::OverflowClipMargin {
                has_visual_box,
                visual_box,
                offset,
            }) => ComputedOverflowClipMarginSide {
                has_visual_box: *has_visual_box,
                visual_box: *visual_box,
                offset: resolve_length(offset.data()).unwrap_or(CssPixels::from_raw(0)),
            },
            _ => ComputedOverflowClipMarginSide {
                has_visual_box: false,
                visual_box: 0,
                offset: CssPixels::from_raw(0),
            },
        }
    };

    // The appearance compat keywords normalize to auto for the appearance
    // member and stay raw for computed_appearance.
    use crate::css::css_enums::appearance;
    let computed_appearance = values
        .value(property_id::APPEARANCE)
        .and_then(keyword_of)
        .and_then(crate::css::css_enums::keyword_to_appearance)
        .expect("a computed appearance keyword maps to its enum");
    let normalized_appearance = match computed_appearance {
        appearance::SEARCHFIELD
        | appearance::TEXTAREA
        | appearance::PUSH_BUTTON
        | appearance::SLIDER_HORIZONTAL
        | appearance::CHECKBOX
        | appearance::RADIO
        | appearance::SQUARE_BUTTON
        | appearance::MENULIST
        | appearance::LISTBOX
        | appearance::METER
        | appearance::PROGRESS_BAR
        | appearance::BUTTON => appearance::AUTO,
        other => other,
    };

    let Some(StyleValueData::Position(position_payload)) = values.value(property_id::OBJECT_POSITION) else {
        unreachable!("a computed object-position is a position value");
    };
    let PositionPayload { edge_x, edge_y } = &**position_payload;
    let position_offset = |edge: &crate::css::style_value::RetainedStyleValueData| -> ComputedStyleValueHandle {
        let StyleValueData::Edge { offset, .. } = edge.data() else {
            unreachable!("a computed position component is an edge value");
        };
        ComputedStyleValueHandle::from_retained(offset)
    };

    let outline_offset_data = values
        .value(property_id::OUTLINE_OFFSET)
        .expect("the table holds outline-offset");
    let Some(outline_offset) = resolve_length(outline_offset_data) else {
        return std::ptr::null();
    };
    let group_color = |property| {
        style_color(values.value(property).expect("the table holds the color"), input)
            .expect("a computed color resolves in the Rust color context")
    };
    let outline_color = group_color(property_id::OUTLINE_COLOR);
    let column_rule_color = group_color(property_id::COLUMN_RULE_COLOR);

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::MISC_LAYOUT,
        &entries,
        |payload: &mut MiscLayoutValues| {
            let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
            payload.outline_offset_style_value = retained(property_id::OUTLINE_OFFSET);
            payload.outline_offset = outline_offset;
            payload.overflow_clip_margin = ComputedOverflowClipMargin {
                left: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_LEFT),
                top: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_TOP),
                right: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_RIGHT),
                bottom: overflow_clip_margin_side(property_id::OVERFLOW_CLIP_MARGIN_BOTTOM),
            };
            payload.appearance = normalized_appearance;
            payload.computed_appearance = computed_appearance;
            payload.native_appearance_disabled = native_appearance_disabled;
            payload.user_agent_margin_sides = user_agent_margin_sides;
            payload.column_height = ComputedSize::from_data(values.handle(property_id::COLUMN_HEIGHT));
            payload.outline_color = outline_color;
            payload.column_rule_color = column_rule_color;
            payload.object_position_x = position_offset(edge_x);
            payload.object_position_y = position_offset(edge_y);
            payload.shape_margin = retained(property_id::SHAPE_MARGIN);
            payload.shape_outside = retained(property_id::SHAPE_OUTSIDE);
        },
        parent,
    )
}

/// Builds the misc interaction group entirely from Rust-owned canonical values.
fn build_misc_interaction_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let implicit_will_change = values
        .animated_overlay()
        .map_or(&[][..], |overlay| overlay.implicit_will_change.as_slice());

    // NB: The generic builder only decodes property values, which leaves implicit_will_change empty.
    if implicit_will_change.is_empty() {
        let generic = build_generic_group(group_index::MISC_INTERACTION, values, input, used_color_scheme, parent);
        if !generic.is_null() {
            return generic;
        }
    }

    let Some(entries) = gather_group_entries(group_index::MISC_INTERACTION, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    let Some(StyleValueData::ScrollbarGutter {
        value: scrollbar_gutter,
    }) = values.value(property_id::SCROLLBAR_GUTTER)
    else {
        unreachable!("a computed scrollbar-gutter is a scrollbar-gutter value");
    };

    let scroll_snap_alignment = |data: &StyleValueData| {
        keyword_of(data)
            .and_then(crate::css::css_enums::keyword_to_scroll_snap_align)
            .expect("a computed scroll-snap-align keyword maps to its enum")
    };
    let (scroll_snap_align_block, scroll_snap_align_inline) = match values.value(property_id::SCROLL_SNAP_ALIGN) {
        Some(StyleValueData::ValueList { values: list, .. }) => {
            let components = list.as_slice();
            (
                scroll_snap_alignment(components[0].data()),
                scroll_snap_alignment(components[1].data()),
            )
        }
        Some(data) => {
            let alignment = scroll_snap_alignment(data);
            (alignment, alignment)
        }
        None => unreachable!("the table holds scroll-snap-align"),
    };

    let (scroll_snap_axis, scroll_snap_strictness) = match values.value(property_id::SCROLL_SNAP_TYPE) {
        Some(StyleValueData::ValueList { values: list, .. }) => {
            let components = list.as_slice();
            (
                keyword_of(components[0].data())
                    .and_then(crate::css::css_enums::keyword_to_scroll_snap_axis)
                    .expect("a computed scroll-snap-type axis keyword maps to its enum"),
                keyword_of(components[1].data())
                    .and_then(crate::css::css_enums::keyword_to_scroll_snap_strictness)
                    .expect("a computed scroll-snap-type strictness keyword maps to its enum"),
            )
        }
        Some(data) => match keyword_of(data).expect("a computed single-value scroll-snap-type is a keyword") {
            keyword::NONE => (
                crate::css::css_enums::scroll_snap_axis::BOTH,
                crate::css::css_enums::scroll_snap_strictness::NONE,
            ),
            code => (
                crate::css::css_enums::keyword_to_scroll_snap_axis(code)
                    .expect("a computed single-keyword scroll-snap-type is none, x, y, block, inline or both"),
                crate::css::css_enums::scroll_snap_strictness::PROXIMITY,
            ),
        },
        None => unreachable!("the table holds scroll-snap-type"),
    };

    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::MISC_INTERACTION,
        &entries,
        |payload: &mut MiscInteractionValues| {
            let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
            payload.scroll_margin = ComputedLengthBox::from_data(
                values.handle(property_id::SCROLL_MARGIN_TOP),
                values.handle(property_id::SCROLL_MARGIN_RIGHT),
                values.handle(property_id::SCROLL_MARGIN_BOTTOM),
                values.handle(property_id::SCROLL_MARGIN_LEFT),
                false,
            );
            payload.scroll_padding = ComputedLengthBox::from_data(
                values.handle(property_id::SCROLL_PADDING_TOP),
                values.handle(property_id::SCROLL_PADDING_RIGHT),
                values.handle(property_id::SCROLL_PADDING_BOTTOM),
                values.handle(property_id::SCROLL_PADDING_LEFT),
                true,
            );
            payload.view_transition_name = retained(property_id::VIEW_TRANSITION_NAME);
            payload.scroll_snap_align_block = scroll_snap_align_block;
            payload.scroll_snap_align_inline = scroll_snap_align_inline;
            payload.scroll_snap_axis = scroll_snap_axis;
            payload.scroll_snap_strictness = scroll_snap_strictness;
            payload.scrollbar_gutter = *scrollbar_gutter;
            payload.will_change = retained(property_id::WILL_CHANGE);
            payload.implicit_will_change = RetainedWillChangePropertyList::from_vec(implicit_will_change.to_vec());
        },
        parent,
    )
}

/// The C++ StyleValueList::Separator::Comma discriminant, static-asserted in
/// ComputedValues.cpp.
const SEPARATOR_COMMA: u8 = 1;

/// Builds the complete text reset group in Rust.
fn build_text_reset_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    parent: GroupShares<'_>,
) -> *const c_void {
    let mut text_decoration_lines: Vec<u8> = Vec::new();
    match values.value(property_id::TEXT_DECORATION_LINE) {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::NONE => {}
        Some(StyleValueData::ValueList { values: list, .. }) => {
            for item in list.as_slice() {
                text_decoration_lines.push(
                    keyword_of(item.data())
                        .and_then(crate::css::css_enums::keyword_to_text_decoration_line)
                        .expect("a computed text-decoration-line item maps to its enum"),
                );
            }
        }
        _ => unreachable!("a computed text-decoration-line is none or a value list"),
    }

    // The builder reads the thickness value only for the length kind.
    let thickness_value = values.handle(property_id::TEXT_DECORATION_THICKNESS);
    let thickness_kind = match thickness_value.optional_data() {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::AUTO => 0u8,
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::FROM_FONT => 1u8,
        Some(_) => 2u8,
        None => unreachable!("the table holds text-decoration-thickness"),
    };

    let mut discard_before = false;
    let mut discard_after = false;
    let mut discard_inner = false;
    match values.value(property_id::WHITE_SPACE_TRIM) {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::NONE => {}
        Some(StyleValueData::ValueList { values: list, .. }) => {
            for item in list.as_slice() {
                match keyword_of(item.data()) {
                    Some(keyword::DISCARD_BEFORE) => discard_before = true,
                    Some(keyword::DISCARD_AFTER) => discard_after = true,
                    Some(keyword::DISCARD_INNER) => discard_inner = true,
                    _ => unreachable!("the white-space-trim keywords cover every list item"),
                }
            }
        }
        _ => unreachable!("a computed white-space-trim is none or a value list"),
    }

    let text_decoration_style = keyword_of(
        values
            .value(property_id::TEXT_DECORATION_STYLE)
            .expect("the table holds text-decoration-style"),
    )
    .and_then(crate::css::css_enums::keyword_to_text_decoration_style)
    .expect("a computed text-decoration-style maps to its enum");
    let text_decoration_color = style_color(
        values
            .value(property_id::TEXT_DECORATION_COLOR)
            .expect("the table holds text-decoration-color"),
        input,
    )
    .expect("a computed text-decoration-color resolves in the Rust color context");

    rust_build_text_reset_group(
        group_index::TEXT_RESET,
        &text_decoration_lines,
        thickness_kind,
        thickness_value,
        text_decoration_style,
        text_decoration_color,
        discard_before,
        discard_after,
        discard_inner,
        parent,
    )
}

/// The C++ PositionArea codes a value's keywords map to, fanning out a value
/// list and skipping non-area keywords like the extractor's helper.
fn position_area_codes(data: &StyleValueData) -> Vec<u8> {
    let mut codes = Vec::new();
    let mut append = |data: &StyleValueData| {
        if let Some(code) = keyword_of(data).and_then(crate::css::css_enums::keyword_to_position_area) {
            codes.push(code);
        }
    };
    match data {
        StyleValueData::ValueList { values: list, .. } => {
            for item in list.as_slice() {
                append(item.data());
            }
        }
        data => append(data),
    }
    codes
}

/// Builds the complete anchor-positioning payload in Rust.
fn build_anchor_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let generic = build_generic_group(group_index::ANCHOR, values, input, used_color_scheme, parent);
    if !generic.is_null() {
        return generic;
    }
    let Some(entries) = gather_group_entries(group_index::ANCHOR, values, input, used_color_scheme) else {
        return std::ptr::null();
    };

    let custom_idents = |property| {
        let mut names = Vec::new();
        let mut append = |data: &StyleValueData| {
            if let StyleValueData::CustomIdent { custom_ident } = data {
                names.push(custom_ident.to_fly_string());
            }
        };
        match values.value(property) {
            Some(StyleValueData::ValueList { values: list, .. }) => {
                for item in list.as_slice() {
                    append(item.data());
                }
            }
            Some(data) => append(data),
            None => {}
        }
        names
    };
    let anchor_names = custom_idents(property_id::ANCHOR_NAME);
    let anchor_scope_all = matches!(
        values.value(property_id::ANCHOR_SCOPE),
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::ALL
    );
    let anchor_scope_names = custom_idents(property_id::ANCHOR_SCOPE);

    let (position_anchor_type, position_anchor_name) = match values.value(property_id::POSITION_ANCHOR) {
        Some(StyleValueData::CustomIdent { custom_ident }) => (3u8, custom_ident.to_fly_string()),
        Some(StyleValueData::Keyword { keyword: code }) => match *code {
            keyword::NORMAL => (0u8, RetainedUtf16FlyString::none()),
            keyword::NONE => (1u8, RetainedUtf16FlyString::none()),
            keyword::AUTO => (2u8, RetainedUtf16FlyString::none()),
            _ => unreachable!("a computed position-anchor keyword is normal, none or auto"),
        },
        _ => unreachable!("a computed position-anchor is a keyword or a custom ident"),
    };

    let position_area_keywords = position_area_codes(
        values
            .value(property_id::POSITION_AREA)
            .expect("the table holds position-area"),
    );

    // position-try-fallbacks, with the extractor's item rules: an item whose
    // keywords form a position area keeps only the area, and everything else
    // fans out (one level deep) into a name and try tactics.
    let mut position_try_fallbacks: Vec<ComputedPositionTryFallback> = Vec::new();
    let mut append_fallback = |data: &StyleValueData| {
        let mut fallback = ComputedPositionTryFallback {
            name: RetainedUtf16FlyString::none(),
            tactics: [0; 5],
            tactic_count: 0,
            has_position_area: false,
            position_area: RetainedPositionAreaList::from_vec(Vec::new()),
        };
        let apply_item = |fallback: &mut ComputedPositionTryFallback, data: &StyleValueData| {
            if let StyleValueData::CustomIdent { custom_ident } = data {
                fallback.name = custom_ident.to_fly_string();
            } else if let Some(tactic) = keyword_of(data).and_then(crate::css::css_enums::keyword_to_try_tactic) {
                assert!(
                    fallback.tactic_count < 5,
                    "a try tactic list holds at most five tactics"
                );
                fallback.tactics[fallback.tactic_count] = tactic;
                fallback.tactic_count += 1;
            }
        };
        let area = position_area_codes(data);
        if !area.is_empty() {
            fallback.has_position_area = true;
            fallback.position_area = RetainedPositionAreaList::from_vec(area);
        } else if let StyleValueData::ValueList { values: list, .. } = data {
            for item in list.as_slice() {
                if let StyleValueData::ValueList { values: children, .. } = item.data() {
                    for child in children.as_slice() {
                        apply_item(&mut fallback, child.data());
                    }
                } else {
                    apply_item(&mut fallback, item.data());
                }
            }
        } else {
            apply_item(&mut fallback, data);
        }
        position_try_fallbacks.push(fallback);
    };
    match values.value(property_id::POSITION_TRY_FALLBACKS) {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::NONE => {}
        Some(StyleValueData::ValueList {
            values: list,
            separator,
            ..
        }) if *separator == SEPARATOR_COMMA => {
            for item in list.as_slice() {
                append_fallback(item.data());
            }
        }
        Some(data) => append_fallback(data),
        None => unreachable!("the table holds position-try-fallbacks"),
    }

    let position_try_order = match values.value(property_id::POSITION_TRY_ORDER) {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::NORMAL => None,
        Some(data) => keyword_of(data).and_then(crate::css::css_enums::keyword_to_try_order),
        None => unreachable!("the table holds position-try-order"),
    };

    // position-visibility, with the extractor's keyword fan-out; the
    // anchors-visible default flips to false before the keywords apply.
    let mut always = false;
    let mut anchors_valid = false;
    let mut anchors_visible = false;
    let mut no_overflow = false;
    {
        let mut apply_keyword = |code: u16| match code {
            keyword::ANCHORS_VALID => anchors_valid = true,
            keyword::ANCHORS_VISIBLE => anchors_visible = true,
            keyword::NO_OVERFLOW => no_overflow = true,
            _ => {}
        };
        match values.value(property_id::POSITION_VISIBILITY) {
            Some(StyleValueData::Keyword { keyword: code }) => {
                always = *code == keyword::ALWAYS;
                apply_keyword(*code);
            }
            Some(StyleValueData::ValueList { values: list, .. }) => {
                for item in list.as_slice() {
                    if let Some(code) = keyword_of(item.data()) {
                        apply_keyword(code);
                    }
                }
            }
            _ => unreachable!("a computed position-visibility is a keyword or a value list"),
        }
    }

    let built = AnchorValues {
        anchor_names: RetainedUtf16FlyStringList::from_vec(anchor_names),
        anchor_scope_all,
        anchor_scope_names: RetainedUtf16FlyStringList::from_vec(anchor_scope_names),
        position_anchor_type,
        position_anchor_name,
        position_area: RetainedPositionAreaList::from_vec(position_area_keywords),
        position_try_fallbacks: RetainedPositionTryFallbackList::from_vec(position_try_fallbacks),
        has_position_try_order: position_try_order.is_some(),
        position_try_order: position_try_order.unwrap_or(0),
        position_visibility_always: always,
        position_visibility_anchors_valid: anchors_valid,
        position_visibility_anchors_visible: anchors_visible,
        position_visibility_no_overflow: no_overflow,
    };
    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::ANCHOR,
        &entries,
        |payload: &mut AnchorValues| *payload = built,
        parent,
    )
}

/// The keyword code of a slot that must hold an enum keyword.
fn required_keyword_code(values: &LonghandSource, property: u16, map: fn(u16) -> Option<u8>) -> u8 {
    values
        .value(property)
        .and_then(keyword_of)
        .and_then(map)
        .expect("a computed enum-keyword slot maps to its enum")
}

/// The resolved integer of an integer-or-calc slot, mirroring the C++
/// int_from_style_value.
fn required_integer(data: &StyleValueData) -> i32 {
    match data {
        StyleValueData::Integer { value } => *value,
        data @ StyleValueData::Calculated { .. } => resolve_calculated_integer_without_context(data)
            .expect("a computed integer calculation resolves without context"),
        _ => unreachable!("a computed integer slot holds an integer or a calculation"),
    }
}

/// The resolved number of a number-or-calc value, mirroring the C++
/// number_from_style_value without a percentage basis.
fn required_number(data: &StyleValueData) -> f64 {
    match data {
        StyleValueData::Number { value } => *value,
        data @ StyleValueData::Calculated { .. } => crate::css::calc::resolve_calculated_number_without_context(data)
            .expect("a computed number calculation resolves without context"),
        _ => unreachable!("a computed number slot holds a number or a calculation"),
    }
}

/// Builds the box group's payload from the table slots. The box type
/// transformation happened at compute time, so the display slot already
/// holds the transformed value; only the pre-transformation display is a
/// C++-side member and arrives through the build inputs.
fn build_box_group(
    values: &LonghandSource,
    display_before_transformation_raw: u32,
    parent: GroupShares<'_>,
) -> *const c_void {
    use crate::css::computed_value_types::{
        BoxValues, ComputedAspectRatio, ComputedContainIntrinsicSize, ComputedVerticalAlign,
    };
    use crate::css::css_enums::{
        keyword_to_baseline_source, keyword_to_continue_value, keyword_to_field_sizing, keyword_to_resize,
        keyword_to_text_overflow, keyword_to_vertical_align,
    };

    let display = match values.value(property_id::DISPLAY) {
        Some(StyleValueData::Display { raw }) => crate::css::display::FfiDisplay::from_raw(*raw),
        _ => unreachable!("a computed display is a display value"),
    };

    let grid_auto_flow = match values.value(property_id::GRID_AUTO_FLOW) {
        Some(StyleValueData::GridAutoFlow { row, dense }) => (*row, *dense),
        _ => (true, false),
    };

    let column_count = match values.value(property_id::COLUMN_COUNT) {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::AUTO => None,
        Some(data) => Some(required_integer(data)),
        None => unreachable!("the table holds column-count"),
    };

    let z_index = match values.value(property_id::Z_INDEX) {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::AUTO => None,
        Some(data) => Some(required_integer(data)),
        None => unreachable!("the table holds z-index"),
    };

    let vertical_align = match values.value(property_id::VERTICAL_ALIGN) {
        Some(StyleValueData::Keyword { keyword: code }) => ComputedVerticalAlign {
            is_keyword: true,
            keyword: keyword_to_vertical_align(*code).expect("a computed vertical-align keyword maps to its enum"),
            value: ComputedStyleValueHandle::empty(),
        },
        Some(_) => ComputedVerticalAlign {
            is_keyword: false,
            keyword: 0,
            value: ComputedStyleValueHandle::from_retained(values.handle(property_id::VERTICAL_ALIGN)),
        },
        None => unreachable!("the table holds vertical-align"),
    };

    // aspect-ratio, with the extractor's degenerate-ratio handling; absent
    // ratios keep zeroed components so payload equality stays field-wise.
    let resolved_ratio = |data: &StyleValueData| -> (f64, f64) {
        let StyleValueData::Ratio(ratio_payload) = data else {
            unreachable!("a computed aspect-ratio component is a ratio");
        };
        let RatioPayload { numerator, denominator } = &**ratio_payload;
        (required_number(numerator.data()), required_number(denominator.data()))
    };
    let ratio_is_degenerate = |(numerator, denominator): (f64, f64)| {
        !numerator.is_finite() || numerator == 0.0 || !denominator.is_finite() || denominator == 0.0
    };
    let initial_aspect_ratio = ComputedAspectRatio {
        use_natural_aspect_ratio_if_available: true,
        has_preferred_ratio: false,
        preferred_ratio_numerator: 0.0,
        preferred_ratio_denominator: 0.0,
        computed_use_natural_aspect_ratio_if_available: true,
        has_computed_ratio: false,
        computed_ratio_numerator: 0.0,
        computed_ratio_denominator: 0.0,
    };
    // https://drafts.csswg.org/css-sizing-4/#intrinsic-size-override
    let contain_intrinsic_size_for = |property: u16| -> ComputedContainIntrinsicSize {
        let none = ComputedContainIntrinsicSize {
            has_auto: false,
            has_length: false,
            length_px: 0.0,
        };
        match values.value(property) {
            Some(StyleValueData::ValueList { values: list, .. }) => {
                let items = list.as_slice();
                if items.len() != 2 {
                    return none;
                }
                match items[1].data() {
                    StyleValueData::Keyword { keyword: code } if *code == keyword::NONE => {
                        ComputedContainIntrinsicSize {
                            has_auto: true,
                            has_length: false,
                            length_px: 0.0,
                        }
                    }
                    data => ComputedContainIntrinsicSize {
                        has_auto: true,
                        has_length: true,
                        length_px: length_to_px_unrounded(data),
                    },
                }
            }
            Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::NONE => none,
            Some(data) => ComputedContainIntrinsicSize {
                has_auto: false,
                has_length: true,
                length_px: length_to_px_unrounded(data),
            },
            None => none,
        }
    };
    let contain_intrinsic_width = contain_intrinsic_size_for(property_id::CONTAIN_INTRINSIC_WIDTH);
    let contain_intrinsic_height = contain_intrinsic_size_for(property_id::CONTAIN_INTRINSIC_HEIGHT);

    let aspect_ratio = match values.value(property_id::ASPECT_RATIO) {
        Some(StyleValueData::ValueList { values: list, .. }) => {
            let items = list.as_slice();
            let auto_then_ratio = items.len() == 2
                && matches!(items[0].data(), StyleValueData::Keyword { keyword: code } if *code == keyword::AUTO)
                && matches!(items[1].data(), StyleValueData::Ratio { .. });
            if auto_then_ratio {
                let ratio = resolved_ratio(items[1].data());
                ComputedAspectRatio {
                    use_natural_aspect_ratio_if_available: true,
                    has_preferred_ratio: !ratio_is_degenerate(ratio),
                    preferred_ratio_numerator: if ratio_is_degenerate(ratio) { 0.0 } else { ratio.0 },
                    preferred_ratio_denominator: if ratio_is_degenerate(ratio) { 0.0 } else { ratio.1 },
                    computed_use_natural_aspect_ratio_if_available: true,
                    has_computed_ratio: true,
                    computed_ratio_numerator: ratio.0,
                    computed_ratio_denominator: ratio.1,
                }
            } else {
                initial_aspect_ratio
            }
        }
        Some(data @ StyleValueData::Ratio { .. }) => {
            let ratio = resolved_ratio(data);
            let degenerate = ratio_is_degenerate(ratio);
            ComputedAspectRatio {
                use_natural_aspect_ratio_if_available: degenerate,
                has_preferred_ratio: !degenerate,
                preferred_ratio_numerator: if degenerate { 0.0 } else { ratio.0 },
                preferred_ratio_denominator: if degenerate { 0.0 } else { ratio.1 },
                computed_use_natural_aspect_ratio_if_available: false,
                has_computed_ratio: true,
                computed_ratio_numerator: ratio.0,
                computed_ratio_denominator: ratio.1,
            }
        }
        _ => initial_aspect_ratio,
    };

    // contain, with the extractor's keyword fan-out.
    let mut size_containment = false;
    let mut inline_size_containment = false;
    let mut layout_containment = false;
    let mut style_containment = false;
    let mut paint_containment = false;
    {
        let mut apply_containment_keyword = |code: u16| match code {
            keyword::SIZE => size_containment = true,
            keyword::INLINE_SIZE => inline_size_containment = true,
            keyword::LAYOUT => layout_containment = true,
            keyword::STYLE => style_containment = true,
            keyword::PAINT => paint_containment = true,
            _ => {}
        };
        match values.value(property_id::CONTAIN) {
            Some(StyleValueData::Keyword { keyword: code }) => match *code {
                keyword::NONE => {}
                keyword::STRICT => {
                    size_containment = true;
                    layout_containment = true;
                    paint_containment = true;
                    style_containment = true;
                }
                keyword::CONTENT => {
                    layout_containment = true;
                    paint_containment = true;
                    style_containment = true;
                }
                other => apply_containment_keyword(other),
            },
            Some(StyleValueData::ValueList { values: list, .. }) => {
                for item in list.as_slice() {
                    if let Some(code) = keyword_of(item.data()) {
                        apply_containment_keyword(code);
                    }
                }
            }
            _ => {}
        }
    }

    // https://drafts.csswg.org/css-contain-2/#skips-its-contents
    // When an element skips its contents, the user agent must change the used value of the contain property so as to
    // turn on layout containment, style containment, paint containment, and size containment.
    if matches!(values.value(property_id::CONTENT_VISIBILITY), Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::HIDDEN)
    {
        size_containment = true;
        layout_containment = true;
        style_containment = true;
        paint_containment = true;
    }

    // container-type, which the extractor only fans out from a value list.
    let mut is_size_container = false;
    let mut is_inline_size_container = false;
    let mut is_scroll_state_container = false;
    if let Some(StyleValueData::ValueList { values: list, .. }) = values.value(property_id::CONTAINER_TYPE) {
        for item in list.as_slice() {
            match keyword_of(item.data()) {
                Some(keyword::SIZE) => is_size_container = true,
                Some(keyword::INLINE_SIZE) => is_inline_size_container = true,
                Some(keyword::SCROLL_STATE) => is_scroll_state_container = true,
                _ => {}
            }
        }
    }

    let mut container_names: Vec<RetainedUtf16FlyString> = Vec::new();
    match values.value(property_id::CONTAINER_NAME) {
        Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::NONE => {}
        Some(StyleValueData::ValueList { values: list, .. }) => {
            for item in list.as_slice() {
                let StyleValueData::CustomIdent { custom_ident } = item.data() else {
                    unreachable!("a computed container-name item is a custom ident");
                };
                container_names.push(custom_ident.to_fly_string());
            }
        }
        Some(StyleValueData::CustomIdent { custom_ident }) => container_names.push(custom_ident.to_fly_string()),
        _ => unreachable!("a computed container-name is none or custom idents"),
    }

    let built = BoxValues {
        display,
        display_before_box_type_transformation: crate::css::display::FfiDisplay::from_raw(
            display_before_transformation_raw,
        ),
        field_sizing: required_keyword_code(values, property_id::FIELD_SIZING, keyword_to_field_sizing),
        baseline_source: required_keyword_code(values, property_id::BASELINE_SOURCE, keyword_to_baseline_source),
        resize: required_keyword_code(values, property_id::RESIZE, keyword_to_resize),
        text_overflow: required_keyword_code(values, property_id::TEXT_OVERFLOW, keyword_to_text_overflow),
        grid_auto_flow_row: grid_auto_flow.0,
        grid_auto_flow_dense: grid_auto_flow.1,
        column_width: ComputedSize::from_data(values.handle(property_id::COLUMN_WIDTH)),
        column_count_has_value: column_count.is_some(),
        column_count: column_count.unwrap_or(0),
        continue_: required_keyword_code(values, property_id::CONTINUE, keyword_to_continue_value),
        max_lines: match values.value(property_id::MAX_LINES) {
            Some(StyleValueData::Keyword { keyword: code }) if *code == keyword::NONE => 0,
            Some(data) => required_integer(data),
            None => unreachable!("the table holds max-lines"),
        },
        has_z_index: z_index.is_some(),
        z_index: z_index.unwrap_or(0),
        vertical_align,
        aspect_ratio,
        contain_intrinsic_width,
        contain_intrinsic_height,
        size_containment,
        inline_size_containment,
        layout_containment,
        style_containment,
        paint_containment,
        is_size_container,
        is_inline_size_container,
        is_scroll_state_container,
        container_name: RetainedUtf16FlyStringList::from_vec(container_names),
    };
    crate::css::computed_values::rust_build_box_group(group_index::BOX, built, parent)
}

/// Builds the inherited font group from canonical Rust longhands and the
/// platform font resources supplied by C++.
unsafe fn build_font_group(
    values: &LonghandSource,
    inputs: &FfiFontGroupBuildInputs,
    parent: GroupShares<'_>,
) -> *const c_void {
    use crate::css::css_pixels::CssPixels;

    assert!(!inputs.first_available_font.is_null());
    assert!(!inputs.font_cascade_list.is_null());
    let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
    let built = FontValues {
        font_size: CssPixels::from_raw(inputs.font_size_raw),
        resolved_line_height_used: CssPixels::from_raw(inputs.line_height_used_raw),
        font_variant_emoji: inputs.font_variant_emoji,
        resolved_font_ascent: inputs.font_ascent,
        resolved_font_descent: inputs.font_descent,
        resolved_font_x_height: inputs.font_x_height,
        resolved_font_cap_height: inputs.font_cap_height,
        resolved_font_zero_advance: inputs.font_zero_advance,
        resolved_first_available_font: inputs.first_available_font,
        // SAFETY: The non-null check above and the caller's guarantee make the
        // list live for the call; the handle keeps it live afterwards.
        font_cascade_list: unsafe { libgfx_rust::font::FontCascadeListHandle::retain(inputs.font_cascade_list) },
        // SAFETY: As above. A cascade the font computer published carries a frozen snapshot; one
        // built for something else (canvas, a unit test) does not, and never reaches a stage.
        frozen_font_list: unsafe { libgfx_rust::font::frozen_font_list_of(inputs.font_cascade_list) },
        font_weight: inputs.font_weight,
        font_width: inputs.font_width,
        math_shift: inputs.math_shift,
        math_style: inputs.math_style,
        math_depth: inputs.math_depth,
        font_family: retained(property_id::FONT_FAMILY),
        font_style: retained(property_id::FONT_STYLE),
        font_optical_sizing: retained(property_id::FONT_OPTICAL_SIZING),
        font_synthesis_weight: retained(property_id::FONT_SYNTHESIS_WEIGHT),
        font_synthesis_style: retained(property_id::FONT_SYNTHESIS_STYLE),
        font_feature_settings: retained(property_id::FONT_FEATURE_SETTINGS),
        font_kerning: retained(property_id::FONT_KERNING),
        font_language_override: retained(property_id::FONT_LANGUAGE_OVERRIDE),
        font_variant_alternates: retained(property_id::FONT_VARIANT_ALTERNATES),
        font_variant_caps: retained(property_id::FONT_VARIANT_CAPS),
        font_variant_east_asian: retained(property_id::FONT_VARIANT_EAST_ASIAN),
        font_variant_ligatures: retained(property_id::FONT_VARIANT_LIGATURES),
        font_variant_numeric: retained(property_id::FONT_VARIANT_NUMERIC),
        font_variant_position: retained(property_id::FONT_VARIANT_POSITION),
        font_variation_settings: retained(property_id::FONT_VARIATION_SETTINGS),
        text_rendering: retained(property_id::TEXT_RENDERING),
        line_height: retained(property_id::LINE_HEIGHT),
        math_shift_value: retained(property_id::MATH_SHIFT),
        math_style_value: retained(property_id::MATH_STYLE),
        math_depth_value: retained(property_id::MATH_DEPTH),
        font_size_value: retained(property_id::FONT_SIZE),
    };
    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::FONT,
        &[],
        |payload: &mut FontValues| *payload = built,
        parent,
    )
}

/// Builds the animation group from the canonical Rust longhand values.
fn build_animation_group(
    values: &LonghandSource,
    input: &ColorResolutionInput,
    used_color_scheme: u8,
    parent: GroupShares<'_>,
) -> *const c_void {
    let Some(entries) = gather_group_entries(group_index::ANIMATION, values, input, used_color_scheme) else {
        return std::ptr::null();
    };
    let retained = |property| ComputedStyleValueHandle::from_retained(values.handle(property));
    let is_single_zero_time = |property| {
        let value = values.handle(property).data();
        let StyleValueData::ValueList { values, .. } = value else {
            return false;
        };
        let [item] = values.as_slice() else {
            return false;
        };
        matches!(item.data(), StyleValueData::Time { value, .. } if *value == 0.0)
    };
    crate::css::computed_values::build_group_payload_with_rust_fill(
        group_index::ANIMATION,
        &entries,
        |payload: &mut AnimationValues| {
            payload.animation_name = retained(property_id::ANIMATION_NAME);
            payload.animation_composition = retained(property_id::ANIMATION_COMPOSITION);
            payload.animation_delay = retained(property_id::ANIMATION_DELAY);
            payload.animation_direction = retained(property_id::ANIMATION_DIRECTION);
            payload.animation_duration = retained(property_id::ANIMATION_DURATION);
            payload.animation_fill_mode = retained(property_id::ANIMATION_FILL_MODE);
            payload.animation_iteration_count = retained(property_id::ANIMATION_ITERATION_COUNT);
            payload.animation_play_state = retained(property_id::ANIMATION_PLAY_STATE);
            payload.animation_timeline = retained(property_id::ANIMATION_TIMELINE);
            payload.animation_range_start = retained(property_id::ANIMATION_RANGE_START);
            payload.animation_range_end = retained(property_id::ANIMATION_RANGE_END);
            payload.animation_timing_function = retained(property_id::ANIMATION_TIMING_FUNCTION);
            payload.scroll_timeline_name = retained(property_id::SCROLL_TIMELINE_NAME);
            payload.scroll_timeline_axis = retained(property_id::SCROLL_TIMELINE_AXIS);
            payload.timeline_scope = retained(property_id::TIMELINE_SCOPE);
            payload.view_timeline_name = retained(property_id::VIEW_TIMELINE_NAME);
            payload.view_timeline_axis = retained(property_id::VIEW_TIMELINE_AXIS);
            payload.view_timeline_inset = retained(property_id::VIEW_TIMELINE_INSET);
            payload.transition_property = retained(property_id::TRANSITION_PROPERTY);
            payload.transition_duration = retained(property_id::TRANSITION_DURATION);
            payload.transition_timing_function = retained(property_id::TRANSITION_TIMING_FUNCTION);
            payload.transition_delay = retained(property_id::TRANSITION_DELAY);
            payload.transition_behavior = retained(property_id::TRANSITION_BEHAVIOR);
            payload.transition_delay_and_duration_are_single_zero = is_single_zero_time(property_id::TRANSITION_DELAY)
                && is_single_zero_time(property_id::TRANSITION_DURATION);
        },
        parent,
    )
}

/// The element's own resolved color as the group builders consume it: the computed `color` of
/// `values`, resolved against the initial color the way the C++ build seeds its context.
fn own_color_from_source(
    values: &LonghandSource<'_>,
    used_color_scheme: u8,
    length: Option<&crate::css::style_compute::FfiLengthResolutionContext>,
) -> Option<u32> {
    let input = ColorResolutionInput {
        scheme: Some(used_color_scheme),
        current_color: Some(Rgba {
            r: 0,
            g: 0,
            b: 0,
            a: 255,
        }),
        current_color_value: None,
        length,
        channels: None,
    };
    to_color(values.value(property_id::COLOR)?, &input).map(packed_color)
}

/// The used color scheme of the values `values` holds.
pub(crate) fn used_color_scheme_of_source(values: &LonghandSource<'_>) -> u8 {
    u8::try_from(values.effective_color_scheme()).unwrap_or_else(|_| {
        debug_assert!(false, "a driven table without a used color scheme");
        crate::css::color_resolution::PREFERRED_COLOR_SCHEME_LIGHT
    })
}

/// The used color scheme and the element's own resolved `color`, as [`assembly_color_inputs`]
/// answers them, from the values `values` holds.
pub(crate) fn assembly_color_inputs_from_source(
    values: &LonghandSource<'_>,
    length: &crate::css::style_compute::FfiLengthResolutionContext,
) -> (u8, u32) {
    let used_color_scheme = used_color_scheme_of_source(values);
    let current_color = own_color_from_source(values, used_color_scheme, Some(length)).unwrap_or_else(|| {
        debug_assert!(false, "a driven table whose color does not resolve");
        0xff00_0000
    });
    (used_color_scheme, current_color)
}

/// One group's payload for a record assembled as [`assemble_group_from_table`] does, but from the
/// values `values` holds.
///
/// # Safety
/// `parent` must be a valid payload of the group or null.
pub(crate) unsafe fn assemble_group_from_source(
    values: &LonghandSource<'_>,
    group: usize,
    font: Option<&FfiFontGroupBuildInputs>,
    parent: GroupShares<'_>,
    (used_color_scheme, current_color): (u8, u32),
    length: &crate::css::style_compute::FfiLengthResolutionContext,
) -> *const c_void {
    let payload = if group == group_index::FONT {
        // SAFETY: The caller passes a valid parent payload or null.
        font.map(|font| unsafe { build_font_group(values, font, parent) })
            .filter(|payload| !payload.is_null())
    } else {
        rebuild_group_from_source(values, group, parent, current_color, used_color_scheme, Some(length))
    };
    payload.unwrap_or_else(|| {
        debug_assert!(false, "style group {group} declined a driven table");
        parent.default_retained()
    })
}

/// The engine: the background group `source` holds, but with the background color `values` holds,
/// which is all an element whose other background longhands hold the values of `source`'s needs.
/// The payload carries one reference for the caller.
///
/// # Safety
/// `source` must be a live background group payload.
pub(crate) unsafe fn patch_background_color(
    values: &LonghandSource<'_>,
    source: *const c_void,
    parent: GroupShares<'_>,
    (used_color_scheme, current_color): (u8, u32),
    length: &crate::css::style_compute::FfiLengthResolutionContext,
) -> *const c_void {
    let input = ColorResolutionInput {
        scheme: Some(used_color_scheme),
        current_color: Some(Rgba {
            r: (current_color >> 16) as u8,
            g: (current_color >> 8) as u8,
            b: current_color as u8,
            a: (current_color >> 24) as u8,
        }),
        current_color_value: values.value(property_id::COLOR),
        length: Some(length),
        channels: None,
    };
    let background_color = style_color(
        values
            .value(property_id::BACKGROUND_COLOR)
            .expect("background-color has a computed value"),
        &input,
    )
    .expect("a computed background-color resolves in Rust");
    let style_value = ComputedStyleValueHandle::from_retained(values.handle(property_id::BACKGROUND_COLOR));
    // SAFETY: The caller passes a live background group payload.
    unsafe {
        crate::css::computed_values::patch_group_payload(
            group_index::BACKGROUND,
            source,
            |payload: &mut BackgroundValues| {
                payload.background_color = background_color;
                payload.background_color_style_value = style_value;
            },
            parent,
        )
    }
}

/// Rebuilds one of the groups whose payload is a function of the element's computed longhand values, its own `color`
/// and its used color scheme alone, reading the values from `values`.
pub(crate) fn rebuild_group_from_source(
    values: &LonghandSource<'_>,
    group: usize,
    parent: GroupShares<'_>,
    current_color: u32,
    used_color_scheme: u8,
    length: Option<&crate::css::style_compute::FfiLengthResolutionContext>,
) -> Option<*const c_void> {
    let input = ColorResolutionInput {
        scheme: Some(used_color_scheme),
        current_color: Some(Rgba {
            r: (current_color >> 16) as u8,
            g: (current_color >> 8) as u8,
            b: current_color as u8,
            a: (current_color >> 24) as u8,
        }),
        current_color_value: values.value(property_id::COLOR),
        length,
        channels: None,
    };
    let payload = match group {
        // The font group needs platform font resources the table does not hold.
        group_index::FONT => return None,
        group_index::BOX => build_box_group(values, values.display_before_box_type_transformation(), parent),
        group_index::SIZING => build_sizing_group(
            group,
            values.handle(property_id::WIDTH),
            values.handle(property_id::MIN_WIDTH),
            values.handle(property_id::MAX_WIDTH),
            values.handle(property_id::HEIGHT),
            values.handle(property_id::MIN_HEIGHT),
            values.handle(property_id::MAX_HEIGHT),
            parent,
        ),
        group_index::SURROUND => build_surround_group(values, parent),
        group_index::ANIMATION => build_animation_group(values, &input, used_color_scheme, parent),
        group_index::ANCHOR => build_anchor_group(values, &input, used_color_scheme, parent),
        group_index::TEXT_RESET => build_text_reset_group(values, &input, parent),
        group_index::ALIGNMENT => build_alignment_group(values, parent),
        group_index::SVG_RESET => build_svg_reset_group(values, &input, parent),
        group_index::GRID => build_grid_group(values, parent),
        group_index::TRANSFORM => build_transform_group(values, &input, used_color_scheme, parent),
        group_index::EFFECTS => build_effects_group(values, &input, used_color_scheme, parent),
        group_index::INHERITED_UI => build_inherited_ui_group(values, &input, used_color_scheme, parent),
        group_index::INHERITED_TEXT => build_inherited_text_group(values, &input, used_color_scheme, parent),
        group_index::MISC_LAYOUT => build_misc_layout_group(values, &input, used_color_scheme, parent),
        group_index::MISC_INTERACTION => build_misc_interaction_group(values, &input, used_color_scheme, parent),
        group_index::INHERITED_SVG => build_inherited_svg_group(values, &input, used_color_scheme, parent),
        group_index::INHERITED_LIST_TABLE => {
            build_inherited_list_table_group(values, &input, used_color_scheme, parent)
        }
        group_index::CONTENT => build_content_group(values, &input, used_color_scheme, parent),
        group_index::MASK => build_mask_group(values, &input, used_color_scheme, parent),
        group_index::BACKGROUND => build_background_group(values, &input, used_color_scheme, parent),
        group_index::BORDER => build_border_group(values, &input, used_color_scheme, parent),
        _ => return None,
    };
    (!payload.is_null()).then_some(payload)
}

/// Builds every applied group's payload from `values`, writing one payload per applied group into `out` and null for
/// every other group. Each payload carries one reference for the caller.
///
/// # Safety
/// The pointers `inputs` borrow must stay live across the call.
pub(crate) unsafe fn build_group_payloads(
    values: &LonghandSource<'_>,
    groups_to_apply: u32,
    inputs: &GroupBuildInputs<'_>,
    out: &mut [*const c_void; group_index::COUNT],
) {
    let input = *inputs.color_input;

    for (group, out_payload) in out.iter_mut().enumerate() {
        *out_payload = std::ptr::null();
        if (groups_to_apply >> group) & 1 == 0 {
            continue;
        }
        let parent = GroupShares::new(inputs.defaults, group, None);
        // SAFETY: Gathered pointers name live table or override data.
        let payload = unsafe {
            match group {
                group_index::FONT => build_font_group(
                    values,
                    inputs.font.expect("an applied font group has platform font inputs"),
                    parent,
                ),
                group_index::BOX => build_box_group(values, inputs.box_display_before_transformation_raw, parent),
                group_index::SIZING => build_sizing_group(
                    group,
                    values.handle(property_id::WIDTH),
                    values.handle(property_id::MIN_WIDTH),
                    values.handle(property_id::MAX_WIDTH),
                    values.handle(property_id::HEIGHT),
                    values.handle(property_id::MIN_HEIGHT),
                    values.handle(property_id::MAX_HEIGHT),
                    parent,
                ),
                group_index::SURROUND => build_surround_group(values, parent),
                group_index::ANIMATION => build_animation_group(values, &input, inputs.used_color_scheme, parent),
                group_index::ANCHOR => build_anchor_group(values, &input, inputs.used_color_scheme, parent),
                group_index::TEXT_RESET => build_text_reset_group(values, &input, parent),
                group_index::ALIGNMENT => build_alignment_group(values, parent),
                group_index::SVG_RESET => build_svg_reset_group(values, &input, parent),
                group_index::GRID => build_grid_group(values, parent),
                group_index::TRANSFORM => build_transform_group(values, &input, inputs.used_color_scheme, parent),
                group_index::EFFECTS => build_effects_group(values, &input, inputs.used_color_scheme, parent),
                group_index::INHERITED_UI => build_inherited_ui_group(values, &input, inputs.used_color_scheme, parent),
                group_index::INHERITED_TEXT => {
                    build_inherited_text_group(values, &input, inputs.used_color_scheme, parent)
                }
                group_index::MISC_LAYOUT => build_misc_layout_group(values, &input, inputs.used_color_scheme, parent),
                group_index::MISC_INTERACTION => {
                    build_misc_interaction_group(values, &input, inputs.used_color_scheme, parent)
                }
                group_index::INHERITED_SVG => {
                    build_inherited_svg_group(values, &input, inputs.used_color_scheme, parent)
                }
                group_index::INHERITED_LIST_TABLE => {
                    build_inherited_list_table_group(values, &input, inputs.used_color_scheme, parent)
                }
                group_index::CONTENT => build_content_group(values, &input, inputs.used_color_scheme, parent),
                group_index::BACKGROUND => build_background_group(values, &input, inputs.used_color_scheme, parent),
                group_index::MASK => build_mask_group(values, &input, inputs.used_color_scheme, parent),
                group_index::BORDER => build_border_group(values, &input, inputs.used_color_scheme, parent),
                _ => build_generic_group(group, values, &input, inputs.used_color_scheme, parent),
            }
        };
        assert!(!payload.is_null(), "computed group build returned null");
        *out_payload = payload;
    }
}

#[cfg(test)]
mod transform_angle_tests {
    use super::*;
    use crate::css::style_value::StyleValueBox;
    use crate::css::style_value_arc::StyleValueArc;

    fn literal(value: f64, unit: &str) -> StyleValueData {
        StyleValueData::Angle {
            value,
            unit: angle_unit_index(unit) as u8,
        }
    }

    fn computed_transform(source: &str) -> RetainedStyleValueData {
        use crate::css::absolutize::{Absolutized, absolutize_with_element_facts};
        use crate::css::css_tokenizer::{TokenizerInput, tokenize_for_parser};
        use crate::css::parser::component_value::consume_a_list_of_component_values;
        use crate::css::parser::value_parser::{ParseContext, ParseOutcome, parse_css_value};
        let units: Vec<_> = source.encode_utf16().collect();
        let tokens = consume_a_list_of_component_values(tokenize_for_parser(TokenizerInput::Utf16(&units))).unwrap();
        let ParseOutcome::Parsed(parsed) = parse_css_value(&ParseContext::default(), property_id::TRANSFORM, &tokens)
        else {
            panic!("valid transform");
        };
        match absolutize_with_element_facts(
            &parsed,
            &crate::css::style_compute::FfiLengthResolutionContext::default(),
            None,
            &[],
            None,
        )
        .unwrap()
        {
            Absolutized::Changed(value) => value,
            Absolutized::Unchanged => RetainedStyleValueData::from_arc(parsed),
        }
    }

    fn first_transform(value: &RetainedStyleValueData) -> &StyleValueData {
        let StyleValueData::ValueList { values, .. } = value.data() else {
            panic!("transform list")
        };
        values.as_slice()[0].data()
    }

    #[test]
    fn parsed_large_turns_remain_identity_after_absolutization_and_lowering() {
        for source in ["rotate(1e30turn)", "rotate(-1e30turn)"] {
            let value = computed_transform(source);
            let matrix = lower_transformation(first_transform(&value)).matrix;
            for (actual, expected) in matrix.into_iter().zip(matrix_identity()) {
                assert!((actual - expected).abs() < 1e-6, "{source}: {matrix:?}");
            }
        }
    }

    #[test]
    fn canonical_arguments_and_serialization_survive_precise_matrix_inputs() {
        let value = computed_transform("rotate(1e30turn)");
        let transform = first_transform(&value);
        let StyleValueData::Transformation(transformation_payload) = transform else {
            panic!("transform function");
        };
        let TransformationPayload {
            property,
            transform_function,
            values,
            matrix_values,
        } = &**transformation_payload;
        assert!(!matrix_values.as_slice().is_empty());
        assert!(
            matches!(values.as_slice()[0].data(), StyleValueData::Angle { value, unit }
            if *value == 1e30 * 360.0 && *unit as usize == angle_unit_index("deg"))
        );
        let without_matrix_inputs = StyleValueData::Transformation(StyleValueBox::new(TransformationPayload {
            property: *property,
            transform_function: *transform_function,
            values: values.clone(),
            matrix_values: crate::css::style_value::RetainedStyleValueDataList::from_retained_values(Vec::new()),
        }));
        assert_eq!(
            crate::css::serialize::serialize_style_value_to_utf16(transform),
            crate::css::serialize::serialize_style_value_to_utf16(&without_matrix_inputs)
        );
        assert!(transform != &without_matrix_inputs);
        assert!(transform.content_hash() != without_matrix_inputs.content_hash());
        let cloned = transform.clone();
        assert!(transform == &cloned);
        assert_eq!(transform.content_hash(), cloned.content_hash());
        assert_eq!(
            lower_transformation(transform).matrix,
            lower_transformation(&cloned).matrix
        );
        let repeated = crate::css::absolutize::absolutize_with_element_facts(
            &cloned,
            &crate::css::style_compute::FfiLengthResolutionContext::default(),
            None,
            &[],
            None,
        )
        .unwrap();
        match repeated {
            crate::css::absolutize::Absolutized::Unchanged => {}
            crate::css::absolutize::Absolutized::Changed(value) => {
                assert!(value.data() == transform);
                assert_eq!(
                    lower_transformation(value.data()).matrix,
                    lower_transformation(transform).matrix
                );
            }
        }
    }

    #[test]
    fn mapped_matrix_inputs_follow_axes_and_drop_replaced_angles() {
        let value = computed_transform("rotate3d(0, 0, 1, 1e30turn)");
        let StyleValueData::Transformation(transformation_payload) = first_transform(&value) else {
            panic!("transform function");
        };
        let TransformationPayload {
            values, matrix_values, ..
        } = &**transformation_payload;
        let mut mapped = values.as_slice().to_vec();
        mapped[0] = RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value: 1.0 }));
        let retained =
            crate::css::style_value::map_transform_matrix_values(values.as_slice(), &mapped, matrix_values.as_slice());
        assert!(retained.as_slice()[0].data() == mapped[0].data());
        assert!(
            matches!(retained.as_slice()[3].data(), StyleValueData::Angle { value, unit }
            if *value == 1e30 && *unit as usize == angle_unit_index("turn"))
        );
        mapped[3] = RetainedStyleValueData::from_arc(StyleValueArc::new(literal(90.0, "deg")));
        let retained =
            crate::css::style_value::map_transform_matrix_values(values.as_slice(), &mapped, matrix_values.as_slice());
        assert!(retained.as_slice().is_empty());
    }

    #[test]
    fn large_whole_turns_do_not_rotate() {
        for value in [1e30, -1e30] {
            assert_eq!(transform_angle_radians(&literal(value, "turn")), 0.0);
        }
    }

    #[test]
    fn large_grad_angles_preserve_their_remainder() {
        // The representable f64 value 1e30 has a remainder of 256 grads, or 230.4 degrees.
        let expected = std::f64::consts::PI * 1.28;
        assert!((transform_angle_radians(&literal(1e30, "grad")) - expected).abs() < 1e-14);
        assert!((transform_angle_radians(&literal(-1e30, "grad")) + expected).abs() < 1e-14);
    }

    #[test]
    fn transform_angle_units_keep_their_periods() {
        for (value, unit) in [
            (450.0, "deg"),
            (500.0, "grad"),
            (1.25, "turn"),
            (std::f64::consts::PI * 2.5, "rad"),
        ] {
            assert!((transform_angle_radians(&literal(value, unit)) - std::f64::consts::FRAC_PI_2).abs() < 1e-14);
        }
    }

    #[test]
    fn calculated_transform_angle_keeps_degree_resolution() {
        use crate::css::calc::{CalcNode, CalcNodeHandle, CalcNumericType, CalcNumericValue, FfiNumericType};
        let node = std::sync::Arc::new(CalcNode::Numeric(CalcNumericValue::Angle {
            value: 450.0,
            unit: angle_unit_index("deg") as u8,
        }));
        let value = StyleValueData::Calculated(StyleValueBox::new(CalculatedPayload {
            resolved_type: FfiNumericType::from_calc(node.numeric_type(&CalcNumericType::default())),
            rust_calculation: CalcNodeHandle::from_arc(node),
            resolve_as_is_number: false,
            resolve_as_base: 0,
            has_percentages_resolve_as: false,
            percentages_resolve_as: 0,
            resolve_numbers_as_integers: false,
            accepted_ranges: crate::css::style_value::RetainedNumericRangeList::empty(),
        }));
        assert_eq!(angle_degrees(&value), Some(450.0));
        assert!((transform_angle_radians(&value) - std::f64::consts::FRAC_PI_2).abs() < 1e-14);
        assert_eq!(angle_degrees(&value), Some(450.0));
    }

    #[test]
    fn non_finite_transform_angles_stay_nan() {
        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            for unit in ["deg", "grad", "rad", "turn"] {
                assert!(transform_angle_radians(&literal(value, unit)).is_nan());
            }
        }
    }
}