Skip to content

Truly independent web browser

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

//! Generated CSS property metadata for the Rust style computation core.
//!
//! The tables are generated by build.rs from Properties.json, replicating the
//! property identifier assignment of the C++ generator exactly: Custom is 0,
//! then shorthands, inherited longhands and non-inherited longhands in JSON
//! order, skipping legacy aliases. A C++ unit test compares every table
//! against the C++-generated equivalents so the two generators cannot drift.
//!
//! Property identifiers cross the FFI as opaque u16 values, like keywords.

include!(concat!(env!("OUT_DIR"), "/property_metadata_generated.rs"));

pub(crate) const NUMBER_OF_LONGHAND_PROPERTIES: usize =
    (LAST_LONGHAND_PROPERTY_ID - FIRST_LONGHAND_PROPERTY_ID + 1) as usize;
pub(crate) const LONGHAND_WORD_COUNT: usize = NUMBER_OF_LONGHAND_PROPERTIES.div_ceil(64);

pub(crate) fn property_name(property_id: u16) -> &'static str {
    if property_id == 0 {
        return "--custom";
    }
    PROPERTY_NAMES
        .get(usize::from(property_id - 1))
        .copied()
        .unwrap_or("<unknown>")
}

fn compare_property_name<T: Copy + Into<u16>>(candidate: &str, name: &[T]) -> std::cmp::Ordering {
    candidate.bytes().map(u16::from).cmp(
        name.iter()
            .copied()
            .map(Into::into)
            .map(crate::css::ffi_support::ascii_lowercase),
    )
}

pub(crate) fn is_custom_property_name<T: Copy + Into<u16>>(name: &[T]) -> bool {
    name.len() > 2 && name[0].into() == u16::from(b'-') && name[1].into() == u16::from(b'-')
}

// NB: This mirrors the property-name resolution formerly performed by
//     CSS/Parser/RustSyntaxParsing.cpp:106 and CSS/Parser/RustQueryParsing.cpp:63.
//     Legacy aliases are accepted by the generated table, while custom property
//     names map to PropertyID::Custom.
pub(crate) fn property_id_from_name<T: Copy + Into<u16>>(name: &[T]) -> Option<u16> {
    if is_custom_property_name(name) {
        return Some(property_id::CUSTOM);
    }
    PROPERTY_NAME_LOOKUP
        .binary_search_by(|(candidate, _)| compare_property_name(candidate, name))
        .ok()
        .map(|index| PROPERTY_NAME_LOOKUP[index].1)
}

pub(crate) fn property_accepted_keywords(property_id: u16) -> &'static [u16] {
    PROPERTY_ACCEPTED_KEYWORDS[property_index(property_id)]
}

pub(crate) fn property_accepted_value_types(property_id: u16) -> &'static [u8] {
    PROPERTY_ACCEPTED_VALUE_TYPES[property_index(property_id)]
}

pub(crate) fn property_custom_ident_blacklist(property_id: u16) -> &'static [&'static str] {
    PROPERTY_CUSTOM_IDENT_BLACKLISTS[property_index(property_id)]
}

pub(crate) fn property_resolve_legacy_value_alias(property_id: u16, keyword: u16) -> u16 {
    PROPERTY_KEYWORD_ALIASES[property_index(property_id)]
        .iter()
        .find_map(|&(alias, resolved)| (alias == keyword).then_some(resolved))
        .unwrap_or(keyword)
}

pub(crate) fn property_accepts_only_keywords(property_id: u16) -> bool {
    PROPERTY_ACCEPTS_ONLY_KEYWORDS[property_index(property_id)]
}

pub(crate) fn property_has_coordinating_list_multiplicity(property_id: u16) -> bool {
    PROPERTY_HAS_COORDINATING_LIST_MULTIPLICITY[property_index(property_id)]
}

pub(crate) fn property_maximum_value_count(property_id: u16) -> usize {
    PROPERTY_MAXIMUM_VALUE_COUNTS[property_index(property_id)] as usize
}

pub(crate) fn property_percentages_resolve_to(property_id: u16) -> Option<u8> {
    PROPERTY_PERCENTAGES_RESOLVE_TO[property_index(property_id)]
}

pub(crate) fn property_has_unitless_length_quirk(property_id: u16) -> bool {
    PROPERTY_HAS_UNITLESS_LENGTH_QUIRK[property_index(property_id)]
}

pub(crate) fn property_has_hashless_hex_color_quirk(property_id: u16) -> bool {
    PROPERTY_HAS_HASHLESS_HEX_COLOR_QUIRK[property_index(property_id)]
}

/// How much of the computation a property needs, mirroring the C++
/// requires-computation levels: 0 = never, 1 = with the cascaded value,
/// 2 = with any non-inherited value, 3 = always.
pub const REQUIRES_COMPUTATION_CASCADED: u8 = 1;
pub const REQUIRES_COMPUTATION_NON_INHERITED: u8 = 2;
pub const REQUIRES_COMPUTATION_ALWAYS: u8 = 3;

fn longhand_index(property_id: u16) -> usize {
    debug_assert!((FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&property_id));
    (property_id - FIRST_LONGHAND_PROPERTY_ID) as usize
}

pub fn property_is_inherited(property_id: u16) -> bool {
    (FIRST_INHERITED_PROPERTY_ID..=LAST_INHERITED_PROPERTY_ID).contains(&property_id)
}

pub fn property_requires_computation_level(property_id: u16) -> u8 {
    REQUIRES_COMPUTATION_LEVELS[longhand_index(property_id)]
}

pub fn property_animation_type(property_id: u16) -> u8 {
    PROPERTY_ANIMATION_TYPES[longhand_index(property_id)]
}

/// Whether changing a property may invalidate geometry exposed by synchronous layout APIs.
///
/// Besides properties which directly affect layout, this includes properties which can change the
/// accumulated visual context, scrollable overflow, or stacking-context structure, and properties
/// which can indirectly expose geometry changes through animations, container queries, or SVG
/// currentColor strokes.
/// Value-aware callers can refine this conservative property-level answer when both sides are
/// available.
pub fn property_may_affect_layout_geometry(property_id: u16) -> bool {
    if !(FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&property_id) {
        return true;
    }
    PROPERTY_MAY_AFFECT_LAYOUT_GEOMETRY[longhand_index(property_id)]
}

/// Whether changing a property may move where a scroll container snaps, besides the properties
/// which affect its scrollable overflow.
pub(crate) fn property_may_resnap_scroll_container(property_id: u16) -> bool {
    matches!(
        property_id,
        property_id::SCROLL_SNAP_TYPE
            | property_id::SCROLL_SNAP_ALIGN
            | property_id::SCROLL_SNAP_STOP
            | property_id::SCROLL_MARGIN_TOP
            | property_id::SCROLL_MARGIN_RIGHT
            | property_id::SCROLL_MARGIN_BOTTOM
            | property_id::SCROLL_MARGIN_LEFT
            | property_id::SCROLL_PADDING_TOP
            | property_id::SCROLL_PADDING_RIGHT
            | property_id::SCROLL_PADDING_BOTTOM
            | property_id::SCROLL_PADDING_LEFT
    )
}

pub(crate) fn property_affects_layout(property_id: u16) -> bool {
    PROPERTY_AFFECTS_LAYOUT[longhand_index(property_id)]
}

pub(crate) fn property_affects_stacking_context(property_id: u16) -> bool {
    PROPERTY_AFFECTS_STACKING_CONTEXT[longhand_index(property_id)]
}

pub(crate) fn property_affects_scrollable_overflow(property_id: u16) -> bool {
    PROPERTY_AFFECTS_SCROLLABLE_OVERFLOW[longhand_index(property_id)]
}

pub(crate) fn property_affects_accumulated_visual_contexts(property_id: u16) -> bool {
    PROPERTY_AFFECTS_ACCUMULATED_VISUAL_CONTEXTS[longhand_index(property_id)]
}

pub(crate) fn property_affects_hit_testing(property_id: u16) -> bool {
    PROPERTY_AFFECTS_HIT_TESTING[longhand_index(property_id)]
}

pub(crate) fn property_style_group_index(property_id: u16) -> Option<u8> {
    match PROPERTY_STYLE_GROUP_INDICES[longhand_index(property_id)] {
        u8::MAX => None,
        index => Some(index),
    }
}

pub(crate) fn property_initial_value(property_id: u16) -> &'static str {
    PROPERTY_INITIAL_VALUES[longhand_index(property_id)]
}

pub(crate) fn pseudo_element_supports_property(pseudo_element: u8, property_id: u16) -> bool {
    if PSEUDO_ELEMENT_TRANSITION_AND_ANIMATION_PROPERTIES
        .binary_search(&property_id)
        .is_ok()
    {
        return PSEUDO_ELEMENT_ACCEPTS_ANIMATIONS[pseudo_element as usize];
    }
    match PSEUDO_ELEMENT_PROPERTY_WHITELISTS[pseudo_element as usize] {
        Some(whitelist) => whitelist.binary_search(&property_id).is_ok(),
        None => true,
    }
}

/// Whether a pseudo-element's own whitelist names the property, leaving out the transition and animation
/// properties.
pub(crate) fn pseudo_element_whitelist_names_property(pseudo_element: u8, property_id: u16) -> bool {
    PSEUDO_ELEMENT_PROPERTY_WHITELISTS[pseudo_element as usize]
        .is_some_and(|whitelist| whitelist.binary_search(&property_id).is_ok())
}

/// An accepted numeric range for one CSS value type.
#[repr(C)]
pub struct FfiPropertyNumericRange {
    pub value_type: u8,
    pub min: f64,
    pub max: f64,
}

pub fn property_numeric_ranges(property_id: u16) -> &'static [FfiPropertyNumericRange] {
    PROPERTY_NUMERIC_RANGES[property_index(property_id)]
}

/// Returns the longhand property identifiers in computation order.
pub fn property_computation_order() -> &'static [u16] {
    &PROPERTY_COMPUTATION_ORDER
}

/// FFI accessors for the parity test on the C++ side.
///
#[unsafe(no_mangle)]
pub extern "C" fn rust_property_metadata_is_inherited(property_id: u16) -> bool {
    property_is_inherited(property_id)
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_property_metadata_numeric_ranges(
    property_id: u16,
    out_length: &mut usize,
) -> *const FfiPropertyNumericRange {
    let ranges = property_numeric_ranges(property_id);
    *out_length = ranges.len();
    ranges.as_ptr()
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_property_metadata_bounds(
    out_first_longhand: &mut u16,
    out_last_longhand: &mut u16,
    out_first_inherited: &mut u16,
    out_last_inherited: &mut u16,
) {
    *out_first_longhand = FIRST_LONGHAND_PROPERTY_ID;
    *out_last_longhand = LAST_LONGHAND_PROPERTY_ID;
    *out_first_inherited = FIRST_INHERITED_PROPERTY_ID;
    *out_last_inherited = LAST_INHERITED_PROPERTY_ID;
}

pub fn property_is_shorthand(property_id: u16) -> bool {
    (FIRST_SHORTHAND_PROPERTY_ID..=LAST_SHORTHAND_PROPERTY_ID).contains(&property_id)
}

pub(crate) fn property_defines_a_css_transition(property_id: u16) -> bool {
    matches!(
        property_id,
        property_id::TRANSITION
            | property_id::TRANSITION_BEHAVIOR
            | property_id::TRANSITION_DELAY
            | property_id::TRANSITION_DURATION
            | property_id::TRANSITION_PROPERTY
            | property_id::TRANSITION_TIMING_FUNCTION
    )
}

/// Each shorthand with its longhands, through any shorthand nested in it (`border-width` in `border`), sorted.
fn shorthand_leaf_longhands() -> &'static [(u16, Box<[u16]>)] {
    fn leaf_longhands(property: u16, leaves: &mut Vec<u16>) {
        for &longhand in longhands_for_shorthand(property) {
            if longhand < FIRST_LONGHAND_PROPERTY_ID {
                leaf_longhands(longhand, leaves);
            } else {
                leaves.push(longhand);
            }
        }
    }
    static SHORTHAND_LEAVES: std::sync::OnceLock<Vec<(u16, Box<[u16]>)>> = std::sync::OnceLock::new();
    SHORTHAND_LEAVES.get_or_init(|| {
        (FIRST_SHORTHAND_PROPERTY_ID..=LAST_SHORTHAND_PROPERTY_ID)
            .map(|shorthand| {
                let mut leaves = Vec::new();
                leaf_longhands(shorthand, &mut leaves);
                leaves.sort_unstable();
                leaves.dedup();
                (shorthand, leaves.into_boxed_slice())
            })
            .collect()
    })
}

/// Whether `longhand` is one of the longhands of `shorthand`, through any shorthand nested in it.
pub(crate) fn shorthand_has_leaf_longhand(shorthand: u16, longhand: u16) -> bool {
    property_is_shorthand(shorthand)
        && shorthand_leaf_longhands()[usize::from(shorthand - FIRST_SHORTHAND_PROPERTY_ID)]
            .1
            .binary_search(&longhand)
            .is_ok()
}

/// The shorthands whose longhands, through any shorthand nested in it, include all of `longhands`, with the fewest
/// longhands first: those a value pending substitution in each of them may have been written for, where a later
/// declaration may have replaced some of the shorthand's other longhands.
pub(crate) fn shorthands_with_leaf_longhands(longhands: &[u16]) -> Vec<u16> {
    let mut shorthands = shorthand_leaf_longhands()
        .iter()
        .filter(|(_, leaves)| longhands.iter().all(|longhand| leaves.binary_search(longhand).is_ok()))
        .collect::<Vec<_>>();
    shorthands.sort_by_key(|(_, leaves)| leaves.len());
    shorthands.into_iter().map(|(shorthand, _)| *shorthand).collect()
}

/// Returns the longhands a shorthand expands to, in Properties.json order.
pub fn longhands_for_shorthand(property_id: u16) -> &'static [u16] {
    if !property_is_shorthand(property_id) {
        return &[];
    }
    SHORTHAND_EXPANSIONS[(property_id - FIRST_SHORTHAND_PROPERTY_ID) as usize]
}

/// The longhands of a shorthand, through any shorthand nested in it.
pub(crate) fn expanded_longhands_for_shorthand(property_id: u16) -> &'static [u16] {
    if !property_is_shorthand(property_id) {
        return &[];
    }
    EXPANDED_LONGHANDS_FOR_SHORTHAND[(property_id - FIRST_SHORTHAND_PROPERTY_ID) as usize]
}

/// The shorthands a property maps to, in preferred order.
pub(crate) fn shorthands_for_longhand(property_id: u16) -> &'static [u16] {
    SHORTHANDS_FOR_LONGHAND[property_index(property_id)]
}

pub(crate) fn property_is_legacy_shorthand(property_id: u16) -> bool {
    LEGACY_SHORTHANDS.binary_search(&property_id).is_ok()
}

pub(crate) fn property_is_positional_value_list_shorthand(property_id: u16) -> bool {
    POSITIONAL_VALUE_LIST_SHORTHANDS.binary_search(&property_id).is_ok()
}

fn property_index(property_id: u16) -> usize {
    debug_assert!((FIRST_SHORTHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&property_id));
    (property_id - FIRST_SHORTHAND_PROPERTY_ID) as usize
}

/// The IDL attribute name of the property, https://drafts.csswg.org/cssom/#css-property-to-idl-attribute
pub fn property_idl_name(property_id: u16) -> &'static str {
    PROPERTY_IDL_NAMES[property_index(property_id)]
}

pub(crate) fn property_is_logical_alias_including_shorthands(property_id: u16) -> bool {
    PROPERTY_IS_LOGICAL_ALIAS[property_index(property_id)]
}

pub(crate) fn longhand_is_logical_alias(property_id: u16) -> bool {
    debug_assert!((FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&property_id));
    property_is_logical_alias_including_shorthands(property_id)
}

pub(crate) fn property_is_in_logical_group(property_id: u16) -> bool {
    property_logical_group(property_id).is_some()
}

pub(crate) fn property_logical_group(property_id: u16) -> Option<u8> {
    match PROPERTY_LOGICAL_GROUPS[property_index(property_id)] {
        0 => None,
        group => Some(group),
    }
}

/// Returns whether `a` wins a keyframe declaration conflict with `b`.
pub(crate) fn animation_property_is_preferred(a: u16, b: u16) -> bool {
    // https://drafts.csswg.org/web-animations-1/#ref-for-computed-keyframes
    // If conflicts arise when expanding shorthand properties or replacing logical properties with physical properties, apply the following rules in order until the conflict is resolved:

    // 1. Longhand properties override shorthand properties (e.g. border-top-color overrides border-top).
    if property_is_shorthand(a) != property_is_shorthand(b) {
        return !property_is_shorthand(a);
    }

    // 2. Shorthand properties with fewer longhand components override those with more longhand components (e.g. border-top overrides border-color).
    if property_is_shorthand(a) {
        let a_length = SHORTHAND_EXPANDED_LONGHAND_COUNTS[(a - FIRST_SHORTHAND_PROPERTY_ID) as usize];
        let b_length = SHORTHAND_EXPANDED_LONGHAND_COUNTS[(b - FIRST_SHORTHAND_PROPERTY_ID) as usize];
        if a_length != b_length {
            return a_length < b_length;
        }
    }

    let a_is_logical_alias = property_is_logical_alias_including_shorthands(a);
    let b_is_logical_alias = property_is_logical_alias_including_shorthands(b);

    // 3. Physical properties override logical properties.
    if a_is_logical_alias != b_is_logical_alias {
        return !a_is_logical_alias;
    }

    // 4. For shorthand properties with an equal number of longhand components, properties whose IDL name (see
    //    the CSS property to IDL attribute algorithm [CSSOM]) appears earlier when sorted in ascending order
    //    by the Unicode codepoints that make up each IDL name, override those who appear later.
    PROPERTY_IDL_NAMES[property_index(a)] < PROPERTY_IDL_NAMES[property_index(b)]
}

#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
    use super::*;
    use crate::css::css_enums::keyword;

    fn utf16(value: &str) -> Vec<u16> {
        value.encode_utf16().collect()
    }

    #[test]
    fn resolves_property_names() {
        for (index, name) in PROPERTY_NAMES.iter().enumerate() {
            assert_eq!(property_id_from_name(&utf16(name)), Some(index as u16 + 1), "{name}");
        }
        for &(name, property_id) in &PROPERTY_NAME_LOOKUP {
            assert_eq!(property_id_from_name(&utf16(name)), Some(property_id), "{name}");
        }

        assert_eq!(
            property_id_from_name(&utf16("BaCkGrOuNd-CoLoR")),
            Some(property_id::BACKGROUND_COLOR)
        );
        assert_eq!(
            property_id_from_name(&utf16("-WeBkIt-BoX-OrIeNt")),
            Some(property_id::_WEBKIT_BOX_ORIENT)
        );
        assert_eq!(property_id_from_name(&utf16("--")), None);
        assert_eq!(property_id_from_name(&utf16("--x")), Some(property_id::CUSTOM));
        assert_eq!(property_id_from_name(&utf16("-webkit-foo")), None);
        assert_eq!(property_id_from_name(&utf16("unknown-property")), None);
    }

    #[test]
    fn layout_geometry_effects_include_direct_and_indirect_effects() {
        assert!(!property_may_affect_layout_geometry(property_id::BACKGROUND_COLOR));
        assert!(property_may_affect_layout_geometry(property_id::COLOR));
        assert!(property_may_affect_layout_geometry(property_id::WIDTH));
        assert!(property_may_affect_layout_geometry(property_id::TRANSFORM));
        assert!(property_may_affect_layout_geometry(property_id::OPACITY));
        assert!(property_may_affect_layout_geometry(property_id::TEXT_RENDERING));
        assert!(property_may_affect_layout_geometry(property_id::STROKE));
        assert!(property_may_affect_layout_geometry(property_id::STROKE_WIDTH));
        assert!(property_may_affect_layout_geometry(property_id::ANIMATION_NAME));
        assert!(property_may_affect_layout_geometry(property_id::TRANSITION_PROPERTY));
        assert!(property_may_affect_layout_geometry(property_id::SCROLL_TIMELINE_NAME));
        assert!(property_may_affect_layout_geometry(property_id::CONTAINER_NAME));
        assert!(property_may_affect_layout_geometry(property_id::CUSTOM));
    }

    #[test]
    fn resnapping_properties_affect_layout_geometry() {
        // A re-snap moves a scroll offset, and with it every box in the scroll container.
        for property_id in FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID {
            if property_may_resnap_scroll_container(property_id) {
                assert!(
                    property_may_affect_layout_geometry(property_id),
                    "{}",
                    property_name(property_id)
                );
            }
        }
    }

    #[test]
    fn exposes_property_keyword_metadata() {
        assert!(property_accepted_keywords(property_id::APPEARANCE).contains(&keyword::NONE));
        assert!(!property_accepted_keywords(property_id::APPEARANCE).contains(&keyword::INHERIT));
        assert!(property_accepts_only_keywords(property_id::APPEARANCE));
        assert!(!property_accepts_only_keywords(property_id::ACCENT_COLOR));
        assert!(property_has_coordinating_list_multiplicity(
            property_id::ANIMATION_DIRECTION
        ));
        assert_eq!(property_maximum_value_count(property_id::BORDER_SPACING), 2);
        assert_eq!(property_maximum_value_count(property_id::WIDTH), 1);
    }

    #[test]
    fn exposes_property_numeric_parser_metadata() {
        // ValueType codes are shared with the C++ enum: Integer = 24,
        // Length = 25, Number = 27, OpacityValue = 28, Percentage = 31.
        assert_eq!(property_accepted_value_types(property_id::Z_INDEX), &[24]);
        assert_eq!(property_accepted_value_types(property_id::WIDTH), &[14, 25, 31]);
        assert_eq!(property_accepted_value_types(property_id::OPACITY), &[28]);
        assert_eq!(property_percentages_resolve_to(property_id::WIDTH), Some(25));
        assert_eq!(property_percentages_resolve_to(property_id::OPACITY), None);
        assert!(property_has_unitless_length_quirk(property_id::WIDTH));
        assert!(!property_has_unitless_length_quirk(property_id::OPACITY));
    }

    #[test]
    fn exposes_property_custom_ident_blacklists() {
        assert_eq!(property_custom_ident_blacklist(property_id::ANIMATION_NAME), &["none"]);
        assert_eq!(
            property_custom_ident_blacklist(property_id::VIEW_TRANSITION_NAME),
            &["auto", "none"]
        );
        assert!(property_custom_ident_blacklist(property_id::WIDTH).is_empty());
    }

    #[test]
    fn resolves_legacy_property_keyword_aliases() {
        assert!(property_accepted_keywords(property_id::OVERFLOW_X).contains(&keyword::OVERLAY));
        assert_eq!(
            property_resolve_legacy_value_alias(property_id::OVERFLOW_X, keyword::OVERLAY),
            keyword::AUTO
        );
    }
}

/// FFI accessors for the parity test on the C++ side.
#[unsafe(no_mangle)]
pub extern "C" fn rust_property_metadata_is_shorthand(property_id: u16) -> bool {
    property_is_shorthand(property_id)
}

#[unsafe(no_mangle)]
pub extern "C" fn rust_property_metadata_longhands_for_shorthand(
    property_id: u16,
    out_length: &mut usize,
) -> *const u16 {
    let longhands = longhands_for_shorthand(property_id);
    *out_length = longhands.len();
    longhands.as_ptr()
}