Skip to content

Truly independent web browser

LibWeb: Parse selectors from token rows and not component values

Andreas Kling372cef14e215
diff --git a/Libraries/LibWeb/Rust/src/css/parser/lexer.rs b/Libraries/LibWeb/Rust/src/css/parser/lexer.rs
index 38515caa7f3..1844dd11288 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/lexer.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/lexer.rs
@@ -17,6 +17,7 @@
use super::block::{BLOCK, Unit, eq_mask, ident_mask};
use crate::css::css_tokenizer::TokenizerInput;
+use std::ops::Range;
/// The code of the units past the end of the source.
const END: u32 = u32::MAX;
@@ -652,21 +653,27 @@ pub(crate) fn name_of<U: Unit>(units: &[U], token: Token) -> Text<'_> {
Text::Unescaped(output)
}
-/// The value of `token`, which is a string.
-pub(crate) fn string_of<U: Unit>(units: &[U], token: Token) -> Text<'_> {
+/// Where the value of `token`, which is a string, is in `units`, and the escapes to remove from it, if it has any.
+pub(crate) fn string_range<U: Unit>(units: &[U], token: Token) -> (Range<usize>, Option<Escapes>) {
debug_assert_eq!(token.kind, Kind::String);
let (start, end) = (token.start as usize, token.end as usize);
- if !token.has(flag::ESCAPED) {
- // NB: Without escapes, the string is closed if it ends in its quote, which is then not the quote it opens with.
- let closed = end - start >= 2 && units[end - 1] == units[start];
- return Text::Source(U::input(&units[start + 1..end - usize::from(closed)]));
+ if token.has(flag::ESCAPED) {
+ return (start + 1..end, Some(Escapes::String(units[start].code())));
}
- let mut output = Vec::with_capacity(end - start);
- unescape(
- &units[start + 1..end],
- Escapes::String(units[start].code()),
- &mut output,
- );
+ // NB: Without escapes, the string is closed if it ends in its quote, which is then not the quote it opens with.
+ let closed = end - start >= 2 && units[end - 1] == units[start];
+ (start + 1..end - usize::from(closed), None)
+}
+
+/// The value of `token`, which is a string.
+pub(crate) fn string_of<U: Unit>(units: &[U], token: Token) -> Text<'_> {
+ let (range, escapes) = string_range(units, token);
+ let units = &units[range];
+ let Some(escapes) = escapes else {
+ return Text::Source(U::input(units));
+ };
+ let mut output = Vec::with_capacity(units.len());
+ unescape(units, escapes, &mut output);
Text::Unescaped(output)
}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/mod.rs b/Libraries/LibWeb/Rust/src/css/parser/mod.rs
index 0bdfe67c76b..c0db6fe226f 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/mod.rs
@@ -18,6 +18,7 @@ pub(crate) mod lexer;
mod memory_tests;
pub(crate) mod positions_shapes_parser;
pub(crate) mod query_parser;
+pub(crate) mod rows;
pub(crate) mod sheet_source_text;
mod stylesheet_cache;
pub(crate) mod syntax;
diff --git a/Libraries/LibWeb/Rust/src/css/parser/rows.rs b/Libraries/LibWeb/Rust/src/css/parser/rows.rs
new file mode 100644
index 00000000000..98f2f7d0e8c
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/parser/rows.rs
@@ -0,0 +1,563 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The tokens of a piece of source as rows of a buffer, and views of them as component values. A grammar reads the
+//! views, and no component value is made: a function or a block is the rows from its first token to the token that
+//! closes it, which the first token names.
+//!
+//! The buffer is scratch memory. Whoever parses many pieces of source fills the same buffer for each.
+
+use super::block::Unit;
+use super::component_value::MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH;
+use super::lexer::{Escapes, Kind, Lexer, Token, flag, number_of, string_range, unescape};
+use crate::css::css_tokenizer::TokenizerInput;
+use smallvec::SmallVec;
+use std::ops::Range;
+
+/// The text of a name or a string, as UTF-16.
+pub(crate) type Name = SmallVec<[u16; 60]>;
+
+/// The token that ends the block or function that a token of `kind` starts.
+#[inline]
+pub(crate) fn closer_of(kind: Kind) -> Option<Kind> {
+ match kind {
+ Kind::Function | Kind::OpenParen => Some(Kind::CloseParen),
+ Kind::OpenSquare => Some(Kind::CloseSquare),
+ Kind::OpenCurly => Some(Kind::CloseCurly),
+ _ => None,
+ }
+}
+
+#[derive(Default)]
+pub(crate) struct Rows {
+ /// The tokens, and after them one end-of-file token, which says whether whitespace or a comment ends the source.
+ /// The `part` of a token that starts a function or a block is the row of the token that closes it, or the row of
+ /// the end-of-file token if nothing closes it.
+ tokens: Vec<Token>,
+ open: Vec<u32>,
+}
+
+impl Rows {
+ /// Fills the rows with the tokens in `range` of `units`, which are preprocessed text. Fails if the functions and
+ /// blocks are nested too deep.
+ pub(crate) fn fill<U: Unit>(&mut self, units: &[U], range: Range<usize>) -> Result<(), ()> {
+ self.tokens.clear();
+ self.open.clear();
+ let mut lexer = Lexer::new(units);
+ lexer.set_position(range.start);
+ loop {
+ let mut token = lexer.next();
+ let row = self.tokens.len() as u32;
+ if token.kind == Kind::EndOfFile || token.start as usize >= range.end {
+ // NB: Whitespace and comments before the end of the range are before the token that starts there.
+ let end = (token.start as usize).min(range.end) as u32;
+ token = Token {
+ start: end,
+ end,
+ part: 0,
+ kind: Kind::EndOfFile,
+ flags: token.flags & (flag::SPACE_BEFORE | flag::COMMENT_BEFORE),
+ };
+ self.tokens.push(token);
+ for &open in &self.open {
+ self.tokens[open as usize].part = row;
+ }
+ return Ok(());
+ }
+ if let Some(&open) = self.open.last()
+ && closer_of(self.tokens[open as usize].kind) == Some(token.kind)
+ {
+ self.open.pop();
+ self.tokens[open as usize].part = row;
+ } else if closer_of(token.kind).is_some() {
+ // NB: This is the depth at which a list of component values fails to parse.
+ if self.open.len() >= MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH {
+ return Err(());
+ }
+ self.open.push(row);
+ }
+ self.tokens.push(token);
+ }
+ }
+
+ /// Fills the rows with the tokens of `input`, which is preprocessed text.
+ pub(crate) fn fill_from(&mut self, input: TokenizerInput<'_>) -> Result<(), ()> {
+ match input {
+ TokenizerInput::Latin1(units) => self.fill(units, 0..units.len()),
+ TokenizerInput::Utf16(units) => self.fill(units, 0..units.len()),
+ }
+ }
+
+ /// The component values of the rows, which are tokens of `source`. With `skip_gap`, whitespace and comments before
+ /// the first token are not part of them.
+ pub(crate) fn values<'a>(&'a self, source: TokenizerInput<'a>, skip_gap: bool) -> Values<'a> {
+ Values {
+ tokens: &self.tokens,
+ source,
+ row: 0,
+ end: self.tokens.len() as u32 - 1,
+ gap_taken: skip_gap,
+ }
+ }
+}
+
+/// A list of component values, and a position in it.
+///
+/// Whitespace and comments are not rows. The list has one whitespace value wherever a row follows either, which is
+/// what a grammar can tell about them.
+#[derive(Clone, Copy)]
+pub(crate) struct Values<'a> {
+ tokens: &'a [Token],
+ source: TokenizerInput<'a>,
+ /// The row of the next value.
+ row: u32,
+ /// The row after the last value: the token that closes the list, or the end-of-file token.
+ end: u32,
+ /// Whether the whitespace before the next row is behind the position.
+ gap_taken: bool,
+}
+
+impl<'a> Values<'a> {
+ fn last_row(&self) -> u32 {
+ self.tokens.len() as u32 - 1
+ }
+
+ #[inline]
+ pub(crate) fn peek(&self) -> Option<Cv<'a>> {
+ let token = self.tokens[self.row as usize];
+ let is_whitespace = !self.gap_taken && token.follows_a_gap();
+ if self.row == self.end && !is_whitespace {
+ return None;
+ }
+ Some(Cv {
+ tokens: self.tokens,
+ source: self.source,
+ row: self.row,
+ is_whitespace,
+ })
+ }
+
+ /// The value after the next `offset` values.
+ pub(crate) fn peek_n(&self, offset: usize) -> Option<Cv<'a>> {
+ let mut values = *self;
+ for _ in 0..offset {
+ values.next()?;
+ }
+ values.peek()
+ }
+
+ #[inline]
+ #[allow(clippy::should_implement_trait)]
+ pub(crate) fn next(&mut self) -> Option<Cv<'a>> {
+ let value = self.peek()?;
+ if value.is_whitespace {
+ self.gap_taken = true;
+ return Some(value);
+ }
+ let token = self.tokens[self.row as usize];
+ if closer_of(token.kind).is_none() {
+ self.row += 1;
+ self.gap_taken = false;
+ } else if token.part == self.last_row() {
+ // NB: Nothing closes the value, so what ends the source is in it, and not after it.
+ self.row = token.part;
+ self.gap_taken = true;
+ } else {
+ self.row = token.part + 1;
+ self.gap_taken = false;
+ }
+ Some(value)
+ }
+
+ /// Goes past the next value.
+ #[inline]
+ pub(crate) fn skip(&mut self) {
+ self.next();
+ }
+
+ #[inline]
+ pub(crate) fn is_empty(&self) -> bool {
+ self.peek().is_none()
+ }
+
+ #[inline]
+ pub(crate) fn discard_whitespace(&mut self) {
+ self.gap_taken = true;
+ }
+
+ /// The values from the position up to the next comma, and goes past them and the comma. `None` once the list is
+ /// behind the position and no comma was the last value.
+ pub(crate) fn split_at_comma(&mut self, is_first: bool) -> Option<Values<'a>> {
+ if !is_first && self.row == self.end && self.gap_taken {
+ return None;
+ }
+ let mut rest = *self;
+ loop {
+ match rest.peek() {
+ Some(value) if value.is_comma() => {
+ let part = Values { end: rest.row, ..*self };
+ rest.skip();
+ *self = rest;
+ return Some(part);
+ }
+ Some(_) => rest.skip(),
+ None => {
+ let part = *self;
+ // NB: The position is the end of the list with nothing before it, which says that no part is left.
+ self.row = self.end;
+ self.gap_taken = true;
+ return if is_first || part.row != part.end || !part.gap_taken {
+ Some(part)
+ } else {
+ None
+ };
+ }
+ }
+ }
+ }
+
+ /// Where the values from the position on are in the source, without the whitespace before and after them.
+ pub(crate) fn source_range(&self) -> Range<usize> {
+ let mut values = *self;
+ values.discard_whitespace();
+ let start = self.tokens[values.row as usize].start as usize;
+ let mut end = start;
+ while let Some(value) = values.next() {
+ if !value.is_whitespace {
+ end = value.source_end();
+ }
+ }
+ start..end
+ }
+
+ /// The text of the source in `range`.
+ pub(crate) fn source_text(&self, range: Range<usize>) -> Vec<u16> {
+ let mut text = Vec::new();
+ self.source.slice(range).append_to(&mut text);
+ text
+ }
+}
+
+/// One component value of a list.
+#[derive(Clone, Copy)]
+pub(crate) struct Cv<'a> {
+ tokens: &'a [Token],
+ source: TokenizerInput<'a>,
+ row: u32,
+ is_whitespace: bool,
+}
+
+impl<'a> Cv<'a> {
+ #[inline]
+ fn token(&self) -> Token {
+ self.tokens[self.row as usize]
+ }
+
+ #[inline]
+ fn kind(&self) -> Option<Kind> {
+ (!self.is_whitespace).then(|| self.token().kind)
+ }
+
+ #[inline]
+ fn code_at(&self, index: usize) -> u32 {
+ u32::from(self.source.code_unit_at(index))
+ }
+
+ fn text(&self, range: (usize, usize), escapes: Option<Escapes>) -> Name {
+ let (start, end) = range;
+ match (self.source, escapes) {
+ (TokenizerInput::Latin1(units), None) => units[start..end].iter().map(|&unit| u16::from(unit)).collect(),
+ (TokenizerInput::Utf16(units), None) => SmallVec::from_slice(&units[start..end]),
+ (source, Some(escapes)) => {
+ let mut output = Vec::with_capacity(end - start);
+ match source {
+ TokenizerInput::Latin1(units) => unescape(&units[start..end], escapes, &mut output),
+ TokenizerInput::Utf16(units) => unescape(&units[start..end], escapes, &mut output),
+ }
+ SmallVec::from_vec(output)
+ }
+ }
+ }
+
+ fn name(&self) -> Name {
+ let token = self.token();
+ self.text(token.name_range(), token.has(flag::ESCAPED).then_some(Escapes::Name))
+ }
+
+ /// Where the value ends in the source.
+ fn source_end(&self) -> usize {
+ let token = self.token();
+ if closer_of(token.kind).is_none() {
+ return token.end as usize;
+ }
+ let closing = self.tokens[token.part as usize];
+ closing.end as usize
+ }
+
+ #[inline]
+ pub(crate) fn is_whitespace(&self) -> bool {
+ self.is_whitespace
+ }
+
+ #[inline]
+ pub(crate) fn is_comma(&self) -> bool {
+ self.kind() == Some(Kind::Comma)
+ }
+
+ #[inline]
+ pub(crate) fn is_colon(&self) -> bool {
+ self.kind() == Some(Kind::Colon)
+ }
+
+ #[inline]
+ pub(crate) fn is_delim(&self, expected: u8) -> bool {
+ self.kind() == Some(Kind::Delim) && self.code_at(self.token().start as usize) == u32::from(expected)
+ }
+
+ #[inline]
+ pub(crate) fn is_ident(&self) -> bool {
+ self.kind() == Some(Kind::Ident)
+ }
+
+ pub(crate) fn ident(&self) -> Option<Name> {
+ self.is_ident().then(|| self.name())
+ }
+
+ /// The value of a hash token that is a valid identifier.
+ pub(crate) fn id(&self) -> Option<Name> {
+ (self.kind() == Some(Kind::Hash) && self.token().has(flag::ID)).then(|| self.name())
+ }
+
+ pub(crate) fn string(&self) -> Option<Name> {
+ if self.kind() != Some(Kind::String) {
+ return None;
+ }
+ let token = self.token();
+ let (range, escapes) = match self.source {
+ TokenizerInput::Latin1(units) => string_range(units, token),
+ TokenizerInput::Utf16(units) => string_range(units, token),
+ };
+ Some(self.text((range.start, range.end), escapes))
+ }
+
+ /// The value of a number token, and whether it is written as an integer, and with a sign.
+ pub(crate) fn number(&self) -> Option<(f64, bool, bool)> {
+ (self.kind() == Some(Kind::Number)).then(|| self.numeric_value())
+ }
+
+ /// The value of a dimension token, whether it is written as an integer, and its unit.
+ pub(crate) fn dimension(&self) -> Option<(f64, bool, Name)> {
+ if self.kind() != Some(Kind::Dimension) {
+ return None;
+ }
+ let (value, is_integer, _) = self.numeric_value();
+ Some((value, is_integer, self.name()))
+ }
+
+ fn numeric_value(&self) -> (f64, bool, bool) {
+ let token = self.token();
+ let (start, end) = token.number_range();
+ let value = match self.source {
+ TokenizerInput::Latin1(units) => number_of(&units[start..end]),
+ TokenizerInput::Utf16(units) => number_of(&units[start..end]),
+ };
+ (value, token.has(flag::INTEGER), token.has(flag::SIGNED))
+ }
+
+ fn contents(&self) -> Values<'a> {
+ Values {
+ tokens: self.tokens,
+ source: self.source,
+ row: self.row + 1,
+ end: self.token().part,
+ gap_taken: false,
+ }
+ }
+
+ /// The name of a function, and its arguments.
+ pub(crate) fn function(&self) -> Option<(Name, Values<'a>)> {
+ (self.kind() == Some(Kind::Function)).then(|| (self.name(), self.contents()))
+ }
+
+ /// What is in a block in square brackets.
+ pub(crate) fn square_block(&self) -> Option<Values<'a>> {
+ (self.kind() == Some(Kind::OpenSquare)).then(|| self.contents())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{Rows, Values};
+ use crate::css::css_tokenizer::{ParserTokenKind, TokenizerInput, tokenize_for_parser};
+ use crate::css::parser::component_value::{ComponentKind, ComponentValue, consume_a_list_of_component_values};
+ use std::fmt::Write;
+
+ fn old_shape(values: &[ComponentValue], output: &mut String) {
+ let mut was_whitespace = false;
+ for value in values {
+ // NB: A run of whitespace and comments is one whitespace value in the rows.
+ if value.is_whitespace() {
+ if !was_whitespace {
+ output.push('_');
+ }
+ was_whitespace = true;
+ continue;
+ }
+ was_whitespace = false;
+ match &value.kind {
+ ComponentKind::Function { name, values } => {
+ write!(output, "f{}(", String::from_utf16_lossy(name.as_ref())).unwrap();
+ old_shape(values, output);
+ output.push(')');
+ }
+ ComponentKind::SimpleBlock { opening, values } => {
+ output.push(if matches!(opening, ParserTokenKind::OpenSquare) {
+ '['
+ } else {
+ '<'
+ });
+ old_shape(values, output);
+ output.push('>');
+ }
+ ComponentKind::Token(ParserTokenKind::Ident(name)) => {
+ write!(output, "i{} ", String::from_utf16_lossy(name.as_ref())).unwrap();
+ }
+ ComponentKind::Token(ParserTokenKind::String(text)) => {
+ write!(output, "s{} ", String::from_utf16_lossy(text.as_ref())).unwrap();
+ }
+ ComponentKind::Token(ParserTokenKind::Comma) => output.push(','),
+ ComponentKind::Token(ParserTokenKind::Colon) => output.push(':'),
+ ComponentKind::Token(ParserTokenKind::Hash { value, is_id: true }) => {
+ write!(output, "#{} ", String::from_utf16_lossy(value.as_ref())).unwrap();
+ }
+ ComponentKind::Token(ParserTokenKind::Number { value, .. }) => write!(output, "n{value} ").unwrap(),
+ ComponentKind::Token(ParserTokenKind::Dimension { value, unit, .. }) => {
+ write!(output, "d{value}{} ", String::from_utf16_lossy(unit.as_ref())).unwrap();
+ }
+ _ => output.push('?'),
+ }
+ }
+ }
+
+ fn new_shape(mut values: Values<'_>, output: &mut String) {
+ while let Some(value) = values.next() {
+ if value.is_whitespace() {
+ output.push('_');
+ } else if let Some((name, arguments)) = value.function() {
+ write!(output, "f{}(", String::from_utf16_lossy(&name)).unwrap();
+ new_shape(arguments, output);
+ output.push(')');
+ } else if let Some(contents) = value.square_block() {
+ output.push('[');
+ new_shape(contents, output);
+ output.push('>');
+ } else if value.kind() == Some(super::Kind::OpenParen) || value.kind() == Some(super::Kind::OpenCurly) {
+ output.push('<');
+ new_shape(value.contents(), output);
+ output.push('>');
+ } else if let Some(name) = value.ident() {
+ write!(output, "i{} ", String::from_utf16_lossy(&name)).unwrap();
+ } else if let Some(text) = value.string() {
+ write!(output, "s{} ", String::from_utf16_lossy(&text)).unwrap();
+ } else if value.is_comma() {
+ output.push(',');
+ } else if value.is_colon() {
+ output.push(':');
+ } else if let Some(name) = value.id() {
+ write!(output, "#{} ", String::from_utf16_lossy(&name)).unwrap();
+ } else if let Some((number, _, _)) = value.number() {
+ write!(output, "n{number} ").unwrap();
+ } else if let Some((number, _, unit)) = value.dimension() {
+ write!(output, "d{number}{} ", String::from_utf16_lossy(&unit)).unwrap();
+ } else {
+ output.push('?');
+ }
+ }
+ }
+
+ #[test]
+ fn has_the_component_values_of_the_tokenizer() {
+ for source in [
+ "",
+ " ",
+ "a",
+ " a ",
+ "a b",
+ "a/**/b",
+ "a /* x */ /* y */ b",
+ ".a > .b:not( .c , #d ) ~ e[f = \"g\" i]",
+ "a:nth-child( 2n + 1 of .b ), c",
+ "a(b[c)d]e)f",
+ "a ( b ] c ) d } e",
+ "a(b",
+ "a(b ",
+ "a(b[c ",
+ "a( /* x */",
+ "[a",
+ "a\\62 c, #\\31 23, 'x\\'y' \"unclosed",
+ "#1a .5em 10px -3 +4n",
+ "a,",
+ ",a,,b ,",
+ "{a(b}c",
+ ] {
+ let tokens = tokenize_for_parser(source.as_bytes());
+ let old = consume_a_list_of_component_values(tokens.as_slice()).unwrap();
+ let mut expected = String::new();
+ old_shape(&old, &mut expected);
+ for wide in [false, true] {
+ let utf16 = source.encode_utf16().collect::<Vec<_>>();
+ let input = if wide {
+ TokenizerInput::Utf16(&utf16)
+ } else {
+ TokenizerInput::Latin1(source.as_bytes())
+ };
+ let mut rows = Rows::default();
+ rows.fill_from(input).unwrap();
+ let mut actual = String::new();
+ new_shape(rows.values(input, false), &mut actual);
+ assert_eq!(actual, expected, "{source:?}");
+ }
+ }
+ }
+
+ #[test]
+ fn splits_at_commas_like_a_slice() {
+ for (source, expected) in [
+ ("", vec![""]),
+ ("a", vec!["a"]),
+ ("a,b", vec!["a", "b"]),
+ ("a , b(c,d) ,", vec!["a", "b(c,d)", ""]),
+ (",", vec!["", ""]),
+ (" ", vec![""]),
+ ("a, ", vec!["a", ""]),
+ ] {
+ let input = TokenizerInput::Latin1(source.as_bytes());
+ let mut rows = Rows::default();
+ rows.fill_from(input).unwrap();
+ let mut values = rows.values(input, false);
+ let mut parts = Vec::new();
+ let mut is_first = true;
+ while let Some(part) = values.split_at_comma(is_first) {
+ is_first = false;
+ parts.push(String::from_utf16(&part.source_text(part.source_range())).unwrap());
+ }
+ assert_eq!(parts, expected, "{source:?}");
+ }
+ }
+
+ #[test]
+ fn fails_where_component_values_are_too_deep() {
+ let source = "(".repeat(crate::css::parser::component_value::MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH + 1);
+ let tokens = tokenize_for_parser(source.as_bytes());
+ assert!(consume_a_list_of_component_values(tokens.as_slice()).is_err());
+ let mut rows = Rows::default();
+ assert!(rows.fill_from(TokenizerInput::Latin1(source.as_bytes())).is_err());
+ let source = &source[1..];
+ let tokens = tokenize_for_parser(source.as_bytes());
+ assert!(consume_a_list_of_component_values(tokens.as_slice()).is_ok());
+ assert!(rows.fill_from(TokenizerInput::Latin1(source.as_bytes())).is_ok());
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
index 4ba3d29cea5..761cb34a329 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
@@ -52,6 +52,7 @@ use crate::css::scope_selectors::ScopeSelectors;
use crate::css::selector_arena::{NestingTarget, RuleOrdinal};
use crate::css::selector_parser::{
RustParsedSelectorList, SelectorType, StyleNestingParent, parse_selector_list_from_component_values,
+ parse_selector_list_of_prelude,
};
use crate::css::serialize::TextSink;
use crate::css::serialize::serialize_component_values_to_utf16;
@@ -159,7 +160,7 @@ pub(crate) struct AtRule {
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct QualifiedRule {
- pub prelude: Vec<ComponentValue>,
+ pub prelude: structure::Prelude,
pub prelude_is_selector: bool,
nesting_parent: StyleNestingParent,
valid_in_context: bool,
@@ -1072,7 +1073,7 @@ where
{
match (rule, rule_kind) {
(Rule::Qualified(rule), ParsedRuleKind::Qualified) if !rule.prelude_is_selector => {
- parse_keyframe_selectors(&rule.prelude)
+ parse_keyframe_selectors(&rule.prelude.component_values())
}
(Rule::Qualified(_), ParsedRuleKind::Qualified) => ParsedRulePrelude::Unparsed,
(Rule::At(rule), ParsedRuleKind::Layer) => parse_layer_prelude(&rule.prelude, rule.has_block),
@@ -1881,6 +1882,10 @@ struct SyntaxParseBuilder<'a> {
dedup: DeclarationDedup,
/// The arena the selectors of the sheet's style rules go into, frozen as the parse finishes.
selectors: RefCell<crate::css::selector_arena::SheetSelectorsBuilder>,
+ /// The tokens of the prelude that is parsed.
+ rows: RefCell<crate::css::parser::rows::Rows>,
+ /// The names that the selectors of the style rules name.
+ names: RefCell<crate::css::selector_parser::NameCache>,
/// What a `&` in the rules being appended names, or none outside every rule.
nesting: Cell<Option<NestingTarget>>,
/// What the rule the rules being appended are directly in is to a `&`, or none outside every
@@ -2308,7 +2313,7 @@ fn structural_validation_code(
match (rule, rule_kind) {
(Rule::Qualified(rule), ParsedRuleKind::Qualified) if rule.prelude_is_selector => {
- if non_whitespace(&rule.prelude).is_empty() {
+ if rule.prelude.is_empty() {
Some(FfiSyntaxDiagnosticCode::StyleEmptySelector)
} else if !selector_list_is_valid {
Some(FfiSyntaxDiagnosticCode::StyleSelectorsInvalid)
@@ -2545,6 +2550,8 @@ impl<'a> SyntaxParseBuilder<'a> {
fn finish(self) -> ParsedStyleSheet {
// NB: Every handle to the sheet's selectors reads them once the arena is frozen.
drop(self.selectors.take());
+ // NB: The arena of the selectors now holds the names, so the parse lets go of them.
+ drop(self.names.take());
let mut declaration_errors = self.collect_declaration_errors().into_vec();
let mut root_declarations = Vec::new();
for item in &self.items {
@@ -2658,6 +2665,8 @@ impl<'a> SyntaxParseBuilder<'a> {
}
selectors
}),
+ rows: RefCell::default(),
+ names: RefCell::default(),
nesting: Cell::new(None),
parent: Cell::new(None),
}
@@ -3044,7 +3053,7 @@ impl<'a> SyntaxParseBuilder<'a> {
fn parse_selector_list(
&self,
- values: &[ComponentValue],
+ prelude: &structure::Prelude,
selector_type: SelectorType,
nesting_parent: StyleNestingParent,
nesting: NestingTarget,
@@ -3054,8 +3063,15 @@ impl<'a> SyntaxParseBuilder<'a> {
.iter()
.map(|namespace| TokenizerInput::Utf16(namespace.as_ref()))
.collect::<Vec<_>>();
- let selector_list =
- parse_selector_list_from_component_values(values, &declared_namespaces, selector_type).ok()?;
+ let selector_list = parse_selector_list_of_prelude(
+ &mut self.rows.borrow_mut(),
+ &self.names,
+ prelude.input(),
+ prelude.range(),
+ &declared_namespaces,
+ selector_type,
+ )
+ .ok()?;
let (list, ordinal) = selector_list
.adapt_for_nesting(nesting_parent)
.into_rule_list_in(&mut self.selectors.borrow_mut(), nesting);
@@ -3102,11 +3118,10 @@ impl<'a> SyntaxParseBuilder<'a> {
fn append_rule(&mut self, rule: &Rule) -> Arc<ParsedRule> {
let original_rule_kind = rule_kind(rule);
- let (is_qualified, name, prelude, declarations, children, has_block, source_position) = match rule {
+ let (is_qualified, name, declarations, children, has_block, source_position) = match rule {
Rule::At(rule) => (
false,
rule.name.as_ref(),
- rule.prelude.as_slice(),
&[][..],
rule.children.as_slice(),
rule.has_block,
@@ -3115,7 +3130,6 @@ impl<'a> SyntaxParseBuilder<'a> {
Rule::Qualified(rule) => (
true,
&[][..],
- rule.prelude.as_slice(),
rule.declarations.as_slice(),
rule.children.as_slice(),
true,
@@ -3181,7 +3195,10 @@ impl<'a> SyntaxParseBuilder<'a> {
let validation_code =
structural_validation_code(rule, original_rule_kind, &parsed_prelude, selector_list.is_some());
let rule_kind = if let Some(code) = validation_code {
- let prelude_source = component_list_source(prelude);
+ let prelude_source = match rule {
+ Rule::At(rule) => component_list_source(&rule.prelude),
+ Rule::Qualified(rule) => Cow::Owned(rule.prelude.text()),
+ };
self.append_rule_validation_diagnostic(rule, original_rule_kind, code, prelude_source.as_ref());
ParsedRuleKind::Invalid
} else {
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs
index a6238a92ae3..2cad2200778 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs
@@ -28,6 +28,7 @@ use crate::css::parser::component_value::{
ComponentKind, ComponentValue, ComponentValueList, MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH,
};
use crate::css::parser::lexer::{Kind, Lexer, Text, Token, flag, name_of, number_of, string_of, url_of};
+use crate::css::parser::rows::closer_of;
use crate::css::property_metadata::property_id_from_name;
use crate::css::selector_parser::StyleNestingParent;
use smallvec::SmallVec;
@@ -57,17 +58,6 @@ fn parser_string(text: Text<'_>) -> ParserString {
}
}
-/// The token that ends the block or function that a token of `kind` starts.
-#[inline]
-fn closer_of(kind: Kind) -> Option<Kind> {
- match kind {
- Kind::Function | Kind::OpenParen => Some(Kind::CloseParen),
- Kind::OpenSquare => Some(Kind::CloseSquare),
- Kind::OpenCurly => Some(Kind::CloseCurly),
- _ => None,
- }
-}
-
fn source_end(value: &ComponentValue) -> usize {
match &value.original_source_text {
ParserSource::Shared { range, .. } => range.end,
@@ -121,14 +111,21 @@ impl<'a, U: Unit> Stream<'a, U> {
fn advance(&mut self) {
self.previous_end = self.token.end as usize;
let mut token = self.lexer.next();
- if token.start as usize >= self.limit && token.kind != Kind::EndOfFile {
+ if token.start as usize >= self.limit {
let limit = self.limit as u32;
+ // NB: Whitespace and comments before the limit are before the token that starts there. The end of the
+ // source is such a token too, and the whitespace and comments after the limit are not in the stream.
+ let flags = if self.previous_end < self.limit {
+ token.flags & (flag::SPACE_BEFORE | flag::COMMENT_BEFORE)
+ } else {
+ 0
+ };
token = Token {
start: limit,
end: limit,
part: limit,
kind: Kind::EndOfFile,
- flags: 0,
+ flags,
};
}
if token.end as usize > self.seen_end {
@@ -326,6 +323,15 @@ impl<'a, U: Unit> Stream<'a, U> {
})
}
+ /// Whether the name of `token` starts with two U+002D HYPHEN-MINUS (-).
+ fn name_starts_with_dashes(&self, token: Token) -> bool {
+ if token.has(flag::ESCAPED) {
+ return starts_with_ascii(&self.name(token), b"--");
+ }
+ let (start, end) = token.name_range();
+ end - start >= 2 && self.units[start].code() == 0x2D && self.units[start + 1].code() == 0x2D
+ }
+
/// Whether the name of `token` is `expected`, which is lowercase ASCII, in any case.
fn name_is(&self, token: Token, expected: &[u8]) -> bool {
if token.has(flag::ESCAPED) {
@@ -473,6 +479,56 @@ impl LineCursor {
}
}
+/// The prelude of a qualified rule: where it is in the source. It starts at its first token, and ends where the block of
+/// the rule starts.
+#[derive(Clone)]
+pub(crate) struct Prelude {
+ source: Arc<SourceStorage>,
+ range: Range<u32>,
+}
+
+impl Prelude {
+ pub(crate) fn range(&self) -> Range<usize> {
+ self.range.start as usize..self.range.end as usize
+ }
+
+ /// The source that the prelude is in, which is preprocessed text.
+ pub(crate) fn input(&self) -> TokenizerInput<'_> {
+ self.source.as_input()
+ }
+
+ /// Whether the prelude has no token.
+ pub(crate) fn is_empty(&self) -> bool {
+ self.range.is_empty()
+ }
+
+ pub(crate) fn component_values(&self) -> Vec<ComponentValue> {
+ match self.source.as_ref() {
+ SourceStorage::Latin1(units) => component_values_in(units, &self.source, self.range()),
+ SourceStorage::Utf16(units) => component_values_in(units, &self.source, self.range()),
+ }
+ }
+
+ pub(crate) fn text(&self) -> Vec<u16> {
+ match self.source.as_ref() {
+ SourceStorage::Latin1(units) => units[self.range()].iter().map(|&unit| u16::from(unit)).collect(),
+ SourceStorage::Utf16(units) => units[self.range()].to_vec(),
+ }
+ }
+}
+
+impl PartialEq for Prelude {
+ fn eq(&self, other: &Self) -> bool {
+ self.text() == other.text()
+ }
+}
+
+impl std::fmt::Debug for Prelude {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(formatter, "Prelude({:?})", String::from_utf16_lossy(&self.text()))
+ }
+}
+
/// What a component value at the top level of a declaration's value is to the declaration.
#[derive(Clone, Copy, PartialEq, Eq)]
enum TopLevel {
@@ -648,36 +704,24 @@ impl<'a, U: Unit> Core<'a, U> {
} else {
RuleContext::Style
};
- let mut rule = QualifiedRule {
- prelude: Vec::with_capacity(8),
- prelude_is_selector: qualified_context == RuleContext::Style,
- nesting_parent: self.style_nesting_parent(),
- valid_in_context: false,
- outer_rule_name: self.rule_names.last().cloned().flatten(),
- declarations: Vec::new(),
- children: Vec::new(),
- source_position: None,
- };
- let mut is_first = true;
+ let nesting_parent = self.style_nesting_parent();
+ let outer_rule_name = self.rule_names.last().cloned().flatten();
+ let start = self.stream.token.start;
+ let mut source_position = None;
+ // Whether the first two component values are a name that starts with two dashes, and a colon.
+ let mut count = 0usize;
+ let mut starts_with_custom_name = false;
+ let mut looks_like_custom_property = false;
+ let mut may_not_be_shared = false;
loop {
- // NB: The whitespace before the rule is not part of its prelude.
- if !is_first {
- self.stream.push_gap(&mut rule.prelude);
- }
- is_first = false;
- let kind = self.kind();
+ let token = self.stream.token;
+ let kind = token.kind;
if kind == Kind::EndOfFile || stop == Some(kind) {
return Err(QualifiedRuleResult::Invalid);
}
match kind {
Kind::CloseCurly if nested == Nested::Yes => return Err(QualifiedRuleResult::Invalid),
Kind::OpenCurly => {
- let mut non_whitespace = rule.prelude.iter().filter(|value| !value.is_whitespace());
- let looks_like_custom_property = non_whitespace
- .next()
- .and_then(ComponentValue::ident)
- .is_some_and(|ident| starts_with_ascii(ident, b"--"))
- && non_whitespace.next().is_some_and(ComponentValue::is_colon);
if looks_like_custom_property {
if nested == Nested::Yes {
self.consume_bad_declaration(nested);
@@ -686,6 +730,19 @@ impl<'a, U: Unit> Core<'a, U> {
}
return Err(QualifiedRuleResult::Invalid);
}
+ let mut rule = QualifiedRule {
+ prelude: Prelude {
+ source: self.stream.storage.clone(),
+ range: start..token.start,
+ },
+ prelude_is_selector: qualified_context == RuleContext::Style,
+ nesting_parent,
+ valid_in_context: false,
+ outer_rule_name,
+ declarations: Vec::new(),
+ children: Vec::new(),
+ source_position,
+ };
self.rule_context.push(qualified_context);
self.rule_names.push(context_rule_name(qualified_context));
rule.children = self.consume_block();
@@ -701,15 +758,15 @@ impl<'a, U: Unit> Core<'a, U> {
return Ok(rule);
}
_ => {
- if rule.source_position.is_none() {
- let start = self.stream.token.start as usize;
- rule.source_position = Some(self.lines.position(self.stream.units, start));
+ if count == 0 {
+ source_position = Some(self.lines.position(self.stream.units, token.start as usize));
+ starts_with_custom_name = kind == Kind::Ident && self.stream.name_starts_with_dashes(token);
+ } else if count == 1 {
+ looks_like_custom_property = starts_with_custom_name && kind == Kind::Colon;
}
- let value = self
- .stream
- .consume_component_value(0)
+ count += 1;
+ self.skip_component_value(&mut may_not_be_shared)
.map_err(|()| QualifiedRuleResult::Invalid)?;
- rule.prelude.push(value);
}
}
}
@@ -1260,6 +1317,20 @@ mod tests {
assert_eq!(found, expected);
}
+ #[test]
+ fn a_value_has_no_whitespace_from_after_it() {
+ for text in ["a: b ", "a: b /* c */", "a: b\n", "a: b !important ", "a: b ;", "a: b"] {
+ let source = source_of(text.as_bytes().into());
+ let items = Parser::new(&source, vec![RuleContext::Style]).consume_block_contents();
+ let [RuleOrDeclarations::Declarations(declarations)] = items.as_slice() else {
+ panic!("expected declarations");
+ };
+ let values = declarations[0].value.component_values();
+ assert_eq!(values.len(), 1, "{text:?}");
+ assert!(!values[0].is_whitespace(), "{text:?}");
+ }
+ }
+
#[test]
fn counts_lines_and_code_points() {
let text: Vec<u16> = "a\n\u{1f600}b\u{e9}\n\nc".encode_utf16().collect();
diff --git a/Libraries/LibWeb/Rust/src/css/parser/token_stream.rs b/Libraries/LibWeb/Rust/src/css/parser/token_stream.rs
index b8fb3003afc..59e1a5b7089 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/token_stream.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/token_stream.rs
@@ -78,21 +78,6 @@ impl<'a> TokenStream<'a> {
}
&self.values[start..end]
}
-
- // Compatibility names for parsers that use iterator-style terminology.
- pub(crate) fn peek(&self) -> Option<&'a ComponentValue> {
- self.values.get(self.position)
- }
-
- pub(crate) fn peek_n(&self, offset: usize) -> Option<&'a ComponentValue> {
- self.values.get(self.position.saturating_add(offset))
- }
-
- pub(crate) fn next(&mut self) -> Option<&'a ComponentValue> {
- let value = self.values.get(self.position)?;
- self.position += 1;
- Some(value)
- }
}
pub(crate) struct StateTransaction<'stream, 'values> {
diff --git a/Libraries/LibWeb/Rust/src/css/selector_parser.rs b/Libraries/LibWeb/Rust/src/css/selector_parser.rs
index 3987db247d6..2c4b71c96bf 100644
--- a/Libraries/LibWeb/Rust/src/css/selector_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/selector_parser.rs
@@ -9,11 +9,11 @@
use crate::css::ffi_support::OwnedBox;
use std::sync::Arc;
-use super::css_tokenizer::{CssNumberType, ParserTokenKind, TokenizerInput, tokenize_for_parser};
+use super::css_tokenizer::{TokenizerInput, filter_code_points};
use super::ffi_support::FfiUtf16View;
use super::ffi_support::ascii_lowercase;
-use super::parser::component_value::{ComponentKind, ComponentValue, consume_a_list_of_component_values};
-use super::parser::token_stream::TokenStream as Stream;
+use super::parser::component_value::ComponentValue;
+use super::parser::rows::{Cv, Name, Rows, Values};
#[cfg(test)]
use super::selector::FfiStringView;
use super::selector::{
@@ -81,19 +81,12 @@ fn pseudo_class_selector(pseudo_class: PseudoClassType) -> PseudoClassSelector {
}
}
-fn split_on_commas(values: &[ComponentValue]) -> Vec<&[ComponentValue]> {
+fn split_on_commas(mut values: Values<'_>) -> Vec<Values<'_>> {
let mut result = Vec::new();
- let mut start = 0;
- loop {
- let end = values[start..]
- .iter()
- .position(ComponentValue::is_comma)
- .map_or(values.len(), |offset| start + offset);
- result.push(&values[start..end]);
- if end == values.len() {
- break;
- }
- start = end + 1;
+ let mut is_first = true;
+ while let Some(part) = values.split_at_comma(is_first) {
+ is_first = false;
+ result.push(part);
}
result
}
@@ -108,38 +101,14 @@ fn clamp_integer(value: f64) -> i32 {
value.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32
}
-fn integer(value: &ComponentValue) -> Option<(i32, bool)> {
- let ComponentKind::Token(ParserTokenKind::Number { value, number_type }) = value.kind else {
- return None;
- };
- if !matches!(
- number_type,
- CssNumberType::Integer | CssNumberType::IntegerWithExplicitSign
- ) {
- return None;
- }
- Some((
- clamp_integer(value),
- number_type == CssNumberType::IntegerWithExplicitSign,
- ))
+fn integer(value: Cv<'_>) -> Option<(i32, bool)> {
+ let (value, is_integer, is_signed) = value.number()?;
+ is_integer.then(|| (clamp_integer(value), is_signed))
}
-fn dimension(value: &ComponentValue) -> Option<(i32, &[u16])> {
- let ComponentKind::Token(ParserTokenKind::Dimension {
- value,
- number_type,
- unit,
- }) = &value.kind
- else {
- return None;
- };
- if !matches!(
- number_type,
- CssNumberType::Integer | CssNumberType::IntegerWithExplicitSign
- ) {
- return None;
- }
- Some((clamp_integer(*value), unit))
+fn dimension(value: Cv<'_>) -> Option<(i32, Name)> {
+ let (value, is_integer, unit) = value.dimension()?;
+ is_integer.then(|| (clamp_integer(value), unit))
}
fn ascii_i32_saturating(value: &[u16]) -> Option<i32> {
@@ -168,11 +137,11 @@ fn digits(value: &[u16]) -> bool {
!value.is_empty() && value.iter().all(|unit| (b'0' as u16..=b'9' as u16).contains(unit))
}
-fn parse_an_plus_b_tail(stream: &mut Stream<'_>, step_size: i32) -> AnPlusBPattern {
- let after_step = stream.position;
+fn parse_an_plus_b_tail(stream: &mut Values<'_>, step_size: i32) -> AnPlusBPattern {
+ let after_step = *stream;
stream.discard_whitespace();
if let Some((offset, true)) = stream.peek().and_then(integer) {
- stream.position += 1;
+ stream.skip();
return AnPlusBPattern { step_size, offset };
}
let sign = if stream.peek().is_some_and(|value| value.is_delim(b'+')) {
@@ -180,32 +149,32 @@ fn parse_an_plus_b_tail(stream: &mut Stream<'_>, step_size: i32) -> AnPlusBPatte
} else if stream.peek().is_some_and(|value| value.is_delim(b'-')) {
-1
} else {
- stream.position = after_step;
+ *stream = after_step;
return AnPlusBPattern { step_size, offset: 0 };
};
- stream.position += 1;
+ stream.skip();
stream.discard_whitespace();
if let Some((offset, false)) = stream.peek().and_then(integer) {
- stream.position += 1;
+ stream.skip();
return AnPlusBPattern {
step_size,
offset: offset.saturating_mul(sign),
};
}
- stream.position = after_step;
+ *stream = after_step;
AnPlusBPattern { step_size, offset: 0 }
}
// https://drafts.csswg.org/css-syntax-3/#anb-microsyntax
-fn parse_an_plus_b(stream: &mut Stream<'_>) -> Option<AnPlusBPattern> {
- let original = stream.position;
+fn parse_an_plus_b(stream: &mut Values<'_>) -> Option<AnPlusBPattern> {
+ let original = *stream;
stream.discard_whitespace();
if stream
.peek()
- .and_then(ComponentValue::ident)
- .is_some_and(|ident| ascii_eq(ident, "odd"))
+ .and_then(|value| value.ident())
+ .is_some_and(|ident| ascii_eq(&ident, "odd"))
{
- stream.position += 1;
+ stream.skip();
return Some(AnPlusBPattern {
step_size: 2,
offset: 1,
@@ -213,78 +182,79 @@ fn parse_an_plus_b(stream: &mut Stream<'_>) -> Option<AnPlusBPattern> {
}
if stream
.peek()
- .and_then(ComponentValue::ident)
- .is_some_and(|ident| ascii_eq(ident, "even"))
+ .and_then(|value| value.ident())
+ .is_some_and(|ident| ascii_eq(&ident, "even"))
{
- stream.position += 1;
+ stream.skip();
return Some(AnPlusBPattern {
step_size: 2,
offset: 0,
});
}
if let Some((offset, _)) = stream.peek().and_then(integer) {
- stream.position += 1;
+ stream.skip();
return Some(AnPlusBPattern { step_size: 0, offset });
}
if let Some((step_size, unit)) = stream.peek().and_then(dimension) {
- if ascii_eq(unit, "n") {
- stream.position += 1;
+ if ascii_eq(&unit, "n") {
+ stream.skip();
return Some(parse_an_plus_b_tail(stream, step_size));
}
- if ascii_eq(unit, "n-") {
- stream.position += 1;
+ if ascii_eq(&unit, "n-") {
+ stream.skip();
if let Some((offset, false)) = stream.peek().and_then(integer) {
- stream.position += 1;
+ stream.skip();
return Some(AnPlusBPattern {
step_size,
offset: offset.saturating_neg(),
});
}
- stream.position = original;
+ *stream = original;
return None;
}
- if unit.len() > 2 && ascii_starts_with(unit, "n-") && digits(&unit[2..]) {
+ if unit.len() > 2 && ascii_starts_with(&unit, "n-") && digits(&unit[2..]) {
let offset = ascii_i32_saturating(&unit[1..])?;
- stream.position += 1;
+ stream.skip();
return Some(AnPlusBPattern { step_size, offset });
}
}
- if let Some(ident) = stream.peek().and_then(ComponentValue::ident) {
- if ident.len() > 3 && ascii_starts_with(ident, "-n-") && digits(&ident[3..]) {
+ if let Some(ident) = stream.peek().and_then(|value| value.ident()) {
+ if ident.len() > 3 && ascii_starts_with(&ident, "-n-") && digits(&ident[3..]) {
let offset = ascii_i32_saturating(&ident[2..])?;
- stream.position += 1;
+ stream.skip();
return Some(AnPlusBPattern { step_size: -1, offset });
}
- if ascii_eq(ident, "-n") {
- stream.position += 1;
+ if ascii_eq(&ident, "-n") {
+ stream.skip();
return Some(parse_an_plus_b_tail(stream, -1));
}
- if ascii_eq(ident, "-n-") {
- stream.position += 1;
+ if ascii_eq(&ident, "-n-") {
+ stream.skip();
stream.discard_whitespace();
if let Some((offset, false)) = stream.peek().and_then(integer) {
- stream.position += 1;
+ stream.skip();
return Some(AnPlusBPattern {
step_size: -1,
offset: offset.saturating_neg(),
});
}
- stream.position = original;
+ *stream = original;
return None;
}
}
if stream.peek().is_some_and(|value| value.is_delim(b'+')) {
- stream.position += 1;
+ stream.skip();
}
- let ident = stream.next().and_then(ComponentValue::ident);
+ let ident = stream.next().and_then(|value| value.ident());
+ let ident = ident.as_deref();
if ident.is_some_and(|ident| ascii_eq(ident, "n")) {
return Some(parse_an_plus_b_tail(stream, 1));
}
if ident.is_some_and(|ident| ascii_eq(ident, "n-")) {
stream.discard_whitespace();
if let Some((offset, false)) = stream.peek().and_then(integer) {
- stream.position += 1;
+ stream.skip();
return Some(AnPlusBPattern {
step_size: 1,
offset: offset.saturating_neg(),
@@ -299,12 +269,36 @@ fn parse_an_plus_b(stream: &mut Stream<'_>) -> Option<AnPlusBPattern> {
let offset = ascii_i32_saturating(&ident[1..])?;
return Some(AnPlusBPattern { step_size: 1, offset });
}
- stream.position = original;
+ *stream = original;
None
}
+/// The process style atom of each name that the selectors of one parse name, with one reference to each. A sheet says
+/// the same names many times, and the process atom table then sees each of them once.
+#[derive(Default)]
+pub(crate) struct NameCache {
+ atoms: hashbrown::HashMap<Box<[u16]>, StyleAtomID, foldhash::fast::FixedState>,
+ /// A reference to each atom, which keeps it live until the arena of the selectors leases it. Whoever holds the
+ /// cache drops it after that.
+ leases: Vec<AtomLease>,
+}
+
+impl NameCache {
+ fn name(&mut self, value: &[u16]) -> StyleAtomID {
+ if let Some(&atom) = self.atoms.get(value) {
+ return atom;
+ }
+ let lease = crate::css::style::process_atoms().intern(value);
+ let atom = lease.atom();
+ self.leases.push(lease);
+ self.atoms.insert(value.into(), atom);
+ atom
+ }
+}
+
struct SelectorParser<'a> {
declared_namespaces: Option<&'a [TokenizerInput<'a>]>,
+ name_cache: Option<&'a std::cell::RefCell<NameCache>>,
pseudo_class_context: Vec<PseudoClassType>,
nesting_limit_exceeded: bool,
compound_pseudo_element: Option<PseudoElementType>,
@@ -318,6 +312,7 @@ impl<'a> SelectorParser<'a> {
fn new(declared_namespaces: Option<&'a [TokenizerInput<'a>]>) -> Self {
Self {
declared_namespaces,
+ name_cache: None,
pseudo_class_context: Vec::new(),
nesting_limit_exceeded: false,
compound_pseudo_element: None,
@@ -328,6 +323,9 @@ impl<'a> SelectorParser<'a> {
/// The process style atom of the name `value` spells.
fn name(&self, value: &[u16]) -> StyleAtomID {
+ if let Some(cache) = self.name_cache {
+ return cache.borrow_mut().name(value);
+ }
let lease = crate::css::style::process_atoms().intern(value);
let atom = lease.atom();
self.names.borrow_mut().push(lease);
@@ -344,7 +342,7 @@ impl<'a> SelectorParser<'a> {
fn parse_selector_list(
&mut self,
- values: &[ComponentValue],
+ values: Values<'_>,
selector_type: SelectorType,
parsing_mode: SelectorParsingMode,
) -> Result<SelectorList, ()> {
@@ -353,13 +351,10 @@ impl<'a> SelectorParser<'a> {
return Err(());
}
let mut selectors = Vec::new();
- let mut start = 0;
- loop {
- let end = values[start..]
- .iter()
- .position(ComponentValue::is_comma)
- .map_or(values.len(), |offset| start + offset);
- let selector_values = &values[start..end];
+ let mut rest = values;
+ let mut is_first = true;
+ while let Some(selector_values) = rest.split_at_comma(is_first) {
+ is_first = false;
let selector = self.parse_complex_selector(selector_values, selector_type);
if self.nesting_limit_exceeded {
return Err(());
@@ -367,17 +362,7 @@ impl<'a> SelectorParser<'a> {
match selector {
Ok(selector) => selectors.push(selector),
Err(()) if parsing_mode == SelectorParsingMode::Forgiving => {
- let mut invalid_values = selector_values;
- while invalid_values.first().is_some_and(ComponentValue::is_whitespace) {
- invalid_values = &invalid_values[1..];
- }
- while invalid_values.last().is_some_and(ComponentValue::is_whitespace) {
- invalid_values = &invalid_values[..invalid_values.len() - 1];
- }
- let source = invalid_values
- .iter()
- .flat_map(|value| value.original_source_text.iter())
- .collect::<Vec<_>>();
+ let source = selector_values.source_text(selector_values.source_range());
selectors.push(CompiledSelector::new(
vec![CompoundSelector {
combinator: if selector_type == SelectorType::Standalone {
@@ -393,10 +378,6 @@ impl<'a> SelectorParser<'a> {
}
Err(()) => return Err(()),
}
- if end == values.len() {
- break;
- }
- start = end + 1;
}
if selectors.is_empty() && parsing_mode != SelectorParsingMode::Forgiving {
return Err(());
@@ -406,10 +387,10 @@ impl<'a> SelectorParser<'a> {
fn parse_complex_selector(
&mut self,
- values: &[ComponentValue],
+ values: Values<'_>,
selector_type: SelectorType,
) -> Result<Arc<CompiledSelector>, ()> {
- let mut stream = Stream::new(values);
+ let mut stream = values;
let mut first_combinator = self.parse_combinator(&mut stream);
match selector_type {
SelectorType::Standalone => {
@@ -529,41 +510,41 @@ impl<'a> SelectorParser<'a> {
Ok(CompiledSelector::new(compounds.into_boxed_slice()))
}
- fn parse_qualified_name(&self, stream: &mut Stream<'_>, allow_wildcard: bool) -> Option<QualifiedName> {
- fn name(value: &ComponentValue) -> Option<&[u16]> {
+ fn parse_qualified_name(&self, stream: &mut Values<'_>, allow_wildcard: bool) -> Option<QualifiedName> {
+ fn name(value: Cv<'_>) -> Option<Name> {
if value.is_delim(b'*') {
- return Some(&[b'*' as u16]);
+ return Some(Name::from_slice(&[b'*' as u16]));
}
value.ident()
}
- let original = stream.position;
+ let original = *stream;
let first = stream.next()?;
if first.is_delim(b'|') {
let parsed_name = stream.next().and_then(name)?;
- if !allow_wildcard && parsed_name == [b'*' as u16] {
- stream.position = original;
+ if !allow_wildcard && parsed_name[..] == [b'*' as u16] {
+ *stream = original;
return None;
}
return Some(QualifiedName::new(
NamespaceType::None,
StyleAtomID::NONE,
- self.qualified_name_part(parsed_name),
+ self.qualified_name_part(&parsed_name),
));
}
let Some(first_name) = name(first) else {
- stream.position = original;
+ *stream = original;
return None;
};
if stream.peek().is_some_and(|value| value.is_delim(b'|')) && stream.peek_n(1).and_then(name).is_some() {
- stream.position += 1;
+ stream.skip();
let parsed_name = name(stream.next().unwrap()).unwrap();
- if !allow_wildcard && parsed_name == [b'*' as u16] {
- stream.position = original;
+ if !allow_wildcard && parsed_name[..] == [b'*' as u16] {
+ *stream = original;
return None;
}
- let namespace_type = if first_name == [b'*' as u16] {
+ let namespace_type = if first_name[..] == [b'*' as u16] {
NamespaceType::Any
} else {
NamespaceType::Named
@@ -579,41 +560,41 @@ impl<'a> SelectorParser<'a> {
})
})
{
- stream.position = original;
+ *stream = original;
return None;
}
return Some(QualifiedName::new(
namespace_type,
if namespace_type == NamespaceType::Named {
- self.name(first_name)
+ self.name(&first_name)
} else {
StyleAtomID::NONE
},
- self.qualified_name_part(parsed_name),
+ self.qualified_name_part(&parsed_name),
));
}
- if !allow_wildcard && first_name == [b'*' as u16] {
- stream.position = original;
+ if !allow_wildcard && first_name[..] == [b'*' as u16] {
+ *stream = original;
return None;
}
Some(QualifiedName::new(
NamespaceType::Default,
StyleAtomID::NONE,
- self.qualified_name_part(first_name),
+ self.qualified_name_part(&first_name),
))
}
- fn next_is_pseudo_element(&self, stream: &Stream<'_>) -> bool {
- if !stream.peek().is_some_and(ComponentValue::is_colon) {
+ fn next_is_pseudo_element(&self, stream: &Values<'_>) -> bool {
+ if !stream.peek().is_some_and(|value| value.is_colon()) {
return false;
}
- if stream.peek_n(1).is_some_and(ComponentValue::is_colon) {
+ if stream.peek_n(1).is_some_and(|value| value.is_colon()) {
return true;
}
- let Some(name) = stream.peek_n(1).and_then(ComponentValue::ident) else {
+ let Some(name) = stream.peek_n(1).and_then(|value| value.ident()) else {
return false;
};
- PseudoElementType::from_name(name).is_some_and(|(pseudo_element, _)| {
+ PseudoElementType::from_name(&name).is_some_and(|(pseudo_element, _)| {
matches!(
pseudo_element,
PseudoElementType::After
@@ -624,7 +605,7 @@ impl<'a> SelectorParser<'a> {
})
}
- fn parse_simple_selector(&mut self, stream: &mut Stream<'_>) -> Result<Option<SimpleSelector>, ()> {
+ fn parse_simple_selector(&mut self, stream: &mut Values<'_>) -> Result<Option<SimpleSelector>, ()> {
if stream
.peek()
.is_none_or(|value| value.is_whitespace() || value.is_comma())
@@ -632,7 +613,7 @@ impl<'a> SelectorParser<'a> {
return Ok(None);
}
- let original = stream.position;
+ let original = *stream;
if let Some(qualified_name) = self.parse_qualified_name(stream, true) {
return Ok(Some(if qualified_name.name.is_none() {
SimpleSelector::Universal(Box::new(qualified_name))
@@ -640,12 +621,12 @@ impl<'a> SelectorParser<'a> {
SimpleSelector::TagName(Box::new(qualified_name))
}));
}
- stream.position = original;
+ *stream = original;
if self.next_is_pseudo_element(stream) {
return self.parse_pseudo_element(stream).map(Some);
}
- if stream.peek().is_some_and(ComponentValue::is_colon) {
+ if stream.peek().is_some_and(|value| value.is_colon()) {
return self.parse_pseudo_class(stream).map(Some);
}
if stream.peek().is_some_and(|value| {
@@ -659,11 +640,11 @@ impl<'a> SelectorParser<'a> {
return Ok(Some(SimpleSelector::Nesting));
}
if first.is_delim(b'.') {
- let class_name = stream.next().and_then(ComponentValue::ident).ok_or(())?;
- return Ok(Some(SimpleSelector::Class(NameSelector::new(self.name(class_name)))));
+ let class_name = stream.next().and_then(|value| value.ident()).ok_or(())?;
+ return Ok(Some(SimpleSelector::Class(NameSelector::new(self.name(&class_name)))));
}
- if let ComponentKind::Token(ParserTokenKind::Hash { value, is_id: true }) = &first.kind {
- return Ok(Some(SimpleSelector::Id(NameSelector::new(self.name(value)))));
+ if let Some(value) = first.id() {
+ return Ok(Some(SimpleSelector::Id(NameSelector::new(self.name(&value)))));
}
if let Some(values) = first.square_block() {
return self.parse_attribute(values).map(Some);
@@ -671,8 +652,8 @@ impl<'a> SelectorParser<'a> {
Err(())
}
- fn parse_attribute(&self, values: &[ComponentValue]) -> Result<SimpleSelector, ()> {
- let mut stream = Stream::new(values);
+ fn parse_attribute(&self, values: Values<'_>) -> Result<SimpleSelector, ()> {
+ let mut stream = values;
stream.discard_whitespace();
let qualified_name = self.parse_qualified_name(&mut stream, false).ok_or(())?;
stream.discard_whitespace();
@@ -713,12 +694,13 @@ impl<'a> SelectorParser<'a> {
.next()
.and_then(|value| value.ident().or_else(|| value.string()))
.ok_or(())?
+ .as_slice()
.into();
stream.discard_whitespace();
let case_type = match stream.next() {
None => AttributeCaseType::Default,
- Some(value) if value.ident().is_some_and(|ident| ascii_eq(ident, "i")) => AttributeCaseType::Insensitive,
- Some(value) if value.ident().is_some_and(|ident| ascii_eq(ident, "s")) => AttributeCaseType::Sensitive,
+ Some(value) if value.ident().is_some_and(|ident| ascii_eq(&ident, "i")) => AttributeCaseType::Insensitive,
+ Some(value) if value.ident().is_some_and(|ident| ascii_eq(&ident, "s")) => AttributeCaseType::Sensitive,
Some(_) => return Err(()),
};
stream.discard_whitespace();
@@ -734,13 +716,13 @@ impl<'a> SelectorParser<'a> {
})))
}
- fn parse_pseudo_class(&mut self, stream: &mut Stream<'_>) -> Result<SimpleSelector, ()> {
- if !stream.next().is_some_and(ComponentValue::is_colon) {
+ fn parse_pseudo_class(&mut self, stream: &mut Values<'_>) -> Result<SimpleSelector, ()> {
+ if !stream.next().is_some_and(|value| value.is_colon()) {
return Err(());
}
let value = stream.next().ok_or(())?;
if let Some(name) = value.ident() {
- let pseudo_class = PseudoClassType::from_name(name).ok_or(())?;
+ let pseudo_class = PseudoClassType::from_name(&name).ok_or(())?;
if !pseudo_class.metadata().is_valid_as_identifier {
return Err(());
}
@@ -756,7 +738,7 @@ impl<'a> SelectorParser<'a> {
}
let (name, function_values) = value.function().ok_or(())?;
- let pseudo_class = PseudoClassType::from_name(name).ok_or(())?;
+ let pseudo_class = PseudoClassType::from_name(&name).ok_or(())?;
let metadata = pseudo_class.metadata();
if !metadata.is_valid_as_function || function_values.is_empty() {
return Err(());
@@ -784,7 +766,7 @@ impl<'a> SelectorParser<'a> {
&mut self,
pseudo_class: PseudoClassType,
parameter_type: PseudoClassParameterType,
- values: &[ComponentValue],
+ values: Values<'_>,
) -> Result<PseudoClassSelector, ()> {
if self.pseudo_class_context.len() > MAXIMUM_SELECTOR_NESTING_DEPTH {
self.nesting_limit_exceeded = true;
@@ -793,7 +775,7 @@ impl<'a> SelectorParser<'a> {
let mut selector = pseudo_class_selector(pseudo_class);
match parameter_type {
PseudoClassParameterType::AnPlusB | PseudoClassParameterType::AnPlusBOf => {
- let mut stream = Stream::new(values);
+ let mut stream = values;
selector.an_plus_b_pattern = parse_an_plus_b(&mut stream).ok_or(())?;
stream.discard_whitespace();
if stream.is_empty() {
@@ -802,20 +784,17 @@ impl<'a> SelectorParser<'a> {
if parameter_type != PseudoClassParameterType::AnPlusBOf
|| !stream
.next()
- .and_then(ComponentValue::ident)
- .is_some_and(|ident| ascii_eq(ident, "of"))
+ .and_then(|value| value.ident())
+ .is_some_and(|ident| ascii_eq(&ident, "of"))
{
return Err(());
}
stream.discard_whitespace();
- selector.argument_selector_list = self.parse_selector_list(
- &stream.values[stream.position..],
- SelectorType::Standalone,
- SelectorParsingMode::Standard,
- )?;
+ selector.argument_selector_list =
+ self.parse_selector_list(stream, SelectorType::Standalone, SelectorParsingMode::Standard)?;
}
PseudoClassParameterType::CompoundSelector => {
- let mut stream = Stream::new(values);
+ let mut stream = values;
let mut compound = self.parse_compound_selector(&mut stream)?;
stream.discard_whitespace();
if !stream.is_empty() || compound.simple_selectors.is_empty() {
@@ -830,36 +809,35 @@ impl<'a> SelectorParser<'a> {
selector.is_forgiving = true;
}
PseudoClassParameterType::Ident => {
- let mut stream = Stream::new(values);
+ let mut stream = values;
stream.discard_whitespace();
- let ident = stream.next().and_then(ComponentValue::ident).ok_or(())?;
+ let ident = stream.next().and_then(|value| value.ident()).ok_or(())?;
stream.discard_whitespace();
if !stream.is_empty() {
return Err(());
}
- selector.direction = Some(if ascii_eq(ident, "ltr") {
+ selector.direction = Some(if ascii_eq(&ident, "ltr") {
Direction::LeftToRight
- } else if ascii_eq(ident, "rtl") {
+ } else if ascii_eq(&ident, "rtl") {
Direction::RightToLeft
} else {
Direction::Other
});
- selector.identifier_identity = self.name(ident);
- selector.identifier = Some(ident.into());
+ selector.identifier_identity = self.name(&ident);
+ selector.identifier = Some(ident.as_slice().into());
}
PseudoClassParameterType::LanguageRanges => {
let mut languages = Vec::new();
for values in split_on_commas(values) {
- let mut stream = Stream::new(values);
+ let mut stream = values;
stream.discard_whitespace();
- let (value, is_string) = match &stream.next().ok_or(())?.kind {
- ComponentKind::Token(ParserTokenKind::Ident(value)) => {
- (SelectorString::from_utf16(value), false)
- }
- ComponentKind::Token(ParserTokenKind::String(value)) => {
- (SelectorString::from_utf16(value), true)
- }
- _ => return Err(()),
+ let value = stream.next().ok_or(())?;
+ let (value, is_string) = if let Some(ident) = value.ident() {
+ (SelectorString::from_utf16(&ident), false)
+ } else if let Some(string) = value.string() {
+ (SelectorString::from_utf16(&string), true)
+ } else {
+ return Err(());
};
stream.discard_whitespace();
if !stream.is_empty() {
@@ -872,23 +850,12 @@ impl<'a> SelectorParser<'a> {
PseudoClassParameterType::LevelList => {
let mut levels = Vec::new();
for values in split_on_commas(values) {
- let mut stream = Stream::new(values);
+ let mut stream = values;
stream.discard_whitespace();
- let Some(ComponentValue {
- kind:
- ComponentKind::Token(ParserTokenKind::Number {
- value,
- number_type: CssNumberType::Integer | CssNumberType::IntegerWithExplicitSign,
- }),
- ..
- }) = stream.next()
- else {
+ let Some((value, true, _)) = stream.next().and_then(|value| value.number()) else {
return Err(());
};
- if !value.is_finite()
- || value.fract() != 0.0
- || *value < i64::MIN as f64
- || *value > i64::MAX as f64
+ if !value.is_finite() || value.fract() != 0.0 || value < i64::MIN as f64 || value > i64::MAX as f64
{
return Err(());
}
@@ -896,7 +863,7 @@ impl<'a> SelectorParser<'a> {
if !stream.is_empty() {
return Err(());
}
- levels.push(*value as i64);
+ levels.push(value as i64);
}
selector.levels = levels.into_boxed_slice();
}
@@ -922,13 +889,13 @@ impl<'a> SelectorParser<'a> {
Ok(selector)
}
- fn parse_pseudo_element(&mut self, stream: &mut Stream<'_>) -> Result<SimpleSelector, ()> {
- if !stream.next().is_some_and(ComponentValue::is_colon) {
+ fn parse_pseudo_element(&mut self, stream: &mut Values<'_>) -> Result<SimpleSelector, ()> {
+ if !stream.next().is_some_and(|value| value.is_colon()) {
return Err(());
}
- let double_colon = stream.peek().is_some_and(ComponentValue::is_colon);
+ let double_colon = stream.peek().is_some_and(|value| value.is_colon());
if double_colon {
- stream.position += 1;
+ stream.skip();
}
let name_value = stream.next().ok_or(())?;
let (name, function_values) = if let Some(name) = name_value.ident() {
@@ -939,11 +906,11 @@ impl<'a> SelectorParser<'a> {
return Err(());
};
- let Some((pseudo_element, alias)) = PseudoElementType::from_name(name) else {
- if function_values.is_none() && ascii_starts_with(name, "-webkit-") && !self.inside_has() {
+ let Some((pseudo_element, alias)) = PseudoElementType::from_name(&name) else {
+ if function_values.is_none() && ascii_starts_with(&name, "-webkit-") && !self.inside_has() {
return Ok(SimpleSelector::PseudoElement(Box::new(PseudoElementSelector {
pseudo_element: PseudoElementType::UnknownWebKit,
- serialized_name: Some(lowercase(name)),
+ serialized_name: Some(lowercase(&name)),
value: PseudoElementValue::None,
identifier_identities: Box::new([]),
})));
@@ -1001,9 +968,9 @@ impl<'a> SelectorParser<'a> {
fn parse_pseudo_element_function(
&mut self,
parameter_type: PseudoElementParameterType,
- values: &[ComponentValue],
+ values: Values<'_>,
) -> Result<PseudoElementValue, ()> {
- let mut stream = Stream::new(values);
+ let mut stream = values;
stream.discard_whitespace();
match parameter_type {
PseudoElementParameterType::None => {
@@ -1031,10 +998,10 @@ impl<'a> SelectorParser<'a> {
PseudoElementValue::Universal
} else {
let name = argument.ident().ok_or(())?;
- if is_css_wide_keyword(name) || ascii_eq(name, "default") {
+ if is_css_wide_keyword(&name) || ascii_eq(&name, "default") {
return Err(());
}
- PseudoElementValue::Identifiers(Box::new([name.into()]))
+ PseudoElementValue::Identifiers(Box::new([name.as_slice().into()]))
};
stream.discard_whitespace();
if !stream.is_empty() {
@@ -1045,7 +1012,14 @@ impl<'a> SelectorParser<'a> {
PseudoElementParameterType::IdentList => {
let mut identifiers = Vec::new();
while !stream.is_empty() {
- identifiers.push(stream.next().and_then(ComponentValue::ident).ok_or(())?.into());
+ identifiers.push(
+ stream
+ .next()
+ .and_then(|value| value.ident())
+ .ok_or(())?
+ .as_slice()
+ .into(),
+ );
stream.discard_whitespace();
}
if identifiers.is_empty() {
@@ -1060,20 +1034,20 @@ impl<'a> SelectorParser<'a> {
// * Between <pt-name-selector> and <pt-class-selector>
// * Between any of the components of <pt-class-selector>.
PseudoElementParameterType::PTNameAndClassSelector => {
- fn custom_ident(value: Option<&ComponentValue>) -> Result<SelectorString, ()> {
- let ident = value.and_then(ComponentValue::ident).ok_or(())?;
- if is_css_wide_keyword(ident) || ascii_eq(ident, "default") {
+ fn custom_ident(value: Option<Cv<'_>>) -> Result<SelectorString, ()> {
+ let ident = value.and_then(|value| value.ident()).ok_or(())?;
+ if is_css_wide_keyword(&ident) || ascii_eq(&ident, "default") {
return Err(());
}
- Ok(ident.into())
+ Ok(ident.as_slice().into())
}
// https://drafts.csswg.org/css-view-transitions-1/#typedef-pt-name-selector
// <pt-name-selector> = '*' | <custom-ident>
let name = if stream.peek().is_some_and(|value| value.is_delim(b'*')) {
- stream.position += 1;
+ stream.skip();
Some(TransitionNameSelector::Universal)
- } else if stream.peek().is_some_and(|value| value.ident().is_some()) {
+ } else if stream.peek().is_some_and(|value| value.is_ident()) {
Some(TransitionNameSelector::Name(custom_ident(stream.next())?))
} else {
None
@@ -1081,7 +1055,7 @@ impl<'a> SelectorParser<'a> {
let mut classes = Vec::new();
while stream.peek().is_some_and(|value| value.is_delim(b'.')) {
- stream.position += 1;
+ stream.skip();
classes.push(custom_ident(stream.next())?);
}
if name.is_none() && classes.is_empty() {
@@ -1102,7 +1076,7 @@ impl<'a> SelectorParser<'a> {
}
}
- fn parse_compound_selector(&mut self, stream: &mut Stream<'_>) -> Result<CompoundSelector, ()> {
+ fn parse_compound_selector(&mut self, stream: &mut Values<'_>) -> Result<CompoundSelector, ()> {
let outer_pseudo_element = self.compound_pseudo_element.take();
let simple_selectors = self.parse_compound_simple_selectors(stream);
self.compound_pseudo_element = outer_pseudo_element;
@@ -1113,7 +1087,7 @@ impl<'a> SelectorParser<'a> {
})
}
- fn parse_compound_simple_selectors(&mut self, stream: &mut Stream<'_>) -> Result<Vec<SimpleSelector>, ()> {
+ fn parse_compound_simple_selectors(&mut self, stream: &mut Values<'_>) -> Result<Vec<SimpleSelector>, ()> {
let mut simple_selectors = Vec::new();
while let Some(simple_selector) = self.parse_simple_selector(stream)? {
if matches!(
@@ -1131,28 +1105,29 @@ impl<'a> SelectorParser<'a> {
Ok(simple_selectors)
}
- fn parse_combinator(&self, stream: &mut Stream<'_>) -> Option<Combinator> {
- let original = stream.position;
- let had_whitespace = stream.peek().is_some_and(ComponentValue::is_whitespace);
+ fn parse_combinator(&self, stream: &mut Values<'_>) -> Option<Combinator> {
+ let original = *stream;
+ let had_whitespace = stream.peek().is_some_and(|value| value.is_whitespace());
stream.discard_whitespace();
let combinator = if stream.peek().is_some_and(|value| value.is_delim(b'>')) {
- stream.position += 1;
+ stream.skip();
Some(Combinator::ImmediateChild)
} else if stream.peek().is_some_and(|value| value.is_delim(b'+')) {
- stream.position += 1;
+ stream.skip();
Some(Combinator::NextSibling)
} else if stream.peek().is_some_and(|value| value.is_delim(b'~')) {
- stream.position += 1;
+ stream.skip();
Some(Combinator::SubsequentSibling)
} else if stream.peek().is_some_and(|value| value.is_delim(b'|'))
&& stream.peek_n(1).is_some_and(|value| value.is_delim(b'|'))
{
- stream.position += 2;
+ stream.skip();
+ stream.skip();
Some(Combinator::Column)
} else if had_whitespace {
Some(Combinator::Descendant)
} else {
- stream.position = original;
+ *stream = original;
None
};
if combinator.is_some() {
@@ -1226,18 +1201,28 @@ pub(crate) fn parse_selector_list<'a>(
selector_type: SelectorType,
parsing_mode: SelectorParsingMode,
) -> Result<ParsedSelectorTree, ()> {
- let tokens = tokenize_for_parser(input);
- let values = consume_a_list_of_component_values(tokens.as_slice())?;
- parse_selector_list_with_mode(&values, declared_namespaces, selector_type, parsing_mode)
+ let filtered = filter_code_points(input.into());
+ let input = filtered.as_input();
+ let mut rows = Rows::default();
+ rows.fill_from(input)?;
+ parse_selector_list_with_mode(
+ rows.values(input, false),
+ None,
+ declared_namespaces,
+ selector_type,
+ parsing_mode,
+ )
}
fn parse_selector_list_with_mode(
- values: &[ComponentValue],
+ values: Values<'_>,
+ name_cache: Option<&std::cell::RefCell<NameCache>>,
declared_namespaces: &[TokenizerInput<'_>],
selector_type: SelectorType,
parsing_mode: SelectorParsingMode,
) -> Result<ParsedSelectorTree, ()> {
let mut parser = SelectorParser::new(Some(declared_namespaces));
+ parser.name_cache = name_cache;
let selectors = parser.parse_selector_list(values, selector_type, parsing_mode)?;
Ok(ParsedSelectorTree {
selectors,
@@ -1245,13 +1230,42 @@ fn parse_selector_list_with_mode(
})
}
+/// Parses the selector list that `values` are. The parser reads their source text.
pub(crate) fn parse_selector_list_from_component_values(
values: &[ComponentValue],
declared_namespaces: &[TokenizerInput<'_>],
selector_type: SelectorType,
) -> Result<ParsedSelectorTree, ()> {
+ let source = values
+ .iter()
+ .flat_map(|value| value.original_source_text.iter())
+ .collect::<Vec<_>>();
+ parse_selector_list(
+ TokenizerInput::Utf16(&source),
+ declared_namespaces,
+ selector_type,
+ SelectorParsingMode::Standard,
+ )
+}
+
+/// Parses the selector list in `range` of `source`, which is the prelude of a qualified rule in preprocessed text.
+/// `rows` is scratch memory, and `names` holds the names of the selectors until their arena leases them.
+pub(crate) fn parse_selector_list_of_prelude(
+ rows: &mut Rows,
+ names: &std::cell::RefCell<NameCache>,
+ source: TokenizerInput<'_>,
+ range: std::ops::Range<usize>,
+ declared_namespaces: &[TokenizerInput<'_>],
+ selector_type: SelectorType,
+) -> Result<ParsedSelectorTree, ()> {
+ match source {
+ TokenizerInput::Latin1(units) => rows.fill(units, range)?,
+ TokenizerInput::Utf16(units) => rows.fill(units, range)?,
+ }
+ // NB: The whitespace before a rule is not part of its prelude.
parse_selector_list_with_mode(
- values,
+ rows.values(source, true),
+ Some(names),
declared_namespaces,
selector_type,
SelectorParsingMode::Standard,
@@ -1340,9 +1354,11 @@ fn parse_pseudo_element_selector(
input: TokenizerInput<'_>,
for_computed_style: bool,
) -> Result<(SelectorRef, PseudoElementType), ()> {
- let tokens = tokenize_for_parser(input);
- let values = consume_a_list_of_component_values(tokens.as_slice())?;
- let mut stream = Stream::new(&values);
+ let filtered = filter_code_points(input);
+ let input = filtered.as_input();
+ let mut rows = Rows::default();
+ rows.fill_from(input)?;
+ let mut stream = rows.values(input, false);
// NB: The parser holds the names it interned until the selector built below leases them.
let mut parser = SelectorParser::new(Some(&[]));
let simple = parser.parse_pseudo_element(&mut stream)?;