Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / css / parser / property_parsing_4.lucb

#==============================================================================================
#
#   property_parsing_4 - parsing property values: background and border
#
#   DESCRIPTION:
#       Port of LibWeb/CSS/Parser/PropertyParsing.cpp (lines 1122-1479): the background
#       shorthand (its per-layer state and lambdas), a single background-position-x/y value, a
#       single background-size value, and the border, border-block and border-inline
#       shorthands.
#
#==============================================================================================

# mark: background ==============================================================================

## The locals of parse_background_value that its lambdas capture by reference: the per-property lists of all
## layers, the per-layer values, the initial values and the properties the current layer may still set.
struct CssParserParseBackgroundValueState:
    var background_images: ak.Vector[CssStyleValue*]
    var background_position_xs: ak.Vector[CssStyleValue*]
    var background_position_ys: ak.Vector[CssStyleValue*]
    var background_sizes: ak.Vector[CssStyleValue*]
    var background_repeats: ak.Vector[CssStyleValue*]
    var background_attachments: ak.Vector[CssStyleValue*]
    var background_clips: ak.Vector[CssStyleValue*]
    var background_origins: ak.Vector[CssStyleValue*]
    var background_color: CssStyleValue*?

    var initial_background_image: CssStyleValue*?
    var initial_background_position_x: CssStyleValue*?
    var initial_background_position_y: CssStyleValue*?
    var initial_background_size: CssStyleValue*?
    var initial_background_repeat: CssStyleValue*?
    var initial_background_attachment: CssStyleValue*?
    var initial_background_clip: CssStyleValue*?
    var initial_background_origin: CssStyleValue*?

    # Per-layer values
    var background_image: CssStyleValue*?
    var background_position_x: CssStyleValue*?
    var background_position_y: CssStyleValue*?
    var background_size: CssStyleValue*?
    var background_repeat: CssStyleValue*?
    var background_attachment: CssStyleValue*?
    var background_clip: CssStyleValue*?
    var background_origin: CssStyleValue*?

    var remaining_layer_properties: ak.Vector[css_data.PropertyId]

## `property_initial_value(property_id)->as_value_list().values()[0]`.
func css_first_initial_value(property_id: css_data.PropertyId) -> CssStyleValue*:
    let values = css_style_value_list_values(css_style_value_as_value_list(css_property_initial_value(property_id)))
    return *ak.vector_at_const(&values, 0)

## The `make_background_shorthand` lambda of parse_background_value.
func css_make_background_shorthand(background_color: CssStyleValue*, background_image: CssStyleValue*, background_position: CssStyleValue*, background_size: CssStyleValue*,
                                   background_repeat: CssStyleValue*, background_attachment: CssStyleValue*, background_origin: CssStyleValue*, background_clip: CssStyleValue*) -> CssStyleValue*:
    return css_shorthand_of(css_data.PropertyId.background,
                            css_property_ids_of([css_data.PropertyId.background_color, css_data.PropertyId.background_image, css_data.PropertyId.background_position,
                                                 css_data.PropertyId.background_size, css_data.PropertyId.background_repeat, css_data.PropertyId.background_attachment,
                                                 css_data.PropertyId.background_origin, css_data.PropertyId.background_clip]),
                            css_style_values_of([background_color, background_image, background_position, background_size, background_repeat, background_attachment,
                                                 background_origin, background_clip]))

## The `background_layer_is_valid` lambda of parse_background_value.
func css_background_layer_is_valid(state: const CssParserParseBackgroundValueState*, allow_background_color: bool) -> bool:
    if allow_background_color:
        if state.background_color != none:
            return true
    else:
        if state.background_color != none:
            return false
    return (state.background_image != none or state.background_position_x != none or state.background_position_y != none or state.background_size != none or state.background_repeat != none or state.background_attachment != none or state.background_clip != none or state.background_origin != none)

## `value ? value.release_nonnull() : initial`.
func css_value_or_initial(value: CssStyleValue*?, initial: CssStyleValue*?) -> CssStyleValue*:
    if let present = value:
        return present
    return initial else trap("VERIFY: an initial value")

## Sets `properties` to the properties a background layer may set (background-size is parsed with
## background-position).
func css_set_background_layer_properties(properties: ak.Vector[css_data.PropertyId]*):
    ak.vector_unchecked_append_u(properties, css_data.PropertyId.background_attachment)
    ak.vector_unchecked_append_u(properties, css_data.PropertyId.background_clip)
    ak.vector_unchecked_append_u(properties, css_data.PropertyId.background_color)
    ak.vector_unchecked_append_u(properties, css_data.PropertyId.background_image)
    ak.vector_unchecked_append_u(properties, css_data.PropertyId.background_origin)
    ak.vector_unchecked_append_u(properties, css_data.PropertyId.background_position)
    ak.vector_unchecked_append_u(properties, css_data.PropertyId.background_repeat)

## The `complete_background_layer` lambda of parse_background_value.
func css_complete_background_layer(state: CssParserParseBackgroundValueState*):
    ak.vector_append_t(&state.background_images, css_value_or_initial(state.background_image, state.initial_background_image))
    ak.vector_append_t(&state.background_position_xs, css_value_or_initial(state.background_position_x, state.initial_background_position_x))
    ak.vector_append_t(&state.background_position_ys, css_value_or_initial(state.background_position_y, state.initial_background_position_y))
    ak.vector_append_t(&state.background_sizes, css_value_or_initial(state.background_size, state.initial_background_size))
    ak.vector_append_t(&state.background_repeats, css_value_or_initial(state.background_repeat, state.initial_background_repeat))
    ak.vector_append_t(&state.background_attachments, css_value_or_initial(state.background_attachment, state.initial_background_attachment))

    if state.background_origin == none and state.background_clip == none:
        state.background_origin = state.initial_background_origin
        state.background_clip = state.initial_background_clip
    elif state.background_clip == none:
        state.background_clip = state.background_origin
    ak.vector_append_t(&state.background_origins, state.background_origin else trap("release_nonnull"))
    ak.vector_append_t(&state.background_clips, state.background_clip else trap("release_nonnull"))

    state.background_image = none
    state.background_position_x = none
    state.background_position_y = none
    state.background_size = none
    state.background_repeat = none
    state.background_attachment = none
    state.background_clip = none
    state.background_origin = none

    ak.vector_clear_with_capacity(&state.remaining_layer_properties)
    css_set_background_layer_properties(&state.remaining_layer_properties)

## The block of parse_background_value's loop that parses the next value for one of the remaining layer
## properties, committing its transaction unless the value is a background-repeat (parsed again in full below).
func css_parser_parse_background_layer_property(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*,
                                                remaining_layer_properties: const ak.Vector[css_data.PropertyId]*) -> CssParserPropertyAndValue?:
    var value_transaction = css_syntax.token_stream_begin_transaction(tokens)
    defer css_syntax.state_transaction_destroy(&value_transaction)
    let property_and_value = css_parser_parse_css_value_for_properties(this, ak.vector_span_const(remaining_layer_properties), tokens) else return none
    # FIXME: background-repeat can't be parsed fully with parse_css_value_for_properties(), so don't commit
    #        the transaction, and then parse it manually below.
    if property_and_value.property != css_data.PropertyId.background_repeat:
        css_syntax.state_transaction_commit(&value_transaction)
    return property_and_value

## The `case PropertyID::BackgroundPosition` block of parse_background_value after the position: an optional
## `/ <background-size>`, in a transaction. False when a `/` is not followed by a background-size (the C++
## returns nullptr).
func css_parser_parse_background_size_after_position(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*, state: CssParserParseBackgroundValueState*) -> bool:
    # Attempt to parse `/ <background-size>`
    var background_size_transaction = css_syntax.token_stream_begin_transaction(tokens)
    defer css_syntax.state_transaction_destroy(&background_size_transaction)
    css_syntax.token_stream_discard_whitespace(tokens)
    let maybe_slash = css_syntax.token_stream_consume_a_token(tokens)
    if css_syntax.component_value_is_delim(&maybe_slash, (u32)'/'):
        css_syntax.token_stream_discard_whitespace(tokens)
        if let maybe_background_size = css_parser_parse_single_background_size_value(this, css_data.PropertyId.background_size, tokens):
            css_syntax.state_transaction_commit(&background_size_transaction)
            state.background_size = maybe_background_size
            css_syntax.token_stream_discard_whitespace(tokens)
            return true
        return false
    css_syntax.token_stream_discard_whitespace(tokens)
    return true

## Ported from Libraries/LibWeb/CSS/Parser/PropertyParsing.cpp:1122 Web::CSS::Parser::Parser::parse_background_value.
pub func css_parser_parse_background_value(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssStyleValue*?:
    var transaction = css_syntax.token_stream_begin_transaction(tokens)
    defer css_syntax.state_transaction_destroy(&transaction)

    # NB: The `make_background_shorthand`, `background_layer_is_valid` and `complete_background_layer` lambdas are
    #     css_make_background_shorthand, css_background_layer_is_valid and css_complete_background_layer, over the
    #     locals they capture (CssParserParseBackgroundValueState).
    var state = CssParserParseBackgroundValueState()

    state.initial_background_image = css_first_initial_value(css_data.PropertyId.background_image)
    state.initial_background_position_x = css_first_initial_value(css_data.PropertyId.background_position_x)
    state.initial_background_position_y = css_first_initial_value(css_data.PropertyId.background_position_y)
    state.initial_background_size = css_first_initial_value(css_data.PropertyId.background_size)
    state.initial_background_repeat = css_first_initial_value(css_data.PropertyId.background_repeat)
    state.initial_background_attachment = css_first_initial_value(css_data.PropertyId.background_attachment)
    state.initial_background_clip = css_first_initial_value(css_data.PropertyId.background_clip)
    state.initial_background_origin = css_first_initial_value(css_data.PropertyId.background_origin)
    let initial_background_color = css_property_initial_value(css_data.PropertyId.background_color)

    # BackgroundSize is always parsed as part of BackgroundPosition, so we don't include it here.
    ak.vector_ensure_capacity(&state.remaining_layer_properties, 7)
    css_set_background_layer_properties(&state.remaining_layer_properties)

    css_syntax.token_stream_discard_whitespace(tokens)
    while css_syntax.token_stream_has_next_token(tokens):
        if css_next_token_is(tokens, .comma):
            if not css_background_layer_is_valid(&state, false):
                return none
            css_complete_background_layer(&state)
            css_syntax.token_stream_discard_a_token(tokens)
            css_syntax.token_stream_discard_whitespace(tokens)
            continue

        let property_and_value = css_parser_parse_background_layer_property(this, tokens, &state.remaining_layer_properties) else return none
        let property = property_and_value.property
        let value = property_and_value.style_value
        css_remove_property(&state.remaining_layer_properties, property)

        match property:
            .background_attachment:
                assert(state.background_attachment == none)
                state.background_attachment = value else trap("release_nonnull")
                css_syntax.token_stream_discard_whitespace(tokens)
                continue
            .background_color:
                assert(state.background_color == none)
                state.background_color = value else trap("release_nonnull")
                css_syntax.token_stream_discard_whitespace(tokens)
                continue
            .background_image:
                assert(state.background_image == none)
                state.background_image = value else trap("release_nonnull")
                css_syntax.token_stream_discard_whitespace(tokens)
                continue
            .background_clip, .background_origin:
                # background-origin and background-clip accept the same values. From the spec:
                #   "If one <box> value is present then it sets both background-origin and background-clip to that value.
                #    If two values are present, then the first sets background-origin and the second background-clip."
                #        - https://www.w3.org/TR/css-backgrounds-3/#background
                # So, we put the first one in background-origin, then if we get a second, we put it in background-clip.
                # If we only get one, we copy the value before creating the ShorthandStyleValue.
                if state.background_origin == none:
                    state.background_origin = value else trap("release_nonnull")
                elif state.background_clip == none:
                    state.background_clip = value else trap("release_nonnull")
                else:
                    trap("VERIFY_NOT_REACHED")
                css_syntax.token_stream_discard_whitespace(tokens)
                continue
            .background_position:
                assert(state.background_position_x == none and state.background_position_y == none)
                let position = value else trap("release_nonnull")
                state.background_position_x = css_position_style_value_edge_x(css_style_value_as_position(position)).css_style_value()
                state.background_position_y = css_position_style_value_edge_y(css_style_value_as_position(position)).css_style_value()

                if not css_parser_parse_background_size_after_position(this, tokens, &state):
                    return none
                continue
            .background_repeat:
                assert(state.background_repeat == none)
                # NB: The tokens for this didn't get consumed, see above. So we parse it fully now.
                if let maybe_repeat = css_parser_parse_single_repeat_style_value(this, property, tokens):
                    state.background_repeat = maybe_repeat
                    css_syntax.token_stream_discard_whitespace(tokens)
                    continue
                return none
            _:
                trap("VERIFY_NOT_REACHED")

    if not css_background_layer_is_valid(&state, true):
        return none

    css_complete_background_layer(&state)

    if state.background_color == none:
        state.background_color = initial_background_color
    css_syntax.state_transaction_commit(&transaction)
    return css_make_background_shorthand(
        state.background_color else trap("release_nonnull"),
        css_style_value_list_of(state.background_images, CssStyleValueListSeparator.comma),
        css_shorthand_of(css_data.PropertyId.background_position,
                         css_property_ids_of([css_data.PropertyId.background_position_x, css_data.PropertyId.background_position_y]),
                         css_style_values_of([css_style_value_list_of(state.background_position_xs, CssStyleValueListSeparator.comma),
                                              css_style_value_list_of(state.background_position_ys, CssStyleValueListSeparator.comma)])),
        css_style_value_list_of(state.background_sizes, CssStyleValueListSeparator.comma),
        css_style_value_list_of(state.background_repeats, CssStyleValueListSeparator.comma),
        css_style_value_list_of(state.background_attachments, CssStyleValueListSeparator.comma),
        css_style_value_list_of(state.background_origins, CssStyleValueListSeparator.comma),
        css_style_value_list_of(state.background_clips, CssStyleValueListSeparator.comma))

# mark: background-position-x/y and background-size =============================================

## Ported from Libraries/LibWeb/CSS/Parser/PropertyParsing.cpp:1341 Web::CSS::Parser::Parser::parse_single_background_position_x_or_y_value.
pub func css_parser_parse_single_background_position_x_or_y_value(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*, property: css_data.PropertyId) -> CssStyleValue*?:
    var relative_edge: css_data.PositionEdge? = none

    var transaction = css_syntax.token_stream_begin_transaction(tokens)
    defer css_syntax.state_transaction_destroy(&transaction)
    if not css_syntax.token_stream_has_next_token(tokens):
        return none

    var value = css_parser_parse_css_value_for_property(this, property, tokens)
    let parsed_value = value else return none

    if css_style_value_is_keyword(parsed_value):
        let keyword = css_style_value_to_keyword(parsed_value)
        if keyword == css_data.Keyword.center:
            css_syntax.state_transaction_commit(&transaction)
            return css_edge_style_value_create(css_data.PositionEdge.center, none).css_style_value()
        if let edge = css_data.keyword_to_position_edge(keyword):
            relative_edge = edge
        else:
            return none

        value = css_parser_parse_length_percentage_value(this, tokens, css_infinite_range, css_infinite_range)
        if value == none:
            css_syntax.state_transaction_commit(&transaction)
            return css_edge_style_value_create(relative_edge, none).css_style_value()

    css_syntax.state_transaction_commit(&transaction)
    return css_edge_style_value_create(relative_edge, value).css_style_value()

## Ported from Libraries/LibWeb/CSS/Parser/PropertyParsing.cpp:1376 Web::CSS::Parser::Parser::parse_single_background_size_value.
pub func css_parser_parse_single_background_size_value(this: CssParser*, property: css_data.PropertyId, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssStyleValue*?:
    var transaction = css_syntax.token_stream_begin_transaction(tokens)
    defer css_syntax.state_transaction_destroy(&transaction)

    let maybe_x_value = css_parser_parse_css_value_for_property(this, property, tokens) else return none

    if css_style_value_to_keyword(maybe_x_value) == css_data.Keyword.cover or css_style_value_to_keyword(maybe_x_value) == css_data.Keyword.contain:
        css_syntax.state_transaction_commit(&transaction)
        return maybe_x_value

    if let maybe_y_value = css_parser_parse_css_value_for_property(this, property, tokens):
        css_syntax.state_transaction_commit(&transaction)
        return css_background_size_style_value_create(maybe_x_value, maybe_y_value).css_style_value()

    css_syntax.state_transaction_commit(&transaction)
    return css_background_size_style_value_create(maybe_x_value, css_keyword_value_of(css_data.Keyword.auto)).css_style_value()

# mark: border ==================================================================================

## The `make_single_value_shorthand` lambda of parse_border_value: a shorthand whose longhands all have `value`.
func css_make_single_value_shorthand(property_id: css_data.PropertyId, longhands: ak.Vector[css_data.PropertyId], value: CssStyleValue*) -> CssStyleValue*:
    var longhand_values = ak.Vector[CssStyleValue*]()
    ak.vector_resize_with_default_value(&longhand_values, ak.vector_size(&longhands), value)

    return css_shorthand_of(property_id, longhands, longhand_values)

## Ported from Libraries/LibWeb/CSS/Parser/PropertyParsing.cpp:1400 Web::CSS::Parser::Parser::parse_border_value.
# https://drafts.csswg.org/css-backgrounds-3/#propdef-border
pub func css_parser_parse_border_value(this: CssParser*, property_id: css_data.PropertyId, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssStyleValue*?:
    var border_width: CssStyleValue*? = none
    var border_color: CssStyleValue*? = none
    var border_style: CssStyleValue*? = none

    var color_property = css_data.PropertyId.border_color
    var style_property = css_data.PropertyId.border_style
    var width_property = css_data.PropertyId.border_width

    if property_id == css_data.PropertyId.border:
        # Already set above.
        assert(color_property == css_data.PropertyId.border_color)
    elif property_id == css_data.PropertyId.border_block:
        color_property = css_data.PropertyId.border_block_color
        style_property = css_data.PropertyId.border_block_style
        width_property = css_data.PropertyId.border_block_width
    elif property_id == css_data.PropertyId.border_inline:
        color_property = css_data.PropertyId.border_inline_color
        style_property = css_data.PropertyId.border_inline_style
        width_property = css_data.PropertyId.border_inline_width
    else:
        trap("VERIFY_NOT_REACHED")

    # NB: The `make_single_value_shorthand` lambda is css_make_single_value_shorthand.

    var remaining_longhands = css_property_ids_of([width_property, color_property, style_property])
    var transaction = css_syntax.token_stream_begin_transaction(tokens)
    defer css_syntax.state_transaction_destroy(&transaction)

    while css_syntax.token_stream_has_next_token(tokens):
        let property_and_value = css_parser_parse_css_value_for_properties(this, ak.vector_span_const(&remaining_longhands), tokens) else return none
        let value = property_and_value.style_value else trap("release_nonnull")
        css_remove_property(&remaining_longhands, property_and_value.property)

        if property_and_value.property == width_property:
            assert(border_width == none)
            border_width = css_make_single_value_shorthand(width_property, css_data.longhands_for_shorthand(width_property), value)
        elif property_and_value.property == color_property:
            assert(border_color == none)
            border_color = css_make_single_value_shorthand(color_property, css_data.longhands_for_shorthand(color_property), value)
        elif property_and_value.property == style_property:
            assert(border_style == none)
            border_style = css_make_single_value_shorthand(style_property, css_data.longhands_for_shorthand(style_property), value)
        else:
            trap("VERIFY_NOT_REACHED")

    if border_width == none:
        border_width = css_property_initial_value(width_property)
    if border_style == none:
        border_style = css_property_initial_value(style_property)
    if border_color == none:
        border_color = css_property_initial_value(color_property)

    css_syntax.state_transaction_commit(&transaction)

    let width = border_width else trap("release_nonnull")
    let style = border_style else trap("release_nonnull")
    let color = border_color else trap("release_nonnull")
    if property_id == css_data.PropertyId.border_block or property_id == css_data.PropertyId.border_inline:
        return css_shorthand_of(property_id, css_property_ids_of([width_property, style_property, color_property]), css_style_values_of([width, style, color]))

    # The border shorthand also resets border-image to its initial value
    return css_shorthand_of(property_id, css_property_ids_of([width_property, style_property, color_property, css_data.PropertyId.border_image]),
                            css_style_values_of([width, style, color, css_property_initial_value(css_data.PropertyId.border_image)]))