Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / css / counter_style_1.lucb

#==============================================================================================
#
#   counter_style_1 - CounterStyle: the predefined styles, construction, comparison and the
#   extended CJK representations
#
#   DESCRIPTION:
#       Port of LibWeb/CSS/CounterStyle.cpp lines 1-197 (decimal, disc,
#       from_counter_style_definition, equals, generate_an_initial_representation_for_
#       extended_cjk_system) and the inline members of CounterStyle.h. counter_style_2 holds
#       the rest. CounterStyle is RefCounted: a blob made by `new`, with the generated vtable
#       and class id. The function-local statics of decimal() and disc() are module variables
#       whose styles are made in the C heap (`with memory.heap`), because the collector neither
#       scans nor sweeps module data (as r30b's ErrorReporter).
#
#       Copyright (c) 2026, Callum Law <callumlaw1709@outlook.com>.
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Construction ============================================================================

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:22 Web::CSS::CounterStyle::create.
pub func css_counter_style_create(name: ak.FlyString, algorithm: CssCounterStyleAlgorithm, negative_sign: CssCounterStyleNegativeSign, prefix: ak.FlyString, suffix: ak.FlyString, range: ak.Vector[CssCounterStyleRangeEntry], fallback: ak.FlyString?, pad_: CssCounterStylePad) -> CssCounterStyle*:
    # NB: All counter styles apart from 'decimal' must have a fallback.
    assert(fallback != none or ak.fly_string_eq_string_view(&name, ak.sv("decimal")))
    let counter_style = new CssCounterStyle(
        vtable = &css_counter_style_vtable,
        class_id = css_counter_style_class.first_id,
        m_name = name,
        m_algorithm = algorithm,
        m_negative_sign = negative_sign,
        m_prefix = prefix,
        m_suffix = suffix,
        m_range = range,
        m_fallback = fallback,
        m_pad = pad_,
    ) else trap("out of memory")
    css_counter_style_construct(counter_style, name, algorithm, negative_sign, prefix, suffix, range, fallback, pad_)
    return counter_style

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:46 Web::CSS::CounterStyle::CounterStyle.
pub func css_counter_style_construct(this: CssCounterStyle*, name: ak.FlyString, algorithm: CssCounterStyleAlgorithm, negative_sign: CssCounterStyleNegativeSign, prefix: ak.FlyString, suffix: ak.FlyString, range: ak.Vector[CssCounterStyleRangeEntry], fallback: ak.FlyString?, pad_: CssCounterStylePad):
    # Counter styles are composed of:
    # a name, to identify the style
    this.m_name = name
    # an algorithm, which transforms integer counter values into a basic string representation
    this.m_algorithm = algorithm
    # a negative sign, which is prepended or appended to the representation of a negative counter value.
    this.m_negative_sign = negative_sign
    # a prefix, to prepend to the representation
    this.m_prefix = prefix
    # a suffix to append to the representation
    this.m_suffix = suffix
    # a range, which limits the values that a counter style handles
    this.m_range = range
    # FIXME: a spoken form, which describes how to read out the counter style in a speech synthesizer
    # and a fallback style, to render the representation with when the counter value is outside the counter style’s
    # range or the counter style otherwise can’t render the counter value
    this.m_fallback = fallback
    # AD-HOC: We store the `pad` descriptor here as well to have everything in one place
    this.m_pad = pad_

## CounterStyle::decimal()'s `static auto decimal_counter_style`.
var css_counter_style_decimal_counter_style: CssCounterStyle*?

## CounterStyle::disc()'s `static auto disc_counter_style`.
var css_counter_style_disc_counter_style: CssCounterStyle*?

## `{ { NumericLimits<i32>::min(), NumericLimits<i32>::max() } }`: the infinite range.
func css_counter_style_infinite_range() -> ak.Vector[CssCounterStyleRangeEntry]:
    var range = ak.Vector[CssCounterStyleRangeEntry]()
    ak.vector_append_t(&range, CssCounterStyleRangeEntry(start = -2147483648, end = 2147483647))
    return range

## Ported from Libraries/LibWeb/CSS/CounterStyle.cpp:14 Web::CSS::CounterStyle::decimal.
# https://drafts.csswg.org/css-counter-styles-3/#decimal
pub func css_counter_style_decimal() -> CssCounterStyle*:
    if let existing = css_counter_style_decimal_counter_style:
        return existing
    # The static outlives every VM: in the C heap, with ak's atomic allocator unset (DESIGN.md §3.3 rule 7).
    let saved_atomic_allocator = ak.atomic_allocator
    ak.atomic_allocator = none
    defer ak.atomic_allocator = saved_atomic_allocator
    with memory.heap:
        var symbols = ak.Vector[ak.FlyString]()
        for digit in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
            ak.vector_append_t(&symbols, ak.fly_string_from_str(digit))
        css_counter_style_decimal_counter_style = css_counter_style_create(
            ak.fly_string_from_str("decimal"),
            .css_generic_counter_style_algorithm(CssGenericCounterStyleAlgorithm(type_ = css_data.CounterStyleSystem.numeric, symbol_list = symbols)),
            CssCounterStyleNegativeSign(prefix = ak.fly_string_from_str("-"), suffix = ak.fly_string_from_str("")),
            ak.fly_string_from_str(""),
            ak.fly_string_from_str(". "),
            css_counter_style_infinite_range(),
            none,
            CssCounterStylePad(minimum_length = 0, symbol = ak.fly_string_from_str("")),
        )

    return css_counter_style_decimal_counter_style else trap("unreachable")

## Ported from Libraries/LibWeb/CSS/CounterStyle.cpp:30 Web::CSS::CounterStyle::disc.
# https://drafts.csswg.org/css-counter-styles-3/#disc
pub func css_counter_style_disc() -> CssCounterStyle*:
    if let existing = css_counter_style_disc_counter_style:
        return existing
    # The static outlives every VM: in the C heap, with ak's atomic allocator unset (DESIGN.md §3.3 rule 7).
    let saved_atomic_allocator = ak.atomic_allocator
    ak.atomic_allocator = none
    defer ak.atomic_allocator = saved_atomic_allocator
    with memory.heap:
        var symbols = ak.Vector[ak.FlyString]()
        ak.vector_append_t(&symbols, ak.fly_string_from_str("\u{2022}"))
        css_counter_style_disc_counter_style = css_counter_style_create(
            ak.fly_string_from_str("disc"),
            .css_generic_counter_style_algorithm(CssGenericCounterStyleAlgorithm(type_ = css_data.CounterStyleSystem.cyclic, symbol_list = symbols)),
            CssCounterStyleNegativeSign(prefix = ak.fly_string_from_str(""), suffix = ak.fly_string_from_str(" ")),
            ak.fly_string_from_str(""),
            ak.fly_string_from_str(" "),
            css_counter_style_infinite_range(),
            ak.fly_string_from_str("decimal"),
            CssCounterStylePad(minimum_length = 0, symbol = ak.fly_string_from_str("")),
        )

    return css_counter_style_disc_counter_style else trap("unreachable")

## Ported from Libraries/LibWeb/CSS/CounterStyle.cpp:45 Web::CSS::CounterStyle::from_counter_style_definition.
pub func css_counter_style_from_counter_style_definition(definition: const CssCounterStyleDefinition*, style_scope: const CssStyleScope*) -> CssCounterStyle*:
    match definition.m_algorithm:
        .css_counter_style_system_style_value_extends(extends):
            # NB: The caller should ensure that any dependencies (i.e. counter styles that occur in the extends chain)
            #     of this counter style are registered before this counter style.
            var extended_counter_style = css_style_scope_get_registered_counter_style(style_scope, extends.name)

            if extended_counter_style == none:
                extended_counter_style = css_style_scope_get_registered_counter_style(style_scope, ak.fly_string_from_str("decimal"))

            let extended = extended_counter_style else trap("VERIFY: the decimal counter style is registered")
            let range = match definition.m_range:
                .empty => extended.m_range
                .vector_css_counter_style_range_entry(range) => range
                .css_auto_range(_) => css_auto_range_resolve(extended.m_algorithm)
            return css_counter_style_create(
                definition.m_name,
                extended.m_algorithm,
                definition.m_negative_sign else extended.m_negative_sign,
                definition.m_prefix else extended.m_prefix,
                definition.m_suffix else extended.m_suffix,
                range,
                definition.m_fallback else (extended.m_fallback else ak.fly_string_from_str("decimal")),
                definition.m_pad else extended.m_pad,
            )
        .css_counter_style_algorithm(algorithm):
            let range = match definition.m_range:
                .vector_css_counter_style_range_entry(range) => range
                _ => css_auto_range_resolve(algorithm)
            return css_counter_style_create(
                definition.m_name,
                algorithm,
                definition.m_negative_sign else CssCounterStyleNegativeSign(prefix = ak.fly_string_from_str("-"), suffix = ak.fly_string_from_str("")),
                definition.m_prefix else ak.fly_string_from_str(""),
                definition.m_suffix else ak.fly_string_from_str(". "),
                range,
                definition.m_fallback else ak.fly_string_from_str("decimal"),
                definition.m_pad else CssCounterStylePad(minimum_length = 0, symbol = ak.fly_string_from_str("")),
            )

# mark: Accessors and comparison ================================================================

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:30 Web::CSS::CounterStyle::name.
pub func css_counter_style_name(this: CssCounterStyle*) -> ak.FlyString:
    return this.m_name

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:31 Web::CSS::CounterStyle::algorithm.
pub func css_counter_style_algorithm(this: CssCounterStyle*) -> CssCounterStyleAlgorithm:
    return this.m_algorithm

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:32 Web::CSS::CounterStyle::negative_sign.
pub func css_counter_style_negative_sign(this: CssCounterStyle*) -> CssCounterStyleNegativeSign:
    return this.m_negative_sign

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:33 Web::CSS::CounterStyle::prefix.
pub func css_counter_style_prefix(this: CssCounterStyle*) -> ak.FlyString:
    return this.m_prefix

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:34 Web::CSS::CounterStyle::suffix.
pub func css_counter_style_suffix(this: CssCounterStyle*) -> ak.FlyString:
    return this.m_suffix

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:35 Web::CSS::CounterStyle::range.
pub func css_counter_style_range(this: CssCounterStyle*) -> ak.Vector[CssCounterStyleRangeEntry]:
    return this.m_range

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:36 Web::CSS::CounterStyle::fallback.
pub func css_counter_style_fallback(this: CssCounterStyle*) -> ak.FlyString?:
    return this.m_fallback

## Ported from Libraries/LibWeb/CSS/CounterStyle.h:37 Web::CSS::CounterStyle::pad.
pub func css_counter_style_pad(this: CssCounterStyle*) -> CssCounterStylePad:
    return this.m_pad

## Ported from Libraries/LibWeb/CSS/CounterStyle.cpp:83 Web::CSS::CounterStyle::equals.
pub func css_counter_style_equals(this: CssCounterStyle*, other: CssCounterStyle*) -> bool:
    return ak.fly_string_eq_fly_string(&this.m_name, &other.m_name) and css_counter_style_algorithm_eq(&this.m_algorithm, &other.m_algorithm) and css_counter_style_negative_sign_eq(&this.m_negative_sign, &other.m_negative_sign) and ak.fly_string_eq_fly_string(&this.m_prefix, &other.m_prefix) and ak.fly_string_eq_fly_string(&this.m_suffix, &other.m_suffix) and css_counter_style_ranges_eq(&this.m_range, &other.m_range) and css_counter_style_pad_eq(&this.m_pad, &other.m_pad) and css_counter_style_optional_fly_strings_eq(this.m_fallback, other.m_fallback)

## CounterStyleNegativeSign's defaulted operator==.
pub func css_counter_style_negative_sign_eq(a: const CssCounterStyleNegativeSign*, b: const CssCounterStyleNegativeSign*) -> bool:
    return ak.fly_string_eq_fly_string(&a.prefix, &b.prefix) and ak.fly_string_eq_fly_string(&a.suffix, &b.suffix)

## CounterStylePad's defaulted operator==.
pub func css_counter_style_pad_eq(a: const CssCounterStylePad*, b: const CssCounterStylePad*) -> bool:
    return a.minimum_length == b.minimum_length and ak.fly_string_eq_fly_string(&a.symbol, &b.symbol)

## Vector<CounterStyleRangeEntry>'s operator==.
pub func css_counter_style_ranges_eq(a: const ak.Vector[CssCounterStyleRangeEntry]*, b: const ak.Vector[CssCounterStyleRangeEntry]*) -> bool:
    if ak.vector_size(a) != ak.vector_size(b):
        return false
    for i in 0..<ak.vector_size(a):
        if *ak.vector_at_const(a, i) != *ak.vector_at_const(b, i):
            return false
    return true

## Optional<FlyString>'s operator==.
func css_counter_style_optional_fly_strings_eq(a: ak.FlyString?, b: ak.FlyString?) -> bool:
    if let left = a:
        if let right = b:
            return ak.fly_string_eq_fly_string(&left, &right)
        return false
    return b == none

## Vector<FlyString>'s operator==.
func css_counter_style_symbols_eq(a: const ak.Vector[ak.FlyString]*, b: const ak.Vector[ak.FlyString]*) -> bool:
    if ak.vector_size(a) != ak.vector_size(b):
        return false
    for i in 0..<ak.vector_size(a):
        if not ak.fly_string_eq_fly_string(ak.vector_at_const(a, i), ak.vector_at_const(b, i)):
            return false
    return true

## CounterStyleAlgorithm's operator== (Variant's: the same alternative, then its defaulted operator==).
pub func css_counter_style_algorithm_eq(a: const CssCounterStyleAlgorithm*, b: const CssCounterStyleAlgorithm*) -> bool:
    match *a:
        .css_additive_counter_style_algorithm(left):
            match *b:
                .css_additive_counter_style_algorithm(right):
                    if ak.vector_size(&left.symbol_list) != ak.vector_size(&right.symbol_list):
                        return false
                    for i in 0..<ak.vector_size(&left.symbol_list):
                        let left_tuple = ak.vector_at_const(&left.symbol_list, i)
                        let right_tuple = ak.vector_at_const(&right.symbol_list, i)
                        if left_tuple.weight != right_tuple.weight or not ak.fly_string_eq_fly_string(&left_tuple.symbol, &right_tuple.symbol):
                            return false
                    return true
                _: return false
        .css_fixed_counter_style_algorithm(left):
            match *b:
                .css_fixed_counter_style_algorithm(right): return left.first_symbol == right.first_symbol and css_counter_style_symbols_eq(&left.symbol_list, &right.symbol_list)
                _: return false
        .css_generic_counter_style_algorithm(left):
            match *b:
                .css_generic_counter_style_algorithm(right): return left.type_ == right.type_ and css_counter_style_symbols_eq(&left.symbol_list, &right.symbol_list)
                _: return false
        .css_ethiopic_numeric_counter_style_algorithm(_):
            match *b:
                .css_ethiopic_numeric_counter_style_algorithm(_): return true
                _: return false
        .css_extended_cjk_counter_style_algorithm(left):
            match *b:
                .css_extended_cjk_counter_style_algorithm(right): return left.type_ == right.type_
                _: return false

# mark: Extended CJK ============================================================================

## Ported from Libraries/LibWeb/CSS/CounterStyle.cpp:88 Web::CSS::generate_an_initial_representation_for_extended_cjk_system.
# https://drafts.csswg.org/css-counter-styles-3/#extended-range-optional
func css_generate_an_initial_representation_for_extended_cjk_system(value_: i64, type_: CssExtendedCjkCounterStyleAlgorithmType, digit_strings: ak.FlyString[10], digit_marker_strings: ak.FlyString[3], group_marker_strings: ak.FlyString[3]) -> ak.String:
    var value = value_

    # 1. If the counter value is 0, the representation is the character for 0 specified for the given counter style.
    #    Skip the rest of this algorithm.
    if value == 0:
        return ak.fly_string_to_string_const(&digit_strings[0])

    # 2. If the counter value is negative, instead use the absolute value of the counter value for the remaining steps
    #    of this algorithm.
    # NB: This is handled within `generate_a_counter_representation_impl`

    # 3. Initially represent the counter value as a decimal number. Starting from the right (ones place), split the
    #    decimal number into groups of four digits.
    var groups = ak.Vector[u16]()
    while value > 0:
        ak.vector_append_t(&groups, (u16)(value % 10000))
        value = value // 10000

    var builder = ak.string_builder_new()

    let group_count = (i32)ak.vector_size(&groups)
    var group_index = group_count - 1
    while group_index >= 0:
        let group_value = *ak.vector_at_const(&groups, (usize)group_index)

        var digits = ak.Vector[u8]()

        var temp_group_value = group_value
        while temp_group_value > 0:
            ak.vector_append_t(&digits, (u8)(temp_group_value % 10))
            temp_group_value = temp_group_value // 10

        # NB: Pad the group with zeroes up to four digits, unless this is the most significant group.
        if group_index != group_count - 1:
            while ak.vector_size(&digits) < 4:
                ak.vector_append_t(&digits, (u8)0)

        # NB: We move around the order of spec steps to work with a string builder rather than replacing characters in
        #     a string.
        var digit_index = (i32)ak.vector_size(&digits) - 1
        while digit_index >= 0:
            let digit_value = *ak.vector_at_const(&digits, (usize)digit_index)

            var should_drop_digit = false
            # 6. Drop ones:
            #  - For the Chinese informal styles, for any group with a value between ten and nineteen, remove the tens
            #    digit (leave the digit marker).
            if type_ == CssExtendedCjkCounterStyleAlgorithmType.simp_chinese_informal or type_ == CssExtendedCjkCounterStyleAlgorithmType.trad_chinese_informal:
                should_drop_digit = should_drop_digit or (group_value >= 10 and group_value < 20 and digit_index == 1)

            #  - For the Japanese informal and Korean informal styles, if any of the digit markers are preceded
            #   by the digit 1, and that digit is not the first digit of the group, remove the digit (leave the
            #    digit marker).
            if type_ == CssExtendedCjkCounterStyleAlgorithmType.japanese_informal or type_ == CssExtendedCjkCounterStyleAlgorithmType.korean_hanja_informal:
                should_drop_digit = should_drop_digit or (digit_value == 1 and digit_index != 0)

            #  - For Korean informal styles, if the value of the ten-thousands group is 1, drop the digit (leave the
            #    digit marker).
            if type_ == CssExtendedCjkCounterStyleAlgorithmType.korean_hanja_informal:
                should_drop_digit = should_drop_digit or (group_index == 1 and group_value == 1 and digit_index == 0)

            # 7. Drop zeros:
            #  - For the Japanese and Korean styles, drop all zero digits.
            if type_ == CssExtendedCjkCounterStyleAlgorithmType.japanese_informal or type_ == CssExtendedCjkCounterStyleAlgorithmType.japanese_formal or type_ == CssExtendedCjkCounterStyleAlgorithmType.korean_hangul_formal or type_ == CssExtendedCjkCounterStyleAlgorithmType.korean_hanja_informal or type_ == CssExtendedCjkCounterStyleAlgorithmType.korean_hanja_formal:
                should_drop_digit = should_drop_digit or digit_value == 0

            #  - For the Chinese styles, drop any trailing zeros for all non-zero groups and collapse (across groups)
            #    each remaining consecutive group of zeros into a single zero digit.
            if type_ == CssExtendedCjkCounterStyleAlgorithmType.simp_chinese_informal or type_ == CssExtendedCjkCounterStyleAlgorithmType.simp_chinese_formal or type_ == CssExtendedCjkCounterStyleAlgorithmType.trad_chinese_informal or type_ == CssExtendedCjkCounterStyleAlgorithmType.trad_chinese_formal:
                var is_trailing_zero = true
                var trailing_zero_index = digit_index
                while trailing_zero_index >= 0:
                    if *ak.vector_at_const(&digits, (usize)trailing_zero_index) != 0:
                        is_trailing_zero = false
                        break
                    trailing_zero_index -= 1

                should_drop_digit = should_drop_digit or is_trailing_zero

                # NB: We don't need to worry about collapsing across groups since dropping trailing zeroes above means
                #     that a run of zeroes can't occur at the end of a group.
                should_drop_digit = should_drop_digit or (digit_value == 0 and digit_index != 3 and *ak.vector_at_const(&digits, (usize)(digit_index + 1)) == 0)

            # 9. Replace the digits 0-9 with the appropriate character for the given counter style.
            if not should_drop_digit:
                ak.string_builder_append_string_view(&builder, ak.fly_string_bytes_as_string_view(&digit_strings[digit_value]))

            # 5. Within each group, for each digit that is not 0, append the appropriate digit marker to the digit.
            #    The ones digit of each group has no marker.
            if digit_value != 0 and digit_index != 0:
                ak.string_builder_append_string_view(&builder, ak.fly_string_bytes_as_string_view(&digit_marker_strings[(usize)(digit_index - 1)]))
            digit_index -= 1

        # 4. For each group with a non-zero value, append the appropriate group marker to the group. The ones group has no marker.
        if *ak.vector_at_const(&groups, (usize)group_index) != 0 and group_index != 0:
            ak.string_builder_append_string_view(&builder, ak.fly_string_bytes_as_string_view(&group_marker_strings[(usize)(group_index - 1)]))

        # 8. For the Korean styles, insert a space (" " U+0020) between each group.
        if (type_ == CssExtendedCjkCounterStyleAlgorithmType.korean_hangul_formal or type_ == CssExtendedCjkCounterStyleAlgorithmType.korean_hanja_informal or type_ == CssExtendedCjkCounterStyleAlgorithmType.korean_hanja_formal) and group_index != 0:
            ak.string_builder_append_u8(&builder, ' ')
        group_index -= 1

    # 10. If the counter value was negative, prepend the appropriate negative sign character for the given counter
    #     style as specified in the table of characters for each style.
    # NB: This is handled within `generate_a_counter_representation_impl`

    # 11. Return the resultant string as the representation of the counter value.
    return ak.string_builder_to_string(&builder) else trap("MUST: StringBuilder::to_string")