Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / css / parser / descriptor_parsing_1.lucb

#==============================================================================================
#
#   descriptor_parsing_1 - parsing descriptor values: the value types of Descriptors.json
#
#   DESCRIPTION:
#       Port of the `[&](DescriptorMetadata::ValueType value_type) { switch (value_type) ... }`
#       lambda of Parser::parse_descriptor_value, LibWeb/CSS/Parser/DescriptorParsing.cpp
#       (lines 82-388), with the lambdas nested in it: one branch per DescriptorMetadata
#       value type (counter-style systems, symbols, ranges and pads, crop/cross, family
#       names, font sources, font weights, lengths, declaration values, page sizes,
#       percentages, strings, symbols and unicode ranges). descriptor_parsing_2 holds the rest
#       of parse_descriptor_value.
#
#       Copyright (c) 2025, Sam Atkins <sam@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Nested lambdas ==========================================================================

## The `[this](auto& tokens) { return parse_nonnegative_integer_symbol_pair_value(tokens); }` lambda.
func css_parser_parse_nonnegative_integer_symbol_pair_value_callback(context: void*?, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssStyleValue*?:
    return css_parser_parse_nonnegative_integer_symbol_pair_value((CssParser*)(context else trap("no parser")), tokens)

## The `[this](auto& tokens) -> RefPtr<StyleValue const> { return parse_unicode_range_value(tokens); }` lambda.
func css_parser_parse_unicode_range_value_callback(context: void*?, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssStyleValue*?:
    if let unicode_range = css_parser_parse_unicode_range_value((CssParser*)(context else trap("no parser")), tokens):
        return unicode_range.css_style_value()
    return none

## The captures of the CounterStyleRange lambda (`[&]`): the parser and the optional computation context.
struct CssParserCounterStyleRangeCaptures:
    var this: CssParser*
    var computation_context: CssComputationContext?

## The `parse_value` lambda of the CounterStyleRange lambda: `infinite` or an <integer>.
func css_parser_parse_counter_style_range_bound(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssStyleValue*?:
    if let keyword_value = css_parser_parse_specific_keyword_value(this, tokens, css_data.Keyword.infinite):
        return keyword_value

    if let integer_value = css_parser_parse_integer_value(this, tokens, css_infinite_integer_range):
        return integer_value

    return none

## The `resolve_value` lambda of the CounterStyleRange lambda.
func css_resolve_counter_style_range_bound(value: CssStyleValue*, infinite_value: i32, computation_context: const (CssComputationContext?)*) -> i32?:
    if css_style_value_is_integer(value):
        return css_integer_style_value_integer(css_style_value_as_integer(value))

    if css_style_value_is_keyword(value) and css_keyword_style_value_keyword(css_style_value_as_keyword(value)) == css_data.Keyword.infinite:
        return infinite_value

    # FIXME: How should we actually handle calc() when we have no document to absolutize against
    let context = *computation_context else return none

    return css_calculated_style_value_resolve_integer(css_style_value_as_calculated(css_style_value_absolutized(value, context)), CssCalculationResolutionContext()) else trap("VERIFY: an integer")

## The CounterStyleRange lambda passed to parse_comma_separated_value_list: one `[ <integer> | infinite ]{2}`.
func css_parser_parse_counter_style_range(context: void*?, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssStyleValue*?:
    let captures = (CssParserCounterStyleRangeCaptures*)(context else trap("no captures"))
    let first_value = css_parser_parse_counter_style_range_bound(captures.this, tokens)
    let second_value = css_parser_parse_counter_style_range_bound(captures.this, tokens)

    if first_value == none or second_value == none:
        return none
    let first = first_value else trap("unreachable")
    let second = second_value else trap("unreachable")

    # If the lower bound of any range is higher than the upper bound, the entire descriptor is
    # invalid and must be ignored.
    let first_int = css_resolve_counter_style_range_bound(first, ak.i32_min, &captures.computation_context)
    let second_int = css_resolve_counter_style_range_bound(second, ak.i32_max, &captures.computation_context)

    if first_int == none or second_int == none or (first_int else trap("unreachable")) > (second_int else trap("unreachable")):
        return none

    var values = ak.Vector[CssStyleValue*]()
    ak.vector_append_t(&values, first)
    ak.vector_append_t(&values, second)
    return css_style_value_list_create(values, CssStyleValueListSeparator.space, CssStyleValueListCollapsible.no).css_style_value()

## A space-separated StyleValueList of one or two values: `StyleValueList::create({ ... }, Separator::Space, collapsible)`.
func css_space_separated_list(first: CssStyleValue*, second: CssStyleValue*?, collapsible: CssStyleValueListCollapsible = CssStyleValueListCollapsible.yes) -> CssStyleValue*:
    var values = ak.Vector[CssStyleValue*]()
    ak.vector_append_t(&values, first)
    if let second_value = second:
        ak.vector_append_t(&values, second_value)
    return css_style_value_list_create(values, CssStyleValueListSeparator.space, collapsible).css_style_value()

# mark: The value types =========================================================================

## The `[&](DescriptorMetadata::ValueType value_type) -> RefPtr<StyleValue const>` lambda of
## parse_descriptor_value (DescriptorParsing.cpp:82): parse a value of one of the value types.
func css_parser_parse_descriptor_value_of_value_type(this: CssParser*, value_type: css_data.DescriptorMetadataValueType, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*,
                                                     computation_context: CssComputationContext?) -> CssStyleValue*?:
    match value_type:
        .counter_style_additive_symbols:
            # [ <integer [0,∞]> && <symbol> ]#
            let additive_tuples = css_parser_parse_comma_separated_value_list(this, tokens,
                                                                              ak.Function1[css_syntax.TokenStream[css_syntax.ComponentValue]*, CssStyleValue*?](
                call = css_parser_parse_nonnegative_integer_symbol_pair_value_callback, context = this)) else return none

            # https://drafts.csswg.org/css-counter-styles-3/#counter-style-symbols
            # Each entry in the additive-symbols descriptor’s value defines an additive tuple, which consists
            # of a counter symbol and an integer weight. Each weight must be a non-negative integer, and the
            # additive tuples must be specified in order of strictly descending weight; otherwise, the
            # declaration is invalid and must be ignored.
            var previous_weight: i32 = ak.i32_max

            let tuples = css_style_value_list_values(css_style_value_as_value_list(additive_tuples.css_style_value()))
            for tuple_style_value in ak.vector_span_const(&tuples):
                let weight = css_style_value_list_value_at(css_style_value_as_value_list(tuple_style_value), 0, false)

                var resolved_weight: i32 = 0

                if css_style_value_is_integer(weight):
                    resolved_weight = css_integer_style_value_integer(css_style_value_as_integer(weight))
                else:
                    # FIXME: How should we actually handle calc() when we have no document to absolutize against
                    let context = computation_context else return none

                    resolved_weight = css_calculated_style_value_resolve_integer(css_style_value_as_calculated(css_style_value_absolutized(weight, context)), CssCalculationResolutionContext()) else trap("VERIFY: an integer")

                if resolved_weight >= previous_weight:
                    return none

                previous_weight = resolved_weight

            return additive_tuples.css_style_value()
        .counter_style_system:
            # https://drafts.csswg.org/css-counter-styles-3/#counter-style-system
            # cyclic | numeric | alphabetic | symbolic | additive | [fixed <integer>?] | [ extends <counter-style-name> ]
            let keyword_value = css_parser_parse_keyword_value(this, tokens) else return none

            if let system = css_data.keyword_to_counter_style_system(css_style_value_to_keyword(keyword_value)):
                return css_counter_style_system_style_value_create(system)

            if css_style_value_to_keyword(keyword_value) == css_data.Keyword.fixed:
                let integer_value = css_parser_parse_integer_value(this, tokens, css_infinite_integer_range)

                return css_counter_style_system_style_value_create_fixed(integer_value)

            if css_style_value_to_keyword(keyword_value) == css_data.Keyword.extends:
                let counter_style_name = css_parser_parse_counter_style_name(this, tokens) else return none

                return css_counter_style_system_style_value_create_extends(counter_style_name)

            return none
        .counter_style_name:
            let counter_style_name = css_parser_parse_counter_style_name(this, tokens) else return none

            return css_custom_ident_style_value_create(counter_style_name).css_style_value()
        .counter_style_negative:
            # https://drafts.csswg.org/css-counter-styles-3/#counter-style-negative
            # <symbol> <symbol>?
            let first_symbol = css_parser_parse_symbol_value(this, tokens)
            let second_symbol = css_parser_parse_symbol_value(this, tokens)

            let first = first_symbol else return none

            if second_symbol == none:
                return css_space_separated_list(first, none)

            return css_space_separated_list(first, second_symbol, CssStyleValueListCollapsible.no)
        .counter_style_pad:
            # https://drafts.csswg.org/css-counter-styles-3/#counter-style-pad
            # <integer [0,∞]> && <symbol>
            return css_parser_parse_nonnegative_integer_symbol_pair_value(this, tokens)
        .counter_style_range:
            # https://drafts.csswg.org/css-counter-styles-3/#counter-style-range
            # [ [ <integer> | infinite ]{2} ]# | auto
            if let value = css_parser_parse_all_as_single_keyword_value(this, tokens, css_data.Keyword.auto):
                return value

            var captures = CssParserCounterStyleRangeCaptures(this = this, computation_context = computation_context)
            if let ranges = css_parser_parse_comma_separated_value_list(this, tokens, ak.Function1[css_syntax.TokenStream[css_syntax.ComponentValue]*, CssStyleValue*?](
                call = css_parser_parse_counter_style_range, context = &captures)):
                return ranges.css_style_value()
            return none
        .crop_or_cross:
            # crop || cross
            let first_keyword = css_parser_parse_keyword_value(this, tokens)
            css_syntax.token_stream_discard_whitespace(tokens)
            let second_keyword = css_parser_parse_keyword_value(this, tokens)

            let first = first_keyword else return none

            var crop: CssStyleValue*? = none
            var cross: CssStyleValue*? = none

            if css_style_value_to_keyword(first) == css_data.Keyword.crop:
                crop = first
            elif css_style_value_to_keyword(first) == css_data.Keyword.cross:
                cross = first
            else:
                return none

            let second = second_keyword else return first

            if crop == none and css_style_value_to_keyword(second) == css_data.Keyword.crop:
                crop = second
            elif cross == none and css_style_value_to_keyword(second) == css_data.Keyword.cross:
                cross = second
            else:
                return none

            return css_space_separated_list(crop else trap("VERIFY: crop"), cross else trap("VERIFY: cross"))
        .family_name:
            return css_parser_parse_family_name_value(this, tokens)
        .font_src_list:
            # "If a component value is parsed correctly and is of a font format or font tech that the UA
            # supports, add it to the list of supported sources. If parsing a component value results in a
            # parsing error or its format or tech are unsupported, do not add it to the list of supported
            # sources.
            # If there are no supported entries at the end of this process, the value for the src descriptor
            # is a parse error.
            # These parsing rules allow for graceful fallback of fonts for user agents which don’t support a
            # particular font tech or font format."
            # https://drafts.csswg.org/css-fonts-4/#font-face-src-parsing
            let source_lists = css_parser_parse_a_comma_separated_list_of_component_values(this, tokens)
            var valid_sources = ak.Vector[CssStyleValue*]()
            for source_list in ak.vector_span_const(&source_lists):
                var source_tokens = css_syntax.token_stream_create(source_list)
                if let font_source = css_parser_parse_font_source_value(this, &source_tokens):
                    if not css_syntax.token_stream_has_next_token(&source_tokens):
                        ak.vector_append_t(&valid_sources, font_source.css_style_value())
            if ak.vector_is_empty(&valid_sources):
                return none
            return css_style_value_list_create(valid_sources, CssStyleValueListSeparator.comma).css_style_value()
        .font_weight_absolute_pair:
            # <font-weight-absolute>{1,2}
            let first = css_parser_parse_font_weight_absolute_value(this, tokens) else return none
            css_syntax.token_stream_discard_whitespace(tokens)
            if not css_syntax.token_stream_has_next_token(tokens):
                return css_space_separated_list(first, none)
            let second = css_parser_parse_font_weight_absolute_value(this, tokens) else return none
            return css_space_separated_list(first, second)
        .length:
            return css_parser_parse_length_value(this, tokens, css_infinite_range)
        .optional_declaration_value:
            css_syntax.token_stream_discard_whitespace(tokens)

            if css_syntax.token_stream_is_empty(tokens):
                return css_unresolved_style_value_create(ak.Vector[css_syntax.ComponentValue](), css_syntax.SubstitutionFunctionsPresence()).css_style_value()

            if let parsed_declaration_value = css_parser_parse_declaration_value(tokens):
                if css_syntax.token_stream_is_empty(tokens):
                    # NB: We know this contains no substitution functions otherwise we would have returned earlier
                    return css_unresolved_style_value_create(parsed_declaration_value, css_syntax.SubstitutionFunctionsPresence()).css_style_value()

            return none
        .page_size:
            # https://drafts.csswg.org/css-page-3/#page-size-prop
            # <length [0,∞]>{1,2} | auto | [ <page-size> || [ portrait | landscape ] ]

            # auto
            if let value = css_parser_parse_all_as_single_keyword_value(this, tokens, css_data.Keyword.auto):
                return value

            # <length [0,∞]>{1,2}
            if let first_length = css_parser_parse_length_value(this, tokens, css_non_negative_range):
                css_syntax.token_stream_discard_whitespace(tokens)

                if let second_length = css_parser_parse_length_value(this, tokens, css_non_negative_range):
                    return css_space_separated_list(first_length, second_length)

                return first_length

            # [ <page-size> || [ portrait | landscape ] ]
            var page_size: CssStyleValue*? = none
            var orientation: CssStyleValue*? = none
            if let first_keyword = css_parser_parse_keyword_value(this, tokens):
                let keyword = css_style_value_to_keyword(first_keyword)
                if keyword == css_data.Keyword.landscape or keyword == css_data.Keyword.portrait:
                    orientation = first_keyword
                elif css_data.keyword_to_page_size(keyword) != none:
                    page_size = first_keyword
                else:
                    return none
            else:
                return none

            css_syntax.token_stream_discard_whitespace(tokens)

            if let second_keyword = css_parser_parse_keyword_value(this, tokens):
                let keyword = css_style_value_to_keyword(second_keyword)
                if orientation == none and (keyword == css_data.Keyword.landscape or keyword == css_data.Keyword.portrait):
                    orientation = second_keyword
                elif page_size == none and css_data.keyword_to_page_size(keyword) != none:
                    page_size = second_keyword
                else:
                    return none

                # Portrait is considered the default orientation, so don't include it.
                if css_style_value_to_keyword(orientation else trap("VERIFY: an orientation")) == css_data.Keyword.portrait:
                    return page_size else trap("VERIFY: a page size")

                return css_space_separated_list(page_size else trap("VERIFY: a page size"), orientation)

            if let size = page_size:
                return size
            return orientation else trap("VERIFY: an orientation")
        .positive_percentage:
            if let percentage_value = css_parser_parse_percentage_value(this, tokens, css_non_negative_range):
                if css_style_value_is_percentage(percentage_value):
                    return percentage_value

                # FIXME: Support relative lengths within calcs here (i.e. by absolutizing and clamping rather
                #        than rejecting anything that doesn't resolve at parse time)
                if css_style_value_is_calculated(percentage_value):
                    let percentage = css_calculated_style_value_resolve_percentage(css_style_value_as_calculated(percentage_value), CssCalculationResolutionContext())
                    if let resolved = percentage:
                        if css_percentage_value(&resolved) >= 0.0:
                            return css_percentage_style_value_create(resolved).css_style_value()
                    return none
            return none
        .string:
            if let string_value = css_parser_parse_string_value(this, tokens):
                return string_value.css_style_value()
            return none
        .symbol:
            return css_parser_parse_symbol_value(this, tokens)
        .symbols:
            # <symbol>+
            var symbols = ak.Vector[CssStyleValue*]()
            while css_syntax.token_stream_has_next_token(tokens):
                let symbol = css_parser_parse_symbol_value(this, tokens) else break
                ak.vector_append_t(&symbols, symbol)

            if ak.vector_is_empty(&symbols):
                return none

            return css_style_value_list_create(symbols, CssStyleValueListSeparator.space, CssStyleValueListCollapsible.no).css_style_value()
        .unicode_range_tokens:
            if let unicode_ranges = css_parser_parse_comma_separated_value_list(this, tokens, ak.Function1[css_syntax.TokenStream[css_syntax.ComponentValue]*, CssStyleValue*?](
                call = css_parser_parse_unicode_range_value_callback, context = this)):
                return unicode_ranges.css_style_value()
            return none
        _:
            return none