dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / src / web / css / parser / parser_4.lucb
#==============================================================================================
#
# parser_4 - the CSS parser: validity in the current context, declarations to style
# properties, value contexts, sizes="", substitution functions and accessors
#
# DESCRIPTION:
# Port of LibWeb/CSS/Parser/Parser.cpp (lines 1630-2253) and the inline member
# push_temporary_value_parsing_context of Parser.h (lines 630-641).
#
# Copyright (c) 2018-2024, Andreas Kling <andreas@ladybird.org>
# Copyright (c) 2021-2026, Sam Atkins <sam@ladybird.org>
# Copyright (c) 2024, Shannon Booth <shannon@serenityos.org>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: Valid in the current context ============================================================
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1630 Web::CSS::Parser::Parser::is_valid_in_the_current_context(Declaration const&).
pub func css_parser_is_valid_in_the_current_context_declaration(this: const CssParser*, declaration: const css_syntax.Declaration*) -> bool:
# TODO: Determine if this *particular* declaration is valid here, not just declarations in general.
# Declarations can't appear at the top level
if ak.vector_is_empty(&this.m_rule_context):
return false
match *ak.vector_last_const(&this.m_rule_context):
.unknown:
# If the context is an unknown type, we don't accept anything.
return false
.style:
# Style rules contain property declarations
return true
.keyframe:
# https://drafts.csswg.org/css-animations-1/#keyframes
# The <declaration-list> inside of <keyframe-block> accepts any CSS property except those defined in this
# specification, but does accept the animation-timing-function property and interprets it specially
# NB: animation-composition is defined in CSS Animations Level 2, so it is not excluded by this rule.
let property = css_property_name_and_id_from_name(declaration.name) else return true
match css_property_name_and_id_id(&property):
.animation, .animation_delay, .animation_direction, .animation_duration, .animation_fill_mode, .animation_iteration_count, .animation_name, .animation_play_state, .animation_timeline:
return false
_:
return true
.at_container, .at_layer, .at_media, .at_supports:
# Grouping rules can contain declarations if they are themselves inside a style or function rule
for context in ak.vector_span_const(&this.m_rule_context):
if context == CssRuleContext.style or context == CssRuleContext.at_function:
return true
return false
.font_feature_value:
# Each feature value block accepts a list of declarations
return true
.at_function:
# @function rules contain descriptor declarations
return true
.at_counter_style, .at_font_face, .at_font_feature_values, .at_page, .at_property, .margin:
# These have descriptor declarations
return true
.at_keyframes:
# @keyframes can only contain keyframe rules
return false
.supports_condition:
# @supports conditions accept all declarations
return true
_:
trap("VERIFY_NOT_REACHED")
## `first_is_one_of(name, ...)` of an at-rule name against literal names (FlyString's
## case-sensitive operator==(StringView)).
func css_fly_string_is_one_of(name: const ak.FlyString*, candidates: const str[]) -> bool:
for candidate in candidates:
if ak.fly_string_eq_string_view(name, ak.sv(candidate)):
return true
return false
## `m_rule_context.contains_slow(context)`.
func css_parser_rule_context_contains(this: const CssParser*, context: CssRuleContext) -> bool:
for entry in ak.vector_span_const(&this.m_rule_context):
if entry == context:
return true
return false
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1707 Web::CSS::Parser::Parser::is_valid_in_the_current_context(AtRule const&).
pub func css_parser_is_valid_in_the_current_context_at_rule(this: const CssParser*, at_rule: const css_syntax.AtRule*) -> bool:
# All at-rules can appear at the top level, except margin rules
if ak.vector_is_empty(&this.m_rule_context):
return not css_is_margin_rule_name(ak.fly_string_bytes_as_string_view(&at_rule.name))
# Only grouping rules can be nested within style rules
if css_parser_rule_context_contains(this, CssRuleContext.style):
return css_fly_string_is_one_of(&at_rule.name, ["container", "layer", "media", "supports"])
if css_parser_rule_context_contains(this, CssRuleContext.at_function):
# https://drafts.csswg.org/css-mixins-1/#function-body
# The body of a @function rule accepts conditional group rules
return css_fly_string_is_one_of(&at_rule.name, ["container", "media", "supports"])
match *ak.vector_last_const(&this.m_rule_context):
.unknown:
# If the context is an unknown type, we don't accept anything.
return false
.style:
# Already handled above
trap("VERIFY_NOT_REACHED")
.at_container, .at_layer, .at_media, .at_supports:
# Grouping rules can contain anything except @import or @namespace
return not css_fly_string_is_one_of(&at_rule.name, ["import", "namespace"])
.supports_condition:
# @supports cannot check for at-rules
return false
.at_page:
# @page rules can contain margin rules
return css_is_margin_rule_name(ak.fly_string_bytes_as_string_view(&at_rule.name))
.at_counter_style, .at_font_face, .font_feature_value, .at_keyframes, .keyframe, .at_property, .margin:
# These can't contain any at-rules
return false
.at_font_feature_values:
return css_font_feature_values_rule_is_font_feature_value_type_at_keyword(at_rule.name)
.at_function:
# Already handled above
trap("VERIFY_NOT_REACHED")
_:
trap("VERIFY_NOT_REACHED")
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1766 Web::CSS::Parser::Parser::is_valid_in_the_current_context(QualifiedRule const&).
pub func css_parser_is_valid_in_the_current_context_qualified_rule(this: const CssParser*, qualified_rule: const css_syntax.QualifiedRule*) -> bool:
_ = qualified_rule
# TODO: Different places accept different kinds of qualified rules. How do we tell them apart? Can we?
# Top level can contain style rules
if ak.vector_is_empty(&this.m_rule_context):
return true
match *ak.vector_last_const(&this.m_rule_context):
.unknown:
# If the context is an unknown type, we don't accept anything.
return false
.style:
# Style rules can contain style rules
return true
.at_container, .at_layer, .at_media, .at_supports:
# Grouping rules can contain style rules
return true
.at_keyframes:
# @keyframes can contain keyframe rules
return true
.supports_condition:
# @supports cannot check qualified rules
return false
.at_counter_style, .at_font_face, .at_font_feature_values, .font_feature_value, .at_function, .at_page, .at_property, .keyframe, .margin:
# These can't contain qualified rules
return false
_:
trap("VERIFY_NOT_REACHED")
# mark: Declarations to style properties ========================================================
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1814 Web::CSS::Parser::Parser::extract_property.
pub func css_parser_extract_property(this: CssParser*, declaration: const css_syntax.Declaration*, dest: CssParserPropertiesAndCustomProperties*):
if let property_and_name = css_parser_convert_to_style_property(this, declaration):
let property = property_and_name.property
if property.property_id == css_data.PropertyId.custom:
_ = ak.ordered_hash_map_set(&dest.custom_properties, property_and_name.name, property)
else:
ak.vector_append_t(&dest.properties, property)
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1826 Web::CSS::Parser::Parser::convert_to_style_declaration.
pub func css_parser_convert_to_style_declaration(this: CssParser*, declarations: const ak.Vector[css_syntax.Declaration]*) -> CssStyleProperties*:
var properties = CssParserPropertiesAndCustomProperties()
let dest = &properties
let list = ak.vector_span_const(declarations)
for declaration in &list:
css_parser_extract_property(this, declaration, dest)
return css_style_properties_create(css_parser_realm(this), properties.properties, properties.custom_properties)
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1836 Web::CSS::Parser::Parser::convert_to_style_property.
pub func css_parser_convert_to_style_property(this: CssParser*, declaration: const css_syntax.Declaration*) -> CssStylePropertyAndName?:
let maybe_property = css_property_name_and_id_from_name(declaration.name)
if maybe_property == none:
if css_parser_has_ignored_vendor_prefix(ak.fly_string_bytes_as_string_view(&declaration.name)):
return none
css_error_reporter_report(css_error_reporter_the(), CssParsingError.css_unknown_property_error(CssUnknownPropertyError(
rule_name = ak.fly_string_from_str("style"),
property_name = declaration.name,
)))
return none
let property = maybe_property else return none
var value_token_stream = css_syntax.token_stream_create(declaration.value)
let value = css_parser_parse_css_value(this, css_property_name_and_id_id(&property), &value_token_stream, declaration.original_value_text) catch failure:
if failure.code == css_parser_parse_error_syntax_error:
css_error_reporter_report(css_error_reporter_the(), CssParsingError.css_invalid_property_error(CssInvalidPropertyError(
rule_name = ak.fly_string_from_str("style"),
property_name = css_property_name_and_id_name(&property),
value_string = css_syntax.token_stream_dump_string(&value_token_stream),
description = ak.string_from_str("Failed to parse."),
)))
return none
if css_property_name_and_id_is_custom_property(&property):
return CssStylePropertyAndName(
property = CssStyleProperty(important = declaration.important, property_id = css_property_name_and_id_id(&property), value = value),
name = css_property_name_and_id_name(&property),
)
return CssStylePropertyAndName(
property = CssStyleProperty(important = declaration.important, property_id = css_property_name_and_id_id(&property), value = value),
name = ak.fly_string_new(),
)
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1872 Web::CSS::Parser::Parser::parse_source_size_value.
pub func css_parser_parse_source_size_value(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssStyleValue*?:
let next = css_syntax.token_stream_next_token(tokens)
if css_syntax.component_value_is_ident(&next, ak.sv("auto")):
css_syntax.token_stream_discard_a_token(tokens) # auto
return css_keyword_style_value_create(css_data.Keyword.auto).css_style_value()
# https://html.spec.whatwg.org/multipage/images.html#valid-source-size-list
# "A <source-size-value> that is a <length> must not be negative,
# and must not use CSS functions other than the math functions."
if let parsed = css_parser_parse_length_value(this, tokens, css_non_negative_range):
# FIXME: It seems odd that we disallow infinite calculated values here rather than clamping as we do for all
# other values - is this correct?
if css_style_value_is_calculated(parsed):
# https://drafts.csswg.org/css-values-4/#calc-range
# "the value resulting from a top-level calculation must be
# clamped to the range allowed in the target context."
let raw_length = css_calculated_style_value_resolve_raw_length(css_style_value_as_calculated(parsed), CssCalculationResolutionContext())
if let length = raw_length:
if not math.is_finite(length):
return none
return parsed
return none
# mark: Value contexts ==========================================================================
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1900 Web::CSS::Parser::Parser::context_allows_quirky_length.
pub func css_parser_context_allows_quirky_length(this: const CssParser*) -> bool:
if not css_parser_in_quirks_mode(this):
return false
# https://drafts.csswg.org/css-values-4/#deprecated-quirky-length
# "When CSS is being parsed in quirks mode, <quirky-length> is a type of <length> that is only valid in certain properties:"
# (NOTE: List skipped for brevity; quirks data is assigned in Properties.json)
# "It is not valid in properties that include or reference these properties, such as the background shorthand,
# or inside functional notations such as calc(), except that they must be allowed in rect() in the clip property."
# So, it must be allowed in the top-level ValueParsingContext, and then not disallowed by any child contexts.
var top_level_property: css_data.PropertyId? = none
if not ak.vector_is_empty(&this.m_value_context):
match *ak.vector_first_const(&this.m_value_context):
.property_id(property_id): top_level_property = property_id
_: top_level_property = none
var unitless_length_allowed = false
if let property_id = top_level_property:
unitless_length_allowed = css_data.property_has_quirk(property_id, css_data.Quirk.unitless_length)
var i: usize = 1
while i < ak.vector_size(&this.m_value_context) and unitless_length_allowed:
match *ak.vector_at_const(&this.m_value_context, i):
.property_id(property_id):
unitless_length_allowed = css_data.property_has_quirk(property_id, css_data.Quirk.unitless_length)
.css_function_context(function_context):
unitless_length_allowed = ak.string_view_equals(&function_context.name, "rect") and top_level_property == css_data.PropertyId.clip
_:
unitless_length_allowed = false
i += 1
return unitless_length_allowed
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1933 Web::CSS::Parser::Parser::context_allows_tree_counting_functions.
pub func css_parser_context_allows_tree_counting_functions(this: const CssParser*) -> bool:
for context in ak.vector_span_const(&this.m_value_context):
match context:
.css_descriptor_context(_):
return false
.css_special_context(special_context):
if (special_context == CssSpecialContext.canvas_context_generic_value or special_context == CssSpecialContext.dom_matrix_init_string or special_context == CssSpecialContext.media_condition):
return false
_:
_ = context
# TODO: Handle other contexts where tree counting functions are not allowed
return true
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1948 Web::CSS::Parser::Parser::context_allows_random_functions.
pub func css_parser_context_allows_random_functions(this: const CssParser*) -> bool:
match *ak.vector_first_const(&this.m_value_context):
.css_special_context(special_context):
if special_context == CssSpecialContext.canvas_context_generic_value or special_context == CssSpecialContext.on_screen_canvas_context_font_value:
return false
_:
_ = this
# For now we only allow random functions within property contexts, see https://drafts.csswg.org/css-values-5/#issue-cd071f29
# FIXME: Should this instead check that the top-level context is a property context (our current configuration
# allows these within DOMMatrixInitString for example)
for context in ak.vector_span_const(&this.m_value_context):
if css_value_parsing_context_has_property_id(&context):
return true
return false
## `context.has<PropertyID>()`.
func css_value_parsing_context_has_property_id(context: const CssValueParsingContext*) -> bool:
match *context:
.property_id(_): return true
_: return false
## The index of the first property context (`find_first_index_if(... has<PropertyID>() ...)`).
func css_parser_first_property_context_index(this: const CssParser*) -> usize?:
for i in 0..<ak.vector_size(&this.m_value_context):
if css_value_parsing_context_has_property_id(ak.vector_at_const(&this.m_value_context, i)):
return i
return none
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1959 Web::CSS::Parser::Parser::random_value_sharing_auto_name.
pub func css_parser_random_value_sharing_auto_name(this: const CssParser*) -> ak.FlyString:
let top_level_property_context_index = css_parser_first_property_context_index(this)
let property_id = match *ak.vector_at_const(&this.m_value_context, top_level_property_context_index else trap("VERIFY: a property context")):
.property_id(id) => id
_ => trap("VERIFY: Variant::get<PropertyID>")
let property_name = css_data.string_from_property_id(property_id)
return ak.fly_string_from_string(css_string_formatted("{} {}", [css_arg_fly_string(&property_name), ak.arg_u64((u64)this.m_random_function_index)]))
## Ported from Libraries/LibWeb/CSS/Parser/Parser.h:631 Web::CSS::Parser::Parser::push_temporary_value_parsing_context.
## The C++ returns a ScopeGuard that pops the context; callers `defer
## css_parser_pop_temporary_value_parsing_context(this)` right after pushing.
pub func css_parser_push_temporary_value_parsing_context(this: CssParser*, context: CssValueParsingContext):
ak.vector_append_t(&this.m_value_context, context)
## The ScopeGuard of push_temporary_value_parsing_context (Parser.h:635).
pub func css_parser_pop_temporary_value_parsing_context(this: CssParser*):
let removed_context = ak.vector_take_last(&this.m_value_context)
# Reset the random function index when we leave the top-level property parsing context
if css_value_parsing_context_has_property_id(&removed_context) and css_parser_first_property_context_index(this) == none:
this.m_random_function_index = 0
# mark: Parse as a value ========================================================================
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1968 Web::CSS::Parser::Parser::parse_as_list_of_component_values.
pub func css_parser_parse_as_list_of_component_values(this: CssParser*) -> ak.Vector[css_syntax.ComponentValue]:
return css_parser_parse_a_list_of_component_values(this, &this.m_token_stream)
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1973 Web::CSS::Parser::Parser::parse_as_css_value.
pub func css_parser_parse_as_css_value(this: CssParser*, property_id: css_data.PropertyId) -> CssStyleValue*?:
let component_values = css_parser_parse_a_list_of_component_values(this, &this.m_token_stream)
var tokens = css_syntax.token_stream_create(component_values)
let parsed_value = css_parser_parse_css_value(this, property_id, &tokens) catch: return none
return parsed_value
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1983 Web::CSS::Parser::Parser::parse_as_descriptor_value.
pub func css_parser_parse_as_descriptor_value(this: CssParser*, at_rule_id: css_data.AtRuleId, descriptor_name_and_id: CssDescriptorNameAndId) -> CssStyleValue*?:
let component_values = css_parser_parse_a_list_of_component_values(this, &this.m_token_stream)
var tokens = css_syntax.token_stream_create(component_values)
let parsed_value = css_parser_parse_descriptor_value(this, at_rule_id, descriptor_name_and_id, &tokens) catch: return none
return parsed_value
## Ported from Libraries/LibWeb/CSS/Parser/Parser.cpp:1993 Web::CSS::Parser::Parser::parse_as_type.
pub func css_parser_parse_as_type(this: CssParser*, value_type: CssValueType) -> CssStyleValue*?:
let component_values = css_parser_parse_a_list_of_component_values(this, &this.m_token_stream)
var tokens = css_syntax.token_stream_create(component_values)
return css_parser_parse_value(this, value_type, &tokens)