Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

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

#==============================================================================================
#
#   rule_parsing_3 - converting parsed rules to CSSOM rules: @property, @container,
#                    @counter-style and @font-face
#
#   DESCRIPTION:
#       Port of LibWeb/CSS/Parser/RuleParsing.cpp (lines 710-1061): convert_to_property_rule,
#       convert_to_container_rule, convert_to_counter_style_rule and convert_to_font_face_rule.
#       Their for_each_as_declaration_list lambdas are the functions before them, with a
#       capture struct each.
#
#       Copyright (c) 2018-2022, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2020-2021, the SerenityOS developers.
#       Copyright (c) 2021-2026, Sam Atkins <sam@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: @property ===============================================================================

## The captures of convert_to_property_rule's `for_each_as_declaration_list` lambda (`[&]`): the parser and
## the three descriptors it collects.
struct CssParserConvertToPropertyRuleCaptures:
    var this: CssParser*
    var syntax_maybe: ak.FlyString?
    var inherits_maybe: bool?
    var initial_value_maybe: CssStyleValue*?

## The `[&](auto& declaration) { ... }` lambda of convert_to_property_rule.
func css_parser_convert_to_property_rule_descriptor(context: void*?, declaration: const css_syntax.Declaration*):
    let captures = (CssParserConvertToPropertyRuleCaptures*)(context else trap("no captures"))
    if let descriptor = css_parser_convert_to_descriptor(captures.this, css_data.AtRuleId.property, *declaration):
        if css_descriptor_name_and_id_id(&descriptor.descriptor_name_and_id) == css_data.DescriptorId.syntax:
            if css_style_value_is_string(descriptor.value):
                captures.syntax_maybe = css_string_style_value_string_value(css_style_value_as_string(descriptor.value))
            return
        if css_descriptor_name_and_id_id(&descriptor.descriptor_name_and_id) == css_data.DescriptorId.inherits:
            match css_style_value_to_keyword(descriptor.value):
                .true_:
                    captures.inherits_maybe = true
                .false_:
                    captures.inherits_maybe = false
                _:
                    return
            return
        if css_descriptor_name_and_id_id(&descriptor.descriptor_name_and_id) == css_data.DescriptorId.initial_value:
            captures.initial_value_maybe = descriptor.value
            return

## `is_a_custom_property_name_string(token.ident())`.
func css_token_ident_is_a_custom_property_name(token: const css_syntax.Token*) -> bool:
    let ident = css_syntax.token_ident(token)
    return css_data.is_a_custom_property_name_string(ak.fly_string_bytes_as_string_view(&ident))

## Ported from Libraries/LibWeb/CSS/Parser/RuleParsing.cpp:710 Web::CSS::Parser::Parser::convert_to_property_rule.
pub func css_parser_convert_to_property_rule(this: CssParser*, rule: css_syntax.AtRule) -> CssPropertyRule*?:
    # https://drafts.css-houdini.org/css-properties-values-api-1/#at-ruledef-property
    # @property <custom-property-name> {
    # <declaration-list>
    # }
    var prelude_stream = css_syntax.token_stream_create(rule.prelude)
    if not rule.is_block_rule:
        css_report_invalid_rule(ak.fly_string_from_str("@property"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Must be a block, not a statement."))
        return none

    if ak.vector_is_empty(&rule.prelude):
        css_report_invalid_rule(ak.fly_string_from_str("@property"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Empty prelude."))
        return none

    css_syntax.token_stream_discard_whitespace(&prelude_stream)
    let token = css_syntax.token_stream_consume_a_token(&prelude_stream)
    if not css_syntax.component_value_is_token(&token):
        css_report_invalid_rule(ak.fly_string_from_str("@property"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Name must be an ident."))
        return none

    let name_token = css_syntax.component_value_token(&token)
    css_syntax.token_stream_discard_whitespace(&prelude_stream)

    if css_syntax.token_stream_has_next_token(&prelude_stream):
        css_report_invalid_rule(ak.fly_string_from_str("@property"), css_syntax.token_stream_dump_string(&prelude_stream),
                                ak.string_from_str("Trailing tokens after name in prelude."))
        return none

    if not css_syntax.token_is(&name_token, .ident) or not css_token_ident_is_a_custom_property_name(&name_token):
        css_report_invalid_rule(ak.fly_string_from_str("@property"), css_syntax.token_stream_dump_string(&prelude_stream),
                                ak.string_from_str("Name must be an ident starting with '--'."))
        return none

    let name = css_syntax.token_ident(&name_token)

    var captures = CssParserConvertToPropertyRuleCaptures(this = this)
    css_syntax.at_rule_for_each_as_declaration_list(&rule, ak.Function1[const css_syntax.Declaration*, unit](call = css_parser_convert_to_property_rule_descriptor, context = &captures))

    # @property rules require a syntax and inherits descriptor; if either are missing, the entire rule is invalid and must be ignored.
    let syntax = captures.syntax_maybe else return none
    if ak.fly_string_is_empty(&syntax) or captures.inherits_maybe == none:
        return none

    var parsing_params: CssParsingParams = ---
    if let document = css_parser_document(this):
        css_parsing_params_construct_dom_document(&parsing_params, document)
    else:
        css_parsing_params_construct_realm_css_parsing_mode(&parsing_params, css_parser_realm(this))

    let syntax_component_values = parse_component_values_list(parsing_params, ak.fly_string_bytes_as_string_view(&syntax))
    let maybe_syntax = css_parse_as_syntax(syntax_component_values, CssLimitSingleComponentIdentToCustomIdent.yes)

    # If the provided string is not a valid syntax string (if it returns failure when consume
    # a syntax definition is called on it), the descriptor is invalid and must be ignored.
    let parsed_syntax = maybe_syntax else return none
    # The initial-value descriptor is optional only if the syntax is the universal syntax definition,
    # otherwise the descriptor is required; if it’s missing, the entire rule is invalid and must be ignored.
    if captures.initial_value_maybe == none and css_syntax_node_type(parsed_syntax) != CssSyntaxNodeNodeType.universal:
        return none

    var initial_value_maybe = captures.initial_value_maybe
    if let initial_value = initial_value_maybe:
        initial_value_maybe = css_parse_with_a_syntax(parsing_params, css_style_value_tokenize(initial_value), parsed_syntax)

        # Otherwise, if the value of the syntax descriptor is not the universal syntax definition,
        # the following conditions must be met for the @property rule to be valid:
        if css_syntax_node_type(parsed_syntax) != CssSyntaxNodeNodeType.universal:
            #  - The initial-value descriptor must be present.
            #  - The initial-value descriptor’s value must parse successfully according to the grammar specified by the syntax definition.
            #  - The initial-value must be computationally independent.
            let parsed_initial_value = initial_value_maybe else return none
            if css_style_value_is_guaranteed_invalid(parsed_initial_value) or not css_style_value_is_computationally_independent(parsed_initial_value):
                return none

    return css_property_rule_create(css_parser_realm(this), name, syntax, captures.inherits_maybe else trap("VERIFY: inherits"), initial_value_maybe)

# mark: @container ==============================================================================

## Ported from Libraries/LibWeb/CSS/Parser/RuleParsing.cpp:844 Web::CSS::Parser::Parser::convert_to_container_rule.
# https://drafts.csswg.org/css-conditional-5/#container-rule
pub func css_parser_convert_to_container_rule[TNestedDeclarationsRule](this: CssParser*, rule: css_syntax.AtRule, nested: CssParserNested) -> CssContainerRule*?:
    # @container <container-condition># {
    #   <block-contents>
    # }
    # <container-condition> = [ <container-name>? <container-query>? ]!
    # <container-name> = <custom-ident>

    var prelude_stream = css_syntax.token_stream_create(rule.prelude)
    if not rule.is_block_rule:
        css_report_invalid_rule(ak.fly_string_from_str("@container"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Must be a block, not a statement."))
        return none

    let prelude_item_values = css_parser_parse_a_comma_separated_list_of_component_values(this, &prelude_stream)
    if ak.vector_is_empty(&prelude_item_values):
        css_report_invalid_rule(ak.fly_string_from_str("@container"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Empty prelude."))
        return none

    var conditions = ak.Vector[CssContainerRuleCondition]()
    ak.vector_ensure_capacity(&conditions, ak.vector_size(&prelude_item_values))

    for prelude_item in ak.vector_span_const(&prelude_item_values):
        var item_tokens = css_syntax.token_stream_create(prelude_item)
        css_syntax.token_stream_discard_whitespace(&item_tokens)
        # https://drafts.csswg.org/css-conditional-5/#container-name
        # The keywords none, and, not, and or are excluded from this <custom-ident>.
        let blacklist: ak.StringView[4] = [ak.sv("none"), ak.sv("and"), ak.sv("not"), ak.sv("or")]
        let container_name = css_parser_parse_custom_ident(this, &item_tokens, blacklist)
        css_syntax.token_stream_discard_whitespace(&item_tokens)
        let container_query = css_parser_parse_container_query(this, &item_tokens)
        if container_name == none and container_query == none:
            css_report_invalid_rule(ak.fly_string_from_str("@container"), css_syntax.token_stream_dump_string(&prelude_stream),
                                    ak.string_from_str("Missing container name or query."))
            return none

        css_syntax.token_stream_discard_whitespace(&item_tokens)
        if css_syntax.token_stream_has_next_token(&item_tokens):
            css_report_invalid_rule(ak.fly_string_from_str("@container"), css_syntax.token_stream_dump_string(&prelude_stream),
                                    ak.string_from_str("Trailing tokens after name and query."))
            return none

        ak.vector_append_t(&conditions, CssContainerRuleCondition(container_name = container_name, container_query = container_query))

    var child_rules = ak.Vector[CssRule*]()
    for child in ak.vector_span_const(&rule.child_rules_and_lists_of_declarations):
        match child:
            .rule(child_rule):
                if let converted_rule = css_parser_convert_to_rule[TNestedDeclarationsRule](this, child_rule, nested):
                    ak.vector_append_t(&child_rules, converted_rule)
            .vector_declaration(declarations):
                ak.vector_append_t(&child_rules, css_nested_declarations_create_css_style_properties(css_parser_realm(this),
                                                                                                     css_parser_convert_to_style_declaration(this, &declarations)).css_rule())

    let rule_list = css_rule_list_create(css_parser_realm(this), ak.vector_span_const(&child_rules))
    return css_container_rule_create(css_parser_realm(this), conditions, rule_list)

# mark: @counter-style ==========================================================================

## The captures of convert_to_counter_style_rule's `for_each_as_declaration_list` lambda (`[&]`): the parser and
## the ten descriptors it collects.
struct CssParserConvertToCounterStyleRuleCaptures:
    var this: CssParser*
    var system: CssStyleValue*?
    var negative: CssStyleValue*?
    var prefix: CssStyleValue*?
    var suffix: CssStyleValue*?
    var range: CssStyleValue*?
    var pad_: CssStyleValue*?
    var fallback: CssStyleValue*?
    var symbols: CssStyleValue*?
    var additive_symbols: CssStyleValue*?
    var speak_as: CssStyleValue*?

## The `[&](auto& declaration) { ... }` lambda of convert_to_counter_style_rule.
func css_parser_convert_to_counter_style_rule_descriptor(context: void*?, declaration: const css_syntax.Declaration*):
    let captures = (CssParserConvertToCounterStyleRuleCaptures*)(context else trap("no captures"))
    let descriptor = css_parser_convert_to_descriptor(captures.this, css_data.AtRuleId.counter_style, *declaration) else return

    match css_descriptor_name_and_id_id(&descriptor.descriptor_name_and_id):
        .system:
            captures.system = descriptor.value
        .negative:
            captures.negative = descriptor.value
        .prefix:
            captures.prefix = descriptor.value
        .suffix:
            captures.suffix = descriptor.value
        .range:
            captures.range = descriptor.value
        .pad_:
            captures.pad_ = descriptor.value
        .fallback:
            captures.fallback = descriptor.value
        .symbols:
            captures.symbols = descriptor.value
        .additive_symbols:
            captures.additive_symbols = descriptor.value
        .speak_as:
            captures.speak_as = descriptor.value
        _:
            trap("VERIFY_NOT_REACHED")

## Ported from Libraries/LibWeb/CSS/Parser/RuleParsing.cpp:921 Web::CSS::Parser::Parser::convert_to_counter_style_rule.
pub func css_parser_convert_to_counter_style_rule(this: CssParser*, rule: css_syntax.AtRule) -> CssCounterStyleRule*?:
    # https://drafts.csswg.org/css-counter-styles-3/#the-counter-style-rule
    var prelude_stream = css_syntax.token_stream_create(rule.prelude)
    if not rule.is_block_rule:
        css_report_invalid_rule(ak.fly_string_from_str("@counter-style"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Must be a block, not a statement."))
        return none

    if ak.vector_is_empty(&rule.prelude):
        css_report_invalid_rule(ak.fly_string_from_str("@counter-style"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Empty prelude."))
        return none

    let maybe_name = css_parser_parse_counter_style_name(this, &prelude_stream)
    if maybe_name == none:
        css_report_invalid_rule(ak.fly_string_from_str("@counter-style"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Missing counter style name."))
        return none
    let name = maybe_name else trap("VERIFY: a name")

    css_syntax.token_stream_discard_whitespace(&prelude_stream)
    if css_syntax.token_stream_has_next_token(&prelude_stream):
        css_report_invalid_rule(ak.fly_string_from_str("@counter-style"), css_syntax.token_stream_dump_string(&prelude_stream),
                                ak.string_from_str("Trailing tokens after name in prelude."))
        return none

    # https://drafts.csswg.org/css-counter-styles-3/#typedef-counter-style-name
    # When used here, to define a counter style, it also cannot be any of the non-overridable counter-style names
    # FIXME: We should allow these in the UA stylesheet in order to initially define them.
    if css_counter_style_rule_matches_non_overridable_counter_style_name(name) and this.m_is_ua_style_sheet != CssIsUaStyleSheet.yes:
        css_report_invalid_rule(ak.fly_string_from_str("@counter-style"), css_syntax.token_stream_dump_string(&prelude_stream),
                                ak.string_from_str("Non-overridable counter style name."))
        return none

    var captures = CssParserConvertToCounterStyleRuleCaptures(this = this)
    css_syntax.at_rule_for_each_as_declaration_list(&rule, ak.Function1[const css_syntax.Declaration*, unit](call = css_parser_convert_to_counter_style_rule_descriptor, context = &captures))

    return css_counter_style_rule_create(css_parser_realm(this), name, captures.system, captures.negative, captures.prefix, captures.suffix, captures.range, captures.pad_,
                                         captures.fallback, captures.symbols, captures.additive_symbols, captures.speak_as)

# mark: @font-face ==============================================================================

## The captures of a `[&](auto& declaration) { ... descriptors.append(...) }` lambda: the parser, the at-rule
## the descriptors belong to, and the DescriptorList they go to.
struct CssParserAppendDescriptorCaptures:
    var this: CssParser*
    var at_rule_id: css_data.AtRuleId
    var descriptors: CssDescriptorList*

## The lambda: convert the declaration to a descriptor of the at-rule, and append it to the list.
func css_parser_append_descriptor(context: void*?, declaration: const css_syntax.Declaration*):
    let captures = (CssParserAppendDescriptorCaptures*)(context else trap("no captures"))
    if let descriptor = css_parser_convert_to_descriptor(captures.this, captures.at_rule_id, *declaration):
        css_descriptor_list_append(captures.descriptors, descriptor)

## Ported from Libraries/LibWeb/CSS/Parser/RuleParsing.cpp:1030 Web::CSS::Parser::Parser::convert_to_font_face_rule.
pub func css_parser_convert_to_font_face_rule(this: CssParser*, rule: css_syntax.AtRule) -> CssFontFaceRule*?:
    # https://drafts.csswg.org/css-fonts/#font-face-rule
    var prelude_stream = css_syntax.token_stream_create(rule.prelude)
    if not rule.is_block_rule:
        css_report_invalid_rule(ak.fly_string_from_str("@font-face"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Must be a block, not a statement."))
        return none

    css_syntax.token_stream_discard_whitespace(&prelude_stream)
    if css_syntax.token_stream_has_next_token(&prelude_stream):
        css_report_invalid_rule(ak.fly_string_from_str("@font-face"), css_syntax.token_stream_dump_string(&prelude_stream), ak.string_from_str("Prelude is not allowed."))
        return none

    var descriptors: CssDescriptorList = ---
    css_descriptor_list_construct(&descriptors, css_data.AtRuleId.font_face)
    var captures = CssParserAppendDescriptorCaptures(this = this, at_rule_id = css_data.AtRuleId.font_face, descriptors = &descriptors)
    css_syntax.at_rule_for_each_as_declaration_list(&rule, ak.Function1[const css_syntax.Declaration*, unit](call = css_parser_append_descriptor, context = &captures))

    return css_font_face_rule_create(css_parser_realm(this), css_css_font_face_descriptors_create(css_parser_realm(this), css_descriptor_list_release_descriptors(&descriptors)))