dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / src / web / css / parser / selector_parsing_1.lucb
#==============================================================================================
#
# selector_parsing_1 - parsing selectors: entry points, selector lists, complex and compound
# selectors, combinators, qualified names
#
# DESCRIPTION:
# Port of LibWeb/CSS/Parser/SelectorParsing.cpp (lines 1-388): next_is_pseudo_element,
# the parse_as_* entry points, create_invalid_selector, <selector-list> (the template
# over TokenStream<T>), <complex-selector>, <compound-selector>, combinators and
# <wq-name>.
#
# ParseErrorOr<T> is `T!` failing with the codes of parser_1
# (css_parser_parse_error_syntax_error, ..._includes_ignored_vendor_prefix).
#
# Copyright (c) 2018-2022, Andreas Kling <andreas@ladybird.org>
# Copyright (c) 2020-2021, the SerenityOS developers.
# Copyright (c) 2021-2025, Sam Atkins <sam@ladybird.org>
# Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
# Copyright (c) 2022, MacDue <macdue@dueutil.tech>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: Entry points ============================================================================
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:17 Web::CSS::Parser::next_is_pseudo_element.
func css_next_is_pseudo_element(tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> bool:
let first = css_syntax.token_stream_next_token(tokens)
let second = css_syntax.token_stream_peek_token(tokens, 1)
if css_syntax.component_value_is(&first, .colon):
# Pseudo-elements
if css_syntax.component_value_is(&second, .colon):
return true
# Legacy single-colon pseudo-elements
if css_syntax.component_value_is(&second, .ident):
let name = css_component_value_ident(&second)
if let pseudo_element = css_data.pseudo_element_from_string(ak.fly_string_bytes_as_string_view(&name)):
if css_is_legacy_single_colon_pseudo_element(pseudo_element):
return true
return false
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:37 Web::CSS::Parser::Parser::parse_as_selector.
pub func css_parser_parse_as_selector(this: CssParser*, parsing_mode: CssParserSelectorParsingMode = CssParserSelectorParsingMode.standard) -> ak.Vector[CssSelector*]?:
let selector_list: ak.Vector[CssSelector*]? = css_parser_parse_a_selector_list(this, &this.m_token_stream, CssParserSelectorType.standalone, parsing_mode) catch:
recover none
return selector_list
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:46 Web::CSS::Parser::Parser::parse_as_relative_selector.
pub func css_parser_parse_as_relative_selector(this: CssParser*, parsing_mode: CssParserSelectorParsingMode = CssParserSelectorParsingMode.standard) -> ak.Vector[CssSelector*]?:
let selector_list: ak.Vector[CssSelector*]? = css_parser_parse_a_selector_list(this, &this.m_token_stream, CssParserSelectorType.relative, parsing_mode) catch:
recover none
return selector_list
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:55 Web::CSS::Parser::Parser::parse_as_pseudo_element_selector.
pub func css_parser_parse_as_pseudo_element_selector(this: CssParser*) -> CssSelectorPseudoElementSelector?:
let component_values = css_parser_consume_a_list_of_component_values(this, &this.m_token_stream)
var tokens = css_syntax.token_stream_create(component_values)
let simple_selector = css_parser_parse_pseudo_element_simple_selector(this, &tokens) catch: return none
if css_syntax.token_stream_has_next_token(&tokens):
return none
if simple_selector.type_ != CssSelectorSimpleSelectorType.pseudo_element:
return none
return css_selector_simple_selector_pseudo_element(&simple_selector)
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:70 Web::CSS::Parser::create_invalid_selector.
func css_create_invalid_selector(combinator: CssSelectorCombinator, component_values: ak.Vector[css_syntax.ComponentValue]) -> CssSelector*:
var values = ak.vector_clone(&component_values) # by-value copy in C++
# Trim leading and trailing whitespace
while not ak.vector_is_empty(&values) and css_syntax.component_value_is(ak.vector_first(&values), .whitespace):
_ = ak.vector_take_first(&values)
while not ak.vector_is_empty(&values) and css_syntax.component_value_is(ak.vector_last(&values), .whitespace):
_ = ak.vector_take_last(&values)
let simple = CssSelectorSimpleSelector(
type_ = CssSelectorSimpleSelectorType.invalid,
value = CssSelectorSimpleSelectorValue.css_selector_simple_selector_invalid(CssSelectorSimpleSelectorInvalid(component_values = values)),
)
var simple_selectors = ak.Vector[CssSelectorSimpleSelector]()
ak.vector_append_t(&simple_selectors, simple)
let compound = CssSelectorCompoundSelector(combinator = combinator, simple_selectors = simple_selectors)
var compound_selectors = ak.Vector[CssSelectorCompoundSelector]()
ak.vector_append_t(&compound_selectors, compound)
return css_selector_create(compound_selectors)
# mark: <selector-list> and <complex-selector> ==================================================
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:94 Web::CSS::Parser::Parser::parse_a_selector_list.
pub func css_parser_parse_a_selector_list[T: css_syntax.TokenStreamToken[T]](this: CssParser*, tokens: css_syntax.TokenStream[T]*, mode: CssParserSelectorType, parsing_mode: CssParserSelectorParsingMode = CssParserSelectorParsingMode.standard) -> ak.Vector[CssSelector*]!:
var selectors = ak.Vector[CssSelector*]()
while true:
let selector_parts = css_parser_consume_a_list_of_component_values(this, tokens, css_syntax.TokenType.comma)
var stream = css_syntax.token_stream_create(selector_parts)
let maybe_selector: CssSelector*? = css_parser_parse_complex_selector(this, &stream, mode) catch failure:
if parsing_mode == CssParserSelectorParsingMode.forgiving:
# Keep the invalid selector around for serialization and nesting
var combinator = CssSelectorCombinator.descendant
if mode == CssParserSelectorType.standalone:
combinator = CssSelectorCombinator.none_
ak.vector_append_t(&selectors, css_create_invalid_selector(combinator, selector_parts))
recover none
error(failure.code, failure.message)
if let selector = maybe_selector:
ak.vector_append_t(&selectors, selector)
if css_syntax.token_stream_is_empty(tokens):
break
css_syntax.token_stream_discard_a_token(tokens)
if ak.vector_is_empty(&selectors) and parsing_mode != CssParserSelectorParsingMode.forgiving:
error(css_parser_parse_error_syntax_error, "")
return selectors
## `ErrorReporter::the().report(InvalidSelectorError { .value_string = ..., .description = ... })`
## with the error's default rule name, "style".
func css_report_invalid_selector(value_string: ak.String, description: ak.String):
css_error_reporter_report(css_error_reporter_the(), CssParsingError.css_invalid_selector_error(CssInvalidSelectorError(
rule_name = ak.fly_string_from_str("style"),
value_string = value_string,
description = description,
)))
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:127 Web::CSS::Parser::Parser::parse_complex_selector.
pub func css_parser_parse_complex_selector(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*, mode: CssParserSelectorType) -> CssSelector*!:
var compound_selectors = ak.Vector[CssSelectorCompoundSelector]()
var first_combinator = css_parser_parse_selector_combinator(this, tokens)
match mode:
.standalone:
# Standalone selectors can't start with a combinator.
# Whitespace, which gets parsed as a descendant combinator, is instead treated as None.
if first_combinator != none and first_combinator != CssSelectorCombinator.descendant:
css_report_invalid_selector(css_syntax.token_stream_dump_string(tokens),
ak.string_from_str("Standalone selector starts with a combinator, which is invalid."))
error(css_parser_parse_error_syntax_error, "")
first_combinator = CssSelectorCombinator.none_
.relative:
# Relative selectors default to starting with a descendant combinator.
if first_combinator == none:
first_combinator = CssSelectorCombinator.descendant
_:
trap("VERIFY_NOT_REACHED")
var first_selector = try css_parser_parse_compound_selector(this, tokens)
if ak.vector_is_empty(&first_selector.simple_selectors):
css_report_invalid_selector(css_syntax.token_stream_dump_string(tokens), ak.string_from_str("Failed to parse first compound-selector."))
error(css_parser_parse_error_syntax_error, "")
first_selector.combinator = first_combinator else CssSelectorCombinator.none_
ak.vector_append_t(&compound_selectors, first_selector)
while css_syntax.token_stream_has_next_token(tokens):
let combinator = css_parser_parse_selector_combinator(this, tokens) else break
var compound_selector = try css_parser_parse_compound_selector(this, tokens)
if ak.vector_is_empty(&compound_selector.simple_selectors):
if css_syntax.token_stream_has_next_token(tokens) or combinator != CssSelectorCombinator.descendant:
css_report_invalid_selector(css_syntax.token_stream_dump_string(tokens), ak.string_from_str("Compound-selector is empty."))
error(css_parser_parse_error_syntax_error, "")
break
compound_selector.combinator = combinator
ak.vector_append_t(&compound_selectors, compound_selector)
if ak.vector_is_empty(&compound_selectors):
css_report_invalid_selector(css_syntax.token_stream_dump_string(tokens), ak.string_from_str("Selector contains no compound-selectors."))
error(css_parser_parse_error_syntax_error, "")
if css_syntax.token_stream_has_next_token(tokens):
css_report_invalid_selector(css_syntax.token_stream_dump_string(tokens), ak.string_from_str("Not all tokens were consumed."))
error(css_parser_parse_error_syntax_error, "")
let parsed_selector = css_selector_create(compound_selectors)
let parsed_compound_selectors = css_selector_compound_selectors(parsed_selector)
# The rest of our code assumes selectors have at most 1 pseudo-element, in the final compound selector,
# so reject anything else for now.
# FIXME: Remove this once we support them elsewhere.
for i in 0..<ak.vector_size(&parsed_compound_selectors) - 1:
for simple_selector in ak.vector_span_const(&ak.vector_at_const(&parsed_compound_selectors, i).simple_selectors):
if simple_selector.type_ == CssSelectorSimpleSelectorType.pseudo_element:
css_report_invalid_selector(css_selector_serialize(parsed_selector),
ak.string_from_str("Pseudo elements before the final compound-selector are not yet supported."))
error(css_parser_parse_error_syntax_error, "")
# https://drafts.csswg.org/css-shadow-1/#selectordef-part
# The ::part() pseudo-element can be followed by other pseudo-elements to style pseudo-elements of the part itself.
var pseudo_element_count = 0
var first_pseudo_element: css_data.PseudoElement? = none
var second_pseudo_element: css_data.PseudoElement? = none
for simple_selector in ak.vector_span_const(&ak.vector_last_const(&parsed_compound_selectors).simple_selectors):
if simple_selector.type_ == CssSelectorSimpleSelectorType.pseudo_element:
pseudo_element_count += 1
let pseudo_element = css_selector_simple_selector_pseudo_element(&simple_selector)
if first_pseudo_element == none:
first_pseudo_element = css_selector_pseudo_element_selector_type(&pseudo_element)
elif second_pseudo_element == none:
second_pseudo_element = css_selector_pseudo_element_selector_type(&pseudo_element)
if pseudo_element_count > 1:
# FIXME: Other pseudo-elements can also be chained (e.g. ::highlight()::before).
# For now, only ::part() followed by one other pseudo-element is supported.
let is_valid_chain = ((first_pseudo_element else trap("VERIFY: a first pseudo-element")) == css_data.PseudoElement.part and (second_pseudo_element else trap("VERIFY: a second pseudo-element")) != css_data.PseudoElement.part and pseudo_element_count == 2)
if not is_valid_chain:
css_report_invalid_selector(css_selector_serialize(parsed_selector),
ak.string_from_str("Pseudo-element chaining is not yet supported for this combination."))
error(css_parser_parse_error_syntax_error, "")
return parsed_selector
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:250 Web::CSS::Parser::Parser::parse_compound_selector.
pub func css_parser_parse_compound_selector(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssSelectorCompoundSelector!:
var simple_selectors = ak.Vector[CssSelectorSimpleSelector]()
while css_syntax.token_stream_has_next_token(tokens):
let component = (try css_parser_parse_simple_selector(this, tokens)) else break
if component.type_ == CssSelectorSimpleSelectorType.tag_name and not ak.vector_is_empty(&simple_selectors):
css_report_invalid_selector(css_syntax.token_stream_dump_string(tokens),
ak.string_from_str("Tag-name selectors can only go at the beginning of a compound selector."))
error(css_parser_parse_error_syntax_error, "")
ak.vector_append_t(&simple_selectors, component)
return CssSelectorCompoundSelector(combinator = CssSelectorCombinator.none_, simple_selectors = simple_selectors)
# mark: Combinators and qualified names =========================================================
## The `consume_single_delim_combinator` lambda of parse_selector_combinator.
func css_parser_consume_single_delim_combinator(tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*, transaction: css_syntax.StateTransaction*, combinator: CssSelectorCombinator) -> CssSelectorCombinator:
css_syntax.token_stream_discard_a_token(tokens)
css_syntax.token_stream_discard_whitespace(tokens)
css_syntax.state_transaction_commit(transaction)
return combinator
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:271 Web::CSS::Parser::Parser::parse_selector_combinator.
pub func css_parser_parse_selector_combinator(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*) -> CssSelectorCombinator?:
_ = this
var transaction = css_syntax.token_stream_begin_transaction(tokens)
defer css_syntax.state_transaction_destroy(&transaction)
let first = css_syntax.token_stream_next_token(tokens)
let had_initial_whitespace = css_syntax.component_value_is(&first, .whitespace)
css_syntax.token_stream_discard_whitespace(tokens)
let next = css_syntax.token_stream_next_token(tokens)
if css_syntax.component_value_is_delim(&next, (u32)'>'):
return css_parser_consume_single_delim_combinator(tokens, &transaction, CssSelectorCombinator.immediate_child)
if css_syntax.component_value_is_delim(&next, (u32)'+'):
return css_parser_consume_single_delim_combinator(tokens, &transaction, CssSelectorCombinator.next_sibling)
if css_syntax.component_value_is_delim(&next, (u32)'~'):
return css_parser_consume_single_delim_combinator(tokens, &transaction, CssSelectorCombinator.subsequent_sibling)
let after_next = css_syntax.token_stream_peek_token(tokens, 1)
if css_syntax.component_value_is_delim(&next, (u32)'|') and css_syntax.component_value_is_delim(&after_next, (u32)'|'):
css_syntax.token_stream_discard_a_token(tokens) # |
css_syntax.token_stream_discard_a_token(tokens) # |
css_syntax.token_stream_discard_whitespace(tokens)
css_syntax.state_transaction_commit(&transaction)
return CssSelectorCombinator.column
if had_initial_whitespace:
css_syntax.state_transaction_commit(&transaction)
return CssSelectorCombinator.descendant
return none
## The `is_name` lambda of parse_selector_qualified_name.
func css_selector_qualified_name_is_name(token: const css_syntax.ComponentValue*) -> bool:
return css_syntax.component_value_is_delim(token, (u32)'*') or css_syntax.component_value_is(token, .ident)
## The `get_name` lambda of parse_selector_qualified_name.
func css_selector_qualified_name_get_name(token: const css_syntax.ComponentValue*) -> ak.FlyString:
if css_syntax.component_value_is_delim(token, (u32)'*'):
return ak.fly_string_from_str("*")
return css_component_value_ident(token)
## Ported from Libraries/LibWeb/CSS/Parser/SelectorParsing.cpp:311 Web::CSS::Parser::Parser::parse_selector_qualified_name.
pub func css_parser_parse_selector_qualified_name(this: CssParser*, tokens: css_syntax.TokenStream[css_syntax.ComponentValue]*, allow_wildcard_name: CssParserAllowWildcardName) -> CssSelectorSimpleSelectorQualifiedName?:
# There are 3 possibilities here:
# (Where <name> and <namespace> are either an <ident> or a `*` delim)
# 1) `|<name>`
# 2) `<namespace>|<name>`
# 3) `<name>`
# Whitespace is forbidden between any of these parts. https://www.w3.org/TR/selectors-4/#white-space
var transaction = css_syntax.token_stream_begin_transaction(tokens)
defer css_syntax.state_transaction_destroy(&transaction)
let first_token = css_syntax.token_stream_consume_a_token(tokens)
if css_syntax.component_value_is_delim(&first_token, (u32)'|'):
# Case 1: `|<name>`
let next = css_syntax.token_stream_next_token(tokens)
if css_selector_qualified_name_is_name(&next):
let name_token = css_syntax.token_stream_consume_a_token(tokens)
if allow_wildcard_name == CssParserAllowWildcardName.no and css_syntax.component_value_is_delim(&name_token, (u32)'*'):
return none
css_syntax.state_transaction_commit(&transaction)
return CssSelectorSimpleSelectorQualifiedName(
namespace_type = CssSelectorSimpleSelectorQualifiedNameNamespaceType.none_,
namespace_ = ak.fly_string_new(),
name = css_selector_simple_selector_name_create(css_selector_qualified_name_get_name(&name_token)),
)
return none
if not css_selector_qualified_name_is_name(&first_token):
return none
let next = css_syntax.token_stream_next_token(tokens)
let after_next = css_syntax.token_stream_peek_token(tokens, 1)
if css_syntax.component_value_is_delim(&next, (u32)'|') and css_selector_qualified_name_is_name(&after_next):
# Case 2: `<namespace>|<name>`
css_syntax.token_stream_discard_a_token(tokens) # `|`
let namespace_ = css_selector_qualified_name_get_name(&first_token)
let name_token = css_syntax.token_stream_consume_a_token(tokens)
let name = css_selector_qualified_name_get_name(&name_token)
if allow_wildcard_name == CssParserAllowWildcardName.no and ak.fly_string_eq_string_view(&name, ak.sv("*")):
return none
var namespace_type = CssSelectorSimpleSelectorQualifiedNameNamespaceType.named
if ak.fly_string_eq_string_view(&namespace_, ak.sv("*")):
namespace_type = CssSelectorSimpleSelectorQualifiedNameNamespaceType.any
# https://www.w3.org/TR/selectors-4/#invalid
# a simple selector containing an undeclared namespace prefix is invalid
if namespace_type == CssSelectorSimpleSelectorQualifiedNameNamespaceType.named and not ak.hash_table_contains_t(&this.m_declared_namespaces, namespace_):
return none
css_syntax.state_transaction_commit(&transaction)
return CssSelectorSimpleSelectorQualifiedName(
namespace_type = namespace_type,
namespace_ = namespace_,
name = css_selector_simple_selector_name_create(name),
)
# Case 3: `<name>`
let name_token = first_token
if allow_wildcard_name == CssParserAllowWildcardName.no and css_syntax.component_value_is_delim(&name_token, (u32)'*'):
return none
css_syntax.state_transaction_commit(&transaction)
return CssSelectorSimpleSelectorQualifiedName(
namespace_type = CssSelectorSimpleSelectorQualifiedNameNamespaceType.default_,
namespace_ = ak.fly_string_new(),
name = css_selector_simple_selector_name_create(css_selector_qualified_name_get_name(&name_token)),
)