dymokomi/luce-browser-engine
Source of release 0.6.0
0.6.0 / src / web / css / parser / arbitrary_substitution_functions_1.lucb
#==============================================================================================
#
# arbitrary_substitution_functions_1 - var(), attr(), env(), if() and inherit(): contexts
# and attr()
#
# DESCRIPTION:
# Port of LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp (lines 1-265) and its
# header: substitution contexts and their guards, the function names, and "replace an
# attr() function". Continued in arbitrary_substitution_functions_2.
#
# Copyright (c) 2025, Sam Atkins <sam@ladybird.org>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: SubstitutionContext =====================================================================
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:20 Web::CSS::Parser::SubstitutionContext::operator==.
pub func css_substitution_context_eq(this: const CssSubstitutionContext*, other: CssSubstitutionContext) -> bool:
return (this.dependency_type == other.dependency_type and ak.string_equals(&this.first, &other.first) and css_optional_strings_equal(this.second, other.second))
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:27 Web::CSS::Parser::SubstitutionContext::to_string.
pub func css_substitution_context_to_string(this: const CssSubstitutionContext*) -> ak.String:
let type_name = match this.dependency_type:
.property => "Property"
.attribute => "Attribute"
.function => "Function"
_ => trap("VERIFY_NOT_REACHED")
# AK formats an empty Optional as "None".
if let second = this.second:
return css_string_formatted("{} {} {}", [ak.arg_str(type_name), css_arg_string(&this.first), css_arg_string(&second)])
return css_string_formatted("{} {} {}", [ak.arg_str(type_name), css_arg_string(&this.first), ak.arg_str("None")])
# mark: GuardedSubstitutionContexts =============================================================
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:43 Web::CSS::Parser::GuardedSubstitutionContexts::guard.
pub func css_guarded_substitution_contexts_guard(this: CssGuardedSubstitutionContexts*, context: CssSubstitutionContext*):
for existing_context in ak.vector_span(&this.m_contexts):
if css_substitution_context_eq(existing_context, *context):
existing_context.is_cyclic = true
context.is_cyclic = true
return
ak.vector_append_t(&this.m_contexts, context)
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:56 Web::CSS::Parser::GuardedSubstitutionContexts::unguard.
pub func css_guarded_substitution_contexts_unguard(this: CssGuardedSubstitutionContexts*, context: CssSubstitutionContext):
# `m_contexts.remove_first_matching([context](auto const& other) { return context == other; })`
var was_removed = false
for index in 0..<ak.vector_size(&this.m_contexts):
if css_substitution_context_eq(&context, **ak.vector_at(&this.m_contexts, index)):
ak.vector_remove(&this.m_contexts, index)
was_removed = true
break
assert(was_removed)
# mark: Arbitrary substitution functions ========================================================
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:64 Web::CSS::Parser::to_arbitrary_substitution_function.
pub func css_to_arbitrary_substitution_function(name: ak.FlyString) -> CssArbitrarySubstitutionFunction?:
if ak.fly_string_equals_ignoring_ascii_case_string_view(&name, ak.sv("attr")):
return CssArbitrarySubstitutionFunction.attr
if ak.fly_string_equals_ignoring_ascii_case_string_view(&name, ak.sv("env")):
return CssArbitrarySubstitutionFunction.env
if ak.fly_string_equals_ignoring_ascii_case_string_view(&name, ak.sv("if")):
return CssArbitrarySubstitutionFunction.if_
if ak.fly_string_equals_ignoring_ascii_case_string_view(&name, ak.sv("inherit")):
return CssArbitrarySubstitutionFunction.inherit
if ak.fly_string_equals_ignoring_ascii_case_string_view(&name, ak.sv("var")):
return CssArbitrarySubstitutionFunction.var_
return none
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:79 Web::CSS::Parser::contains_guaranteed_invalid_value.
pub func css_contains_guaranteed_invalid_value(values: ak.Vector[css_syntax.ComponentValue]) -> bool:
for value in ak.vector_span_const(&values):
if css_syntax.component_value_contains_guaranteed_invalid_value(&value):
return true
return false
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:88 Web::CSS::Parser::contains_attr_tainted_value.
func css_contains_attr_tainted_value(values: ak.Vector[css_syntax.ComponentValue]) -> bool:
for value in ak.vector_span_const(&values):
if css_syntax.component_value_contains_attr_tainted_value(&value):
return true
return false
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:97 Web::CSS::Parser::mark_as_attr_tainted.
# The C++ takes the vector by value: the copy is marked, not the caller's.
func css_mark_as_attr_tainted(values: ak.Vector[css_syntax.ComponentValue]) -> ak.Vector[css_syntax.ComponentValue]:
var marked = ak.vector_clone(&values)
let marked_values = ak.vector_span(&marked)
for value in &marked_values:
css_syntax.component_value_set_attr_tainted(value)
return marked
## `{ ComponentValue { GuaranteedInvalidValue {} } }`: a list of one guaranteed-invalid value.
func css_guaranteed_invalid_component_values() -> ak.Vector[css_syntax.ComponentValue]:
var values = ak.Vector[css_syntax.ComponentValue]()
ak.vector_append_t(&values, css_syntax.component_value_from_guaranteed_invalid_value(css_syntax.GuaranteedInvalidValue()))
return values
## A list of one component value made from `token`.
func css_component_values_of_token(token: css_syntax.Token) -> ak.Vector[css_syntax.ComponentValue]:
var values = ak.Vector[css_syntax.ComponentValue]()
ak.vector_append_t(&values, css_syntax.component_value_from_token(token))
return values
## `arguments.get<DeclarationValueList>()`.
func css_arbitrary_substitution_function_arguments_declaration_value_list(arguments: CssArbitrarySubstitutionFunctionArguments) -> ak.Vector[ak.Vector[css_syntax.ComponentValue]]:
return match arguments:
.vector_vector_component_value(list) => list
_ => trap("VERIFY: the arguments are a DeclarationValueList")
## `declaration_value_list.get(1)`: the second <declaration-value>, if there was a comma.
func css_declaration_value_list_second(list: const ak.Vector[ak.Vector[css_syntax.ComponentValue]]*) -> ak.Vector[css_syntax.ComponentValue]?:
if let second = ak.vector_get_const(list, 1):
return *second
return none
# mark: replace an attr() function ==============================================================
## The `syntax` variable of replace_an_attr_function:
## `Variant<Empty, NonnullOwnPtr<SyntaxNode>, RawStringKeyword, NumberKeyword, AttrUnit>`.
enum CssReplaceAnAttrFunctionSyntax:
empty
syntax_node(node: CssSyntaxNode*)
raw_string_keyword
number_keyword
attr_unit(name: ak.FlyString)
## The `failure` lambda of replace_an_attr_function: step 7, FAILURE.
func css_replace_an_attr_function_failure(element: DomAbstractElement*, guarded_contexts: CssGuardedSubstitutionContexts*, second_argument: ak.Vector[css_syntax.ComponentValue]?,
syntax: CssReplaceAnAttrFunctionSyntax) -> ak.Vector[css_syntax.ComponentValue]:
# This is step 7, but defined here for convenience.
# 1. If second arg is null, and syntax was omitted, return an empty CSS <string>.
let syntax_is_empty = match syntax:
.empty => true
_ => false
if second_argument == none and syntax_is_empty:
return css_component_values_of_token(css_syntax.token_create_string(ak.fly_string_new(), ak.String()))
# 2. If second arg is null, return the guaranteed-invalid value.
let second = second_argument else return css_guaranteed_invalid_component_values()
# 3. Substitute arbitrary substitution functions in second arg, and return the result.
return css_substitute_arbitrary_substitution_functions(element, guarded_contexts, second)
## The `parse_as_number` lambda of replace_an_attr_function.
func css_replace_an_attr_function_parse_as_number(element: DomAbstractElement*, attribute_value: ak.String) -> CssNumberStyleValue*?:
var parsing_params: CssParsingParams = ---
css_parsing_params_construct_dom_document(&parsing_params, dom_node_document(dom_abstract_element_element(element).dom_node()))
var parser = css_parser_create(parsing_params, ak.string_bytes_as_string_view(&attribute_value))
let unsubstituted_values = css_parser_parse_as_list_of_component_values(&parser)
let syntax_node = css_type_syntax_node_create(ak.fly_string_from_str("number"))
var syntax_parsing_params: CssParsingParams = ---
css_parsing_params_construct_dom_document(&syntax_parsing_params, dom_abstract_element_document(element))
let parsed_value = css_parse_with_a_syntax(syntax_parsing_params, unsubstituted_values, syntax_node.css_syntax_node())
if css_style_value_is_guaranteed_invalid(parsed_value):
return none
# FIXME: The spec is ambiguous about what we should do for non-number-literals.
# Chromium treats them as invalid, so copy that for now.
# Spec issue: https://github.com/w3c/csswg-drafts/issues/12479
if not css_style_value_is_number(parsed_value):
return none
return css_style_value_as_number(parsed_value)
## The `syntax.visit(...)` of step 4 of replace_an_attr_function: a number, a dimension or a percentage parsed from the
## attribute's value when syntax is the number keyword or an <attr-unit> (setting `return_from_step_4`), none otherwise.
func css_replace_an_attr_function_step_4(element: DomAbstractElement*, attribute_value: ak.String, syntax: CssReplaceAnAttrFunctionSyntax,
return_from_step_4: bool*) -> ak.Vector[css_syntax.ComponentValue]?:
match syntax:
# https://drafts.csswg.org/css-values-5/#ref-for-typedef-attr-type%E2%91%A0
.number_keyword:
# If given as the number keyword, it causes the attribute’s literal value, after stripping leading and
# trailing whitespace, to be parsed as a <number-token>. Values that fail to parse trigger fallback.
*return_from_step_4 = true
let parsed_number = css_replace_an_attr_function_parse_as_number(element, attribute_value) else return none
return css_component_values_of_token(css_syntax.token_create_number(css_syntax.number_create(css_syntax.NumberType.number, css_number_style_value_number(parsed_number)), ak.String()))
.attr_unit(name):
# If given as an <attr-unit> value, the value is first parsed as if number keyword was specified, then the
# resulting numeric value is turned into a dimension with the corresponding unit, or a percentage if % was
# given. Same as for number <attr-type>, values that do not correspond to the <number-token> production
# trigger fallback.
*return_from_step_4 = true
let parsed_number = css_replace_an_attr_function_parse_as_number(element, attribute_value) else return none
let percent = ak.fly_string_from_str("%")
if ak.fly_string_eq_fly_string(&name, &percent):
return css_component_values_of_token(css_syntax.token_create_percentage(css_syntax.number_create(css_syntax.NumberType.number, css_number_style_value_number(parsed_number)), ak.String()))
return css_component_values_of_token(css_syntax.token_create_dimension_f64(css_number_style_value_number(parsed_number), name, ak.String()))
_:
return none
## Ported from Libraries/LibWeb/CSS/Parser/ArbitrarySubstitutionFunctions.cpp:105 Web::CSS::Parser::replace_an_attr_function.
# https://drafts.csswg.org/css-values-5/#replace-an-attr-function
func css_replace_an_attr_function(element: DomAbstractElement*, guarded_contexts: CssGuardedSubstitutionContexts*, arguments: CssArbitrarySubstitutionFunctionArguments) -> ak.Vector[css_syntax.ComponentValue]:
# 1. Let el be the element that the style containing the attr() function is being applied to.
# Let first arg be the first <declaration-value> in arguments.
# Let second arg be the <declaration-value>? passed after the comma, or null if there was no comma.
let declaration_value_list = css_arbitrary_substitution_function_arguments_declaration_value_list(arguments)
let first_argument = *ak.vector_first_const(&declaration_value_list)
let second_argument = css_declaration_value_list_second(&declaration_value_list)
var attribute_name = ak.fly_string_new()
var syntax = CssReplaceAnAttrFunctionSyntax.empty
# NB: The `failure` lambda (step 7) is css_replace_an_attr_function_failure.
# 2. Substitute arbitrary substitution functions in first arg, then parse it as <attr-name> <attr-type>?.
# If that returns failure, jump to the last step (labeled FAILURE).
# Otherwise, let attr name and syntax be the results of parsing (with syntax being null if <attr-type> was
# omitted), processed as specified in the definition of those arguments.
let substituted = css_substitute_arbitrary_substitution_functions(element, guarded_contexts, first_argument)
var first_argument_tokens = css_syntax.token_stream_create(substituted)
# <attr-name> = [ <ident-token>? '|' ]? <ident-token>
# FIXME: Support optional attribute namespace
let name_token = css_syntax.token_stream_next_token(&first_argument_tokens)
if not css_syntax.component_value_is(&name_token, .ident):
return css_replace_an_attr_function_failure(element, guarded_contexts, second_argument, syntax)
let consumed_name_token = css_syntax.token_stream_consume_a_token(&first_argument_tokens)
attribute_name = css_component_value_ident(&consumed_name_token)
css_syntax.token_stream_discard_whitespace(&first_argument_tokens)
# <attr-type> = type( <syntax> ) | raw-string | number | <attr-unit>
let next = css_syntax.token_stream_next_token(&first_argument_tokens)
if css_syntax.component_value_is(&next, .ident):
let syntax_ident = css_component_value_ident(&next)
if ak.fly_string_equals_ignoring_ascii_case_string_view(&syntax_ident, ak.sv("raw-string")):
css_syntax.token_stream_discard_a_token(&first_argument_tokens) # raw-string
syntax = CssReplaceAnAttrFunctionSyntax.raw_string_keyword
elif ak.fly_string_equals_ignoring_ascii_case_string_view(&syntax_ident, ak.sv("number")):
css_syntax.token_stream_discard_a_token(&first_argument_tokens) # number
syntax = CssReplaceAnAttrFunctionSyntax.number_keyword
elif css_data.dimension_for_unit(ak.fly_string_bytes_as_string_view(&syntax_ident)) != none:
let unit_token = css_syntax.token_stream_consume_a_token(&first_argument_tokens)
syntax = CssReplaceAnAttrFunctionSyntax.attr_unit(name = css_component_value_ident(&unit_token))
else:
return css_replace_an_attr_function_failure(element, guarded_contexts, second_argument, syntax)
elif css_syntax.component_value_is_delim(&next, (u32)'%'):
css_syntax.token_stream_discard_a_token(&first_argument_tokens) # %
syntax = CssReplaceAnAttrFunctionSyntax.attr_unit(name = ak.fly_string_from_str("%"))
elif css_syntax.component_value_is_function_string_view(&next, ak.sv("type")):
let type_token = css_syntax.token_stream_consume_a_token(&first_argument_tokens)
let type_function = css_syntax.component_value_function(&type_token)
if let parsed_syntax = css_parse_as_syntax(type_function.value):
syntax = CssReplaceAnAttrFunctionSyntax.syntax_node(node = parsed_syntax)
else:
return css_replace_an_attr_function_failure(element, guarded_contexts, second_argument, syntax)
css_syntax.token_stream_discard_whitespace(&first_argument_tokens)
if css_syntax.token_stream_has_next_token(&first_argument_tokens):
return css_replace_an_attr_function_failure(element, guarded_contexts, second_argument, syntax)
# 3. If attr name exists as an attribute on el, let attr value be its value; otherwise jump to the last step (labeled FAILURE).
# FIXME: Attribute namespaces
let attribute_value = dom_element_get_attribute(dom_abstract_element_element(element), attribute_name) else return css_replace_an_attr_function_failure(element, guarded_contexts, second_argument, syntax)
# 4. If syntax is the keyword number or an <attr-unit> value, parse attr value against <attr-type>.
# If that succeeds, return the result; otherwise, jump to the last step (labeled FAILURE).
# NOTE: No parsing or modification of any kind is performed on the value.
var return_from_step_4 = false
let step_4_result = css_replace_an_attr_function_step_4(element, attribute_value, syntax, &return_from_step_4)
if return_from_step_4:
if let result = step_4_result:
return css_mark_as_attr_tainted(result)
return css_replace_an_attr_function_failure(element, guarded_contexts, second_argument, syntax)
# 5. If syntax is null or the keyword raw-string, return a CSS <string> whose value is attr value.
# NOTE: No parsing or modification of any kind is performed on the value.
let is_null_or_raw_string = match syntax:
.empty, .raw_string_keyword => true
_ => false
if is_null_or_raw_string:
return css_mark_as_attr_tainted(css_component_values_of_token(css_syntax.token_create_string(ak.fly_string_from_string(attribute_value), ak.String())))
# 6. Substitute arbitrary substitution functions in attr value, with «"attribute", attr name» as the substitution
# context, then parse with a <syntax> attr value, with syntax and el. If that succeeds, return the result;
# otherwise, jump to the last step (labeled FAILURE).
var parsing_params: CssParsingParams = ---
css_parsing_params_construct_dom_document(&parsing_params, dom_node_document(dom_abstract_element_element(element).dom_node()))
var parser = css_parser_create(parsing_params, ak.string_bytes_as_string_view(&attribute_value))
let unsubstituted_values = css_parser_parse_as_list_of_component_values(&parser)
let substituted_values = css_substitute_arbitrary_substitution_functions(element, guarded_contexts, unsubstituted_values,
CssSubstitutionContext(dependency_type = CssSubstitutionContextDependencyType.attribute, first = ak.fly_string_to_string_const(&attribute_name)))
let syntax_node = match syntax:
.syntax_node(node) => node
_ => trap("VERIFY: syntax is a SyntaxNode")
var syntax_parsing_params: CssParsingParams = ---
css_parsing_params_construct_dom_document(&syntax_parsing_params, dom_abstract_element_document(element))
let parsed_value = css_parse_with_a_syntax(syntax_parsing_params, substituted_values, syntax_node)
if css_style_value_is_guaranteed_invalid(parsed_value):
return css_replace_an_attr_function_failure(element, guarded_contexts, second_argument, syntax)
return css_mark_as_attr_tainted(css_style_value_tokenize(parsed_value))
# 7. FAILURE:
# NB: Step 7 is a lambda defined at the top of the function.