Skip to content

Truly independent web browser

LibWeb: Parse the structure of style sheets from the new lexer

Andreas Kling6ce7996643d7
diff --git a/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs b/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
index 8ac5b8e2517..4f512218a26 100644
--- a/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
+++ b/Libraries/LibWeb/Rust/src/css/css_tokenizer.rs
@@ -175,13 +175,13 @@ impl TokenizerInput<'_> {
}
}
-enum FilteredTokenizerInput<'a> {
+pub(crate) enum FilteredTokenizerInput<'a> {
Borrowed(TokenizerInput<'a>),
Owned(Vec<u16>),
}
impl FilteredTokenizerInput<'_> {
- fn as_input(&self) -> TokenizerInput<'_> {
+ pub(crate) fn as_input(&self) -> TokenizerInput<'_> {
match self {
Self::Borrowed(input) => *input,
Self::Owned(units) => TokenizerInput::Utf16(units),
@@ -189,7 +189,7 @@ impl FilteredTokenizerInput<'_> {
}
}
-fn filter_code_points(input: TokenizerInput<'_>) -> FilteredTokenizerInput<'_> {
+pub(crate) fn filter_code_points(input: TokenizerInput<'_>) -> FilteredTokenizerInput<'_> {
let needs_filtering = match input {
TokenizerInput::Latin1(units) => units.iter().any(|unit| matches!(unit, b'\r' | b'\x0c' | b'\0')),
TokenizerInput::Utf16(units) => {
@@ -508,14 +508,14 @@ pub(crate) enum SourceStorage {
}
impl SourceStorage {
- fn from_input(input: TokenizerInput<'_>) -> Self {
+ pub(crate) fn from_input(input: TokenizerInput<'_>) -> Self {
match input {
TokenizerInput::Latin1(units) => Self::Latin1(units.into()),
TokenizerInput::Utf16(units) => Self::Utf16(units.into()),
}
}
- fn as_input(&self) -> TokenizerInput<'_> {
+ pub(crate) fn as_input(&self) -> TokenizerInput<'_> {
match self {
Self::Latin1(units) => TokenizerInput::Latin1(units),
Self::Utf16(units) => TokenizerInput::Utf16(units),
@@ -615,7 +615,7 @@ impl ParserSource {
Self::Empty
}
- fn shared(storage: Arc<SourceStorage>, range: Range<usize>) -> Self {
+ pub(crate) fn shared(storage: Arc<SourceStorage>, range: Range<usize>) -> Self {
Self::Shared { storage, range }
}
@@ -698,8 +698,19 @@ pub(crate) fn tokenize_for_parser<'a>(input: impl Into<TokenizerInput<'a>>) -> V
/// The tokens of `input`, whose comments tokenize as `comments` says.
pub(crate) fn tokenize_for_parser_with_comments(input: TokenizerInput<'_>, comments: Comments) -> Vec<ParserToken> {
+ let source = Arc::new(SourceStorage::from_input(filter_code_points(input).as_input()));
+ let mut tokenizer = Tokenizer::new(source.as_input());
+ tokenizer.comments = comments;
let mut tokens = Vec::with_capacity(input.len() / 3);
- ParserTokenFeed::with_comments(input, comments).fill(&mut tokens, usize::MAX);
+ let mut string_storage = Vec::new();
+ loop {
+ let token = tokenizer.next_token();
+ if matches!(token.token_type, TokenType::EndOfFile) {
+ break;
+ }
+ tokens.push(parser_token(&token, Some(&source), &mut string_storage));
+ }
+ finish_shared_strings(&mut tokens, string_storage);
tokens
}
@@ -851,53 +862,6 @@ fn finish_shared_strings(tokens: &mut [ParserToken], string_storage: Vec<u16>) {
}
}
-/// Tokenizes a source for the parser a chunk of tokens at a time, as the parser asks for them — so the tokens of a
-/// whole style sheet never have to exist at once.
-pub(crate) struct ParserTokenFeed {
- source: Arc<SourceStorage>,
- // None once the tokenizer has reached the end of the source.
- cursor: Option<TokenizerCursor>,
-}
-
-impl ParserTokenFeed {
- pub(crate) fn new(input: TokenizerInput<'_>) -> Self {
- Self::with_comments(input, Comments::AsWhitespace)
- }
-
- fn with_comments(input: TokenizerInput<'_>, comments: Comments) -> Self {
- let source = Arc::new(SourceStorage::from_input(filter_code_points(input).as_input()));
- let mut tokenizer = Tokenizer::new(source.as_input());
- tokenizer.comments = comments;
- let cursor = tokenizer.cursor();
- Self {
- source,
- cursor: Some(cursor),
- }
- }
-
- /// Appends up to `count` more tokens to `tokens`, and returns false if the source had none left.
- pub(crate) fn fill(&mut self, tokens: &mut Vec<ParserToken>, count: usize) -> bool {
- let Some(cursor) = self.cursor else {
- return false;
- };
- let first = tokens.len();
- let mut string_storage = Vec::new();
- let mut tokenizer = Tokenizer::resume(self.source.as_input(), cursor);
- self.cursor = loop {
- if tokens.len() - first == count {
- break Some(tokenizer.cursor());
- }
- let token = tokenizer.next_token();
- if matches!(token.token_type, TokenType::EndOfFile) {
- break None;
- }
- tokens.push(parser_token(&token, Some(&self.source), &mut string_storage));
- };
- finish_shared_strings(&mut tokens[first..], string_storage);
- tokens.len() > first
- }
-}
-
type TokenString = SmallVec<[u16; 16]>;
enum TokenType {
@@ -1051,17 +1015,6 @@ struct Tokenizer<'a> {
comments: Comments,
}
-// The state a tokenizer resumes from, at the start of its next token.
-#[derive(Clone, Copy)]
-struct TokenizerCursor {
- index: usize,
- prev_index: usize,
- current_code_point: u32,
- position: SourcePosition,
- prev_position: SourcePosition,
- comments: Comments,
-}
-
impl<'a> Tokenizer<'a> {
fn new(input: TokenizerInput<'a>) -> Self {
Self {
@@ -1075,29 +1028,6 @@ impl<'a> Tokenizer<'a> {
}
}
- fn resume(input: TokenizerInput<'a>, cursor: TokenizerCursor) -> Self {
- Self {
- input,
- index: cursor.index,
- prev_index: cursor.prev_index,
- current_code_point: cursor.current_code_point,
- position: cursor.position,
- prev_position: cursor.prev_position,
- comments: cursor.comments,
- }
- }
-
- fn cursor(&self) -> TokenizerCursor {
- TokenizerCursor {
- index: self.index,
- prev_index: self.prev_index,
- current_code_point: self.current_code_point,
- position: self.position,
- prev_position: self.prev_position,
- comments: self.comments,
- }
- }
-
fn next_token(&mut self) -> Token {
let token_start = self.position;
let mut token = self.consume_a_token();
diff --git a/Libraries/LibWeb/Rust/src/css/parser/block.rs b/Libraries/LibWeb/Rust/src/css/parser/block.rs
index 7273a575c5b..65e7fc2ca9b 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/block.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/block.rs
@@ -15,7 +15,9 @@ use crate::css::css_tokenizer::TokenizerInput;
/// How many code units a block holds.
pub(crate) const BLOCK: usize = 16;
-pub(crate) trait Unit: Copy + Eq + 'static {
+pub(crate) trait Unit: Copy + Eq + std::hash::Hash + 'static {
+ /// Whether a code point can take two units.
+ const WIDE: bool;
fn code(self) -> u32;
/// Loads a block of units as bytes.
fn load(units: &[Self; BLOCK]) -> Block;
@@ -23,6 +25,8 @@ pub(crate) trait Unit: Copy + Eq + 'static {
}
impl Unit for u8 {
+ const WIDE: bool = false;
+
#[inline(always)]
fn code(self) -> u32 {
u32::from(self)
@@ -40,6 +44,8 @@ impl Unit for u8 {
}
impl Unit for u16 {
+ const WIDE: bool = true;
+
#[inline(always)]
fn code(self) -> u32 {
u32::from(self)
diff --git a/Libraries/LibWeb/Rust/src/css/parser/component_value.rs b/Libraries/LibWeb/Rust/src/css/parser/component_value.rs
index 45485bd166e..66f758c4d87 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/component_value.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/component_value.rs
@@ -12,7 +12,7 @@ use crate::css::css_tokenizer::{
use crate::css::serialize::{StringUnits, TextSink, serialize_a_string, serialize_an_identifier};
use smallvec::SmallVec;
-const MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH: usize = 256;
+pub(crate) const MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH: usize = 256;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct ComponentValueList<T = Vec<ComponentValue>> {
@@ -490,24 +490,8 @@ fn is_same_token_kind(left: &ParserTokenKind, right: &ParserTokenKind) -> bool {
std::mem::discriminant(left) == std::mem::discriminant(right)
}
-/// The tokens that component values are consumed from, which a source may produce only as they're asked for.
-pub(crate) trait ParserTokens {
- fn token(&mut self, index: usize) -> Option<&ParserToken>;
- fn token_mut(&mut self, index: usize) -> Option<&mut ParserToken>;
-}
-
-impl ParserTokens for [ParserToken] {
- fn token(&mut self, index: usize) -> Option<&ParserToken> {
- self.get(index)
- }
-
- fn token_mut(&mut self, index: usize) -> Option<&mut ParserToken> {
- self.get_mut(index)
- }
-}
-
-fn consume_component_values<T: ParserTokens + ?Sized>(
- tokens: &mut T,
+fn consume_component_values(
+ tokens: &mut [ParserToken],
position: &mut usize,
ending: Option<&ParserTokenKind>,
depth: usize,
@@ -519,7 +503,7 @@ fn consume_component_values<T: ParserTokens + ?Sized>(
let mut values = Vec::with_capacity(4);
let mut token_count = 0;
- while let Some(token) = tokens.token(*position) {
+ while let Some(token) = tokens.get(*position) {
if ending.is_some_and(|ending| is_same_token_kind(&token.kind, ending)) {
break;
}
@@ -531,8 +515,8 @@ fn consume_component_values<T: ParserTokens + ?Sized>(
Ok(ComponentValueList::with_token_count(values, token_count))
}
-pub(crate) fn consume_a_component_value<T: ParserTokens + ?Sized>(
- tokens: &mut T,
+pub(crate) fn consume_a_component_value(
+ tokens: &mut [ParserToken],
position: &mut usize,
depth: usize,
take_tokens: bool,
@@ -541,7 +525,7 @@ pub(crate) fn consume_a_component_value<T: ParserTokens + ?Sized>(
return Err(());
}
let token = if take_tokens {
- let token = tokens.token_mut(*position).ok_or(())?;
+ let token = tokens.get_mut(*position).ok_or(())?;
std::mem::replace(
token,
ParserToken {
@@ -552,7 +536,7 @@ pub(crate) fn consume_a_component_value<T: ParserTokens + ?Sized>(
},
)
} else {
- tokens.token(*position).ok_or(())?.clone()
+ tokens.get(*position).ok_or(())?.clone()
};
*position += 1;
let opening_source_length = token.source.len();
@@ -571,7 +555,7 @@ pub(crate) fn consume_a_component_value<T: ParserTokens + ?Sized>(
)?;
let last_child_source = function_values.last().map(|value| &value.original_source_text);
let mut closing_source = None;
- if let Some(closing) = tokens.token(*position)
+ if let Some(closing) = tokens.get(*position)
&& matches!(closing.kind, ParserTokenKind::CloseParen)
{
*position += 1;
@@ -606,7 +590,7 @@ pub(crate) fn consume_a_component_value<T: ParserTokens + ?Sized>(
let block_values = consume_component_values(tokens, position, Some(&ending), depth + 1, take_tokens)?;
let last_child_source = block_values.last().map(|value| &value.original_source_text);
let mut closing_source = None;
- if let Some(closing) = tokens.token(*position)
+ if let Some(closing) = tokens.get(*position)
&& is_same_token_kind(&closing.kind, &ending)
{
*position += 1;
diff --git a/Libraries/LibWeb/Rust/src/css/parser/lexer.rs b/Libraries/LibWeb/Rust/src/css/parser/lexer.rs
index 73d296aa6af..38515caa7f3 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/lexer.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/lexer.rs
@@ -189,11 +189,6 @@ impl<'a, U: Unit> Lexer<'a, U> {
self.units
}
- /// Where the next token is looked for.
- pub(crate) fn position(&self) -> usize {
- self.position
- }
-
/// Makes the lexer go on from `position`, which is where a token starts or ends.
pub(crate) fn set_position(&mut self, position: usize) {
self.position = position;
@@ -635,6 +630,7 @@ pub(crate) enum Text<'a> {
Unescaped(Vec<u16>),
}
+#[cfg(test)]
impl Text<'_> {
pub(crate) fn input(&self) -> TokenizerInput<'_> {
match self {
diff --git a/Libraries/LibWeb/Rust/src/css/parser/mod.rs b/Libraries/LibWeb/Rust/src/css/parser/mod.rs
index 51655cc5f66..0bdfe67c76b 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/mod.rs
@@ -5,7 +5,6 @@
*/
pub(crate) mod arbitrary_substitution;
-#[cfg_attr(not(test), expect(dead_code, reason = "the parser does not read the lexer yet"))]
pub(crate) mod block;
pub(crate) mod calc_parser;
pub(crate) mod color_parser;
@@ -14,7 +13,6 @@ pub(crate) mod descriptor_parser;
pub(crate) mod fonts_parser;
pub(crate) mod grid_parser;
pub(crate) mod images_gradients_parser;
-#[expect(dead_code, reason = "the parser does not read the lexer yet")]
pub(crate) mod lexer;
#[cfg(test)]
mod memory_tests;
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
index 0d5cd665304..4ba3d29cea5 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
@@ -9,8 +9,7 @@ use crate::css::counter_style::{CounterStyleData, FfiCounterStyle};
use crate::css::css_enums::{keyword_from_ascii_case_insensitive, keyword_to_generic_font_family};
use crate::css::css_string::CssString;
use crate::css::css_tokenizer::{
- CssNumberType, ParserString, ParserToken, ParserTokenFeed, ParserTokenKind, SourcePosition, TokenizerInput,
- tokenize_for_parser,
+ CssNumberType, ParserString, ParserTokenKind, SourcePosition, TokenizerInput, tokenize_for_parser,
};
use crate::css::declaration_block::{
DeclarationBlock, DeclarationBlockBuilder, DeclaredProperty, SharedDeclarationBlock,
@@ -30,8 +29,7 @@ use crate::css::parser::arbitrary_substitution::{
ArbitrarySubstitutionFunction, arbitrary_substitution_function, arguments_are_valid, declaration_value_is_valid,
};
use crate::css::parser::component_value::{
- ComponentKind, ComponentSerializationMode, ComponentValue, ParserTokens, consume_a_component_value,
- consume_a_list_of_component_values, trim_whitespace,
+ ComponentKind, ComponentSerializationMode, ComponentValue, consume_a_list_of_component_values, trim_whitespace,
};
use crate::css::parser::descriptor_parser::parse_descriptor;
use crate::css::parser::query_parser::{
@@ -70,10 +68,13 @@ use std::rc::Rc;
use std::sync::Arc;
mod shared_rules;
+mod structure;
#[cfg(test)]
mod ownership_tests;
pub(crate) use shared_rules::{ParsedRuleList, SharedRule};
+pub(crate) use structure::DeclarationValue;
+use structure::{Parser, source_of};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
@@ -171,7 +172,7 @@ pub(crate) struct QualifiedRule {
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Declaration {
pub name: ParserString,
- pub value: Vec<ComponentValue>,
+ pub value: DeclarationValue,
pub important: bool,
pub source_position: SourcePosition,
pub is_property: bool,
@@ -968,12 +969,13 @@ fn parse_property_prelude(rule: &AtRule, context: &ParseContext) -> ParsedRulePr
let mut initial_value_source = None;
let mut initial_value_is_invalid = false;
for declaration in at_rule_declarations(rule) {
- let source = component_list_source(&declaration.value);
+ let source = declaration.value.text();
+ let declaration_values = declaration.value.component_values();
if parse_descriptor(
context,
2,
declaration.name.as_ref(),
- &declaration.value,
+ &declaration_values,
source.as_ref(),
)
.is_none()
@@ -982,15 +984,15 @@ fn parse_property_prelude(rule: &AtRule, context: &ParseContext) -> ParsedRulePr
// initial value. It is not computationally independent, so it makes the rule invalid.
if equals_ascii_case_insensitive(declaration.name.as_ref(), b"initial-value")
&& !declaration.important
- && declaration_value_is_valid(&declaration.value)
- && initial_value_contains_variable_reference(&declaration.value) == Some(true)
+ && declaration_value_is_valid(&declaration_values)
+ && initial_value_contains_variable_reference(&declaration_values) == Some(true)
{
initial_value_is_invalid = true;
}
continue;
}
if equals_ascii_case_insensitive(declaration.name.as_ref(), b"syntax") {
- let values = non_whitespace(&declaration.value);
+ let values = non_whitespace(&declaration_values);
syntax_source = values
.as_slice()
.first()
@@ -998,7 +1000,7 @@ fn parse_property_prelude(rule: &AtRule, context: &ParseContext) -> ParsedRulePr
.filter(|_| values.len() == 1)
.map(|source| source.to_vec().into_boxed_slice().into());
} else if equals_ascii_case_insensitive(declaration.name.as_ref(), b"inherits") {
- let values = non_whitespace(&declaration.value);
+ let values = non_whitespace(&declaration_values);
inherits = values
.as_slice()
.first()
@@ -1016,7 +1018,7 @@ fn parse_property_prelude(rule: &AtRule, context: &ParseContext) -> ParsedRulePr
} else if equals_ascii_case_insensitive(declaration.name.as_ref(), b"initial-value") {
initial_value_is_invalid = false;
initial_value_source = Some(serialize_component_values_to_utf16(
- &declaration.value,
+ &declaration_values,
ComponentSerializationMode::Retokenize,
));
}
@@ -1155,63 +1157,6 @@ where
}
}
-struct Parser {
- tokens: TokenWindow,
- position: usize,
- rule_context: Vec<RuleContext>,
- rule_names: Vec<Option<ParserString>>,
-}
-
-// How many tokens a feed adds to a token window at once.
-const TOKEN_WINDOW_CHUNK_SIZE: usize = 256;
-
-// The tokens a parser reads: all of its source's tokens, or a window of them that a feed extends as the parser reads
-// past its end.
-struct TokenWindow {
- tokens: Vec<ParserToken>,
- feed: Option<ParserTokenFeed>,
- // The diagnostics for the tokens the feed has added so far.
- diagnostics: Vec<FfiSyntaxDiagnostic>,
-}
-
-impl TokenWindow {
- fn fill_through(&mut self, index: usize) {
- while index >= self.tokens.len()
- && let Some(feed) = &mut self.feed
- {
- let first = self.tokens.len();
- if !feed.fill(&mut self.tokens, TOKEN_WINDOW_CHUNK_SIZE) {
- self.feed = None;
- return;
- }
- self.diagnostics.extend(token_diagnostics(&self.tokens[first..]));
- }
- }
-
- // Drops the tokens before position, which the parser never reads again, and returns where position then is. Only
- // a window that a feed extends drops any, and only a chunk's worth or more at once — so moving its unread tokens to
- // the front never costs more than their tokenization did.
- fn discard_before(&mut self, position: usize) -> usize {
- if self.feed.is_none() || position < TOKEN_WINDOW_CHUNK_SIZE {
- return position;
- }
- self.tokens.drain(..position);
- 0
- }
-}
-
-impl ParserTokens for TokenWindow {
- fn token(&mut self, index: usize) -> Option<&ParserToken> {
- self.fill_through(index);
- self.tokens.get(index)
- }
-
- fn token_mut(&mut self, index: usize) -> Option<&mut ParserToken> {
- self.fill_through(index);
- self.tokens.get_mut(index)
- }
-}
-
fn equals_ascii_case_insensitive(value: &[u16], expected: &[u8]) -> bool {
value.len() == expected.len()
&& value
@@ -1486,560 +1431,20 @@ fn context_for_at_rule(name: &[u16]) -> RuleContext {
}
}
-impl Parser {
- fn style_nesting_parent(&self) -> StyleNestingParent {
- self.rule_context
- .iter()
- .rev()
- .find_map(|context| match context {
- RuleContext::Style => Some(StyleNestingParent::Style),
- RuleContext::AtScope => Some(StyleNestingParent::Scope),
- _ => None,
- })
- .unwrap_or(StyleNestingParent::None)
- }
-
- fn new(tokens: Vec<ParserToken>, rule_context: Vec<RuleContext>) -> Self {
- let rule_names = rule_context.iter().copied().map(context_rule_name).collect();
- Self {
- tokens: TokenWindow {
- tokens,
- feed: None,
- diagnostics: Vec::new(),
- },
- position: 0,
- rule_context,
- rule_names,
- }
- }
-
- // A parser that tokenizes its source only as far as it reads, for a style sheet's contents.
- fn streaming<'a>(source: impl Into<TokenizerInput<'a>>) -> Self {
- let mut parser = Self::new(Vec::new(), Vec::new());
- parser.tokens.feed = Some(ParserTokenFeed::new(source.into()));
- parser
- }
-
- fn from_source<'a>(
- source: impl Into<TokenizerInput<'a>>,
- rule_context: Vec<RuleContext>,
- ) -> (Self, Vec<FfiSyntaxDiagnostic>) {
- let tokens = tokenize_for_parser(source);
- let diagnostics = token_diagnostics(&tokens);
- (Self::new(tokens, rule_context), diagnostics)
- }
-
- fn next_kind(&mut self) -> Option<&ParserTokenKind> {
- self.tokens.token(self.position).map(|token| &token.kind)
- }
-
- fn peek_kind(&mut self, offset: usize) -> Option<&ParserTokenKind> {
- self.tokens.token(self.position + offset).map(|token| &token.kind)
- }
-
- fn discard_whitespace(&mut self) {
- while matches!(self.next_kind(), Some(ParserTokenKind::Whitespace)) {
- self.position += 1;
- }
- }
-
- fn consume_component_value(&mut self) -> Result<ComponentValue, ()> {
- consume_a_component_value(&mut self.tokens, &mut self.position, 0, true)
- }
-
- fn clone_component_value(&mut self) -> Result<ComponentValue, ()> {
- consume_a_component_value(&mut self.tokens, &mut self.position, 0, false)
- }
-
- fn declaration_can_take_tokens(&mut self) -> bool {
- let mut nesting_depth = 0usize;
- let mut index = self.position;
- while let Some(token) = self.tokens.token(index) {
- index += 1;
- match token.kind {
- ParserTokenKind::Function(_) | ParserTokenKind::OpenSquare | ParserTokenKind::OpenParen => {
- nesting_depth += 1;
- }
- ParserTokenKind::OpenCurly if nesting_depth == 0 => return false,
- ParserTokenKind::OpenCurly => nesting_depth += 1,
- ParserTokenKind::CloseSquare | ParserTokenKind::CloseParen | ParserTokenKind::CloseCurly
- if nesting_depth > 0 =>
- {
- nesting_depth -= 1;
- }
- ParserTokenKind::Semicolon | ParserTokenKind::CloseCurly if nesting_depth == 0 => break,
- _ => {}
- }
- }
- true
- }
-
- fn consume_component_values_until(
- &mut self,
- stop: Option<&ParserTokenKind>,
- nested: Nested,
- take_tokens: bool,
- ) -> Vec<ComponentValue> {
- let mut values = Vec::with_capacity(4);
- while let Some(kind) = self.next_kind() {
- if stop.is_some_and(|stop| std::mem::discriminant(kind) == std::mem::discriminant(stop))
- || nested == Nested::Yes && matches!(kind, ParserTokenKind::CloseCurly)
- {
- break;
- }
- let value = if take_tokens {
- self.consume_component_value()
- } else {
- self.clone_component_value()
- };
- let Ok(value) = value else {
- break;
- };
- values.push(value);
- }
- values
- }
-
- // https://drafts.csswg.org/css-syntax-3/#consume-stylesheet-contents
- // OPTIMIZATION: Returns the next rule of the list that algorithm builds, or None once the input is exhausted — so a
- // caller can process each rule and drop its component values before the next one is consumed, rather than holding
- // the component values of the whole sheet at once.
- fn consume_next_stylesheet_rule(&mut self) -> Option<Rule> {
- self.position = self.tokens.discard_before(self.position);
- loop {
- match self.next_kind() {
- Some(ParserTokenKind::Whitespace | ParserTokenKind::Cdo | ParserTokenKind::Cdc) => self.position += 1,
- None => return None,
- Some(ParserTokenKind::AtKeyword(_)) => {
- if let Some(rule) = self.consume_at_rule(Nested::No) {
- return Some(Rule::At(rule));
- }
- }
- _ => {
- if let Ok(rule) = self.consume_qualified_rule(None, Nested::No) {
- return Some(Rule::Qualified(rule));
- }
- }
- }
- }
- }
-
- // https://drafts.csswg.org/css-syntax-3/#consume-at-rule
- fn consume_at_rule(&mut self, nested: Nested) -> Option<AtRule> {
- let ParserTokenKind::AtKeyword(name) = self.next_kind()?.clone() else {
- return None;
- };
- self.position += 1;
- let mut rule = AtRule {
- name,
- prelude: Vec::with_capacity(4),
- children: Vec::new(),
- has_block: false,
- nesting_parent: self.style_nesting_parent(),
- valid_in_context: false,
- outer_rule_name: self.rule_names.last().cloned().flatten(),
- };
- loop {
- match self.next_kind() {
- None | Some(ParserTokenKind::Semicolon) => {
- self.position += usize::from(self.next_kind().is_some());
- rule.valid_in_context = self.at_rule_is_valid(&rule);
- return Some(rule);
- }
- Some(ParserTokenKind::CloseCurly) if nested == Nested::Yes => {
- rule.valid_in_context = self.at_rule_is_valid(&rule);
- return Some(rule);
- }
- Some(ParserTokenKind::OpenCurly) => {
- let context = context_for_at_rule(rule.name.as_ref());
- self.rule_context.push(context);
- self.rule_names.push(Some(at_rule_name(rule.name.as_ref())));
- rule.children = self.consume_block();
- self.rule_names.pop();
- self.rule_context.pop();
- rule.has_block = true;
- rule.valid_in_context = self.at_rule_is_valid(&rule);
- return Some(rule);
- }
- _ => rule.prelude.push(self.consume_component_value().ok()?),
- }
- }
- }
-
- // https://drafts.csswg.org/css-syntax-3/#consume-qualified-rule
- fn consume_qualified_rule(
- &mut self,
- stop: Option<&ParserTokenKind>,
- nested: Nested,
- ) -> Result<QualifiedRule, QualifiedRuleResult> {
- let qualified_context = if self.rule_context.last() == Some(&RuleContext::AtKeyframes) {
- RuleContext::Keyframe
- } 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,
- };
- loop {
- let Some(kind) = self.next_kind() else {
- return Err(QualifiedRuleResult::Invalid);
- };
- if stop.is_some_and(|stop| std::mem::discriminant(kind) == std::mem::discriminant(stop)) {
- return Err(QualifiedRuleResult::Invalid);
- }
- match kind {
- ParserTokenKind::CloseCurly if nested == Nested::Yes => return Err(QualifiedRuleResult::Invalid),
- ParserTokenKind::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);
- } else {
- self.consume_block();
- }
- return Err(QualifiedRuleResult::Invalid);
- }
- self.rule_context.push(qualified_context);
- self.rule_names.push(context_rule_name(qualified_context));
- rule.children = self.consume_block();
- self.rule_names.pop();
- self.rule_context.pop();
- if matches!(rule.children.first(), Some(RuleOrDeclarations::Declarations(_))) {
- let RuleOrDeclarations::Declarations(declarations) = rule.children.remove(0) else {
- unreachable!();
- };
- rule.declarations = declarations;
- }
- rule.valid_in_context = self.qualified_rule_is_valid();
- return Ok(rule);
- }
- _ => {
- let value = self
- .consume_component_value()
- .map_err(|()| QualifiedRuleResult::Invalid)?;
- if rule.source_position.is_none() && !value.is_whitespace() {
- rule.source_position = Some(value.start_position);
- }
- rule.prelude.push(value);
- }
- }
- }
- }
-
- // https://drafts.csswg.org/css-syntax-3/#consume-block
- fn consume_block(&mut self) -> Vec<RuleOrDeclarations> {
- debug_assert!(matches!(self.next_kind(), Some(ParserTokenKind::OpenCurly)));
- self.position += 1;
- let result = self.consume_block_contents();
- self.position += usize::from(matches!(self.next_kind(), Some(ParserTokenKind::CloseCurly)));
- result
- }
-
- // https://drafts.csswg.org/css-syntax-3/#consume-block-contents
- fn consume_block_contents(&mut self) -> Vec<RuleOrDeclarations> {
- let mut result = Vec::with_capacity(4);
- let mut declarations = Vec::with_capacity(8);
- loop {
- match self.next_kind() {
- Some(ParserTokenKind::Whitespace | ParserTokenKind::Semicolon) => self.position += 1,
- None | Some(ParserTokenKind::CloseCurly) => {
- if !declarations.is_empty() {
- result.push(RuleOrDeclarations::Declarations(declarations));
- }
- return result;
- }
- Some(ParserTokenKind::AtKeyword(_)) => {
- if !declarations.is_empty() {
- result.push(RuleOrDeclarations::Declarations(std::mem::take(&mut declarations)));
- }
- if let Some(rule) = self.consume_at_rule(Nested::Yes) {
- result.push(RuleOrDeclarations::Rule(Rule::At(rule)));
- }
- }
- _ => {
- let could_be_declaration = matches!(self.next_kind(), Some(ParserTokenKind::Ident(_))) && {
- let mut lookahead = 1;
- while matches!(self.peek_kind(lookahead), Some(ParserTokenKind::Whitespace)) {
- lookahead += 1;
- }
- matches!(self.peek_kind(lookahead), Some(ParserTokenKind::Colon))
- };
- let start = self.position;
- if could_be_declaration && let Some(declaration) = self.consume_declaration(Nested::Yes) {
- declarations.push(declaration);
- continue;
- }
- self.position = start;
- match self.consume_qualified_rule(Some(&ParserTokenKind::Semicolon), Nested::Yes) {
- Ok(rule) => {
- if !declarations.is_empty() {
- result.push(RuleOrDeclarations::Declarations(std::mem::take(&mut declarations)));
- }
- result.push(RuleOrDeclarations::Rule(Rule::Qualified(rule)));
- }
- Err(QualifiedRuleResult::Invalid) => {
- self.position += usize::from(matches!(self.next_kind(), Some(ParserTokenKind::Semicolon)));
- }
- }
- }
- }
- }
- }
-
- // https://drafts.csswg.org/css-syntax-3/#consume-declaration
- fn consume_declaration(&mut self, nested: Nested) -> Option<Declaration> {
- let token = self.tokens.token(self.position)?.clone();
- let ParserTokenKind::Ident(name) = token.kind else {
- self.consume_bad_declaration(nested);
- return None;
- };
- self.position += 1;
- self.discard_whitespace();
- if !matches!(self.next_kind(), Some(ParserTokenKind::Colon)) {
- self.consume_bad_declaration(nested);
- return None;
- }
- self.position += 1;
- self.discard_whitespace();
- let can_take_tokens = self.declaration_can_take_tokens();
- let mut value = self.consume_component_values_until(Some(&ParserTokenKind::Semicolon), nested, can_take_tokens);
-
- let mut important = false;
- if value.len() >= 2 {
- let mut important_index = None;
- for index in (1..value.len()).rev() {
- if value[index]
- .ident()
- .is_some_and(|ident| equals_ascii_case_insensitive(ident, b"important"))
- {
- important_index = Some(index);
- break;
- }
- if !value[index].is_whitespace() {
- break;
- }
- }
- if let Some(important_index) = important_index {
- let mut bang_index = None;
- for index in (0..important_index).rev() {
- if value[index].is_delim(b'!') {
- bang_index = Some(index);
- break;
- }
- if !value[index].is_whitespace() {
- break;
- }
- }
- if let Some(bang_index) = bang_index {
- value.remove(important_index);
- value.remove(bang_index);
- important = true;
- }
- }
- }
- while value.last().is_some_and(ComponentValue::is_whitespace) {
- value.pop();
- }
-
- let is_custom_property = starts_with_ascii(name.as_ref(), b"--");
- if is_custom_property && name.as_ref().len() == 2 {
- return None;
- }
- // INTEROP: The initial-value descriptor accepts arbitrary component values, including mixed curly blocks.
- let is_initial_value_descriptor = self.rule_context.last() == Some(&RuleContext::AtProperty)
- && equals_ascii_case_insensitive(name.as_ref(), b"initial-value");
- if !is_custom_property && !is_initial_value_descriptor {
- let mut contains_curly = false;
- let mut contains_non_whitespace = false;
- for component in &value {
- if matches!(
- component.kind,
- ComponentKind::SimpleBlock {
- opening: ParserTokenKind::OpenCurly,
- ..
- }
- ) {
- if contains_non_whitespace {
- return None;
- }
- contains_curly = true;
- } else if !component.is_whitespace() {
- if contains_curly {
- return None;
- }
- contains_non_whitespace = true;
- }
- }
- }
- if !self.declaration_is_valid(name.as_ref()) {
- return None;
- }
- let is_property = self.declaration_is_property();
- let rule_context = if !is_property && self.rule_context.contains(&RuleContext::AtFunction) {
- RuleContext::AtFunction
- } else {
- self.rule_context.last().copied().unwrap_or(RuleContext::Unknown)
- };
- Some(Declaration {
- name,
- value,
- important,
- source_position: token.start_position,
- is_property,
- rule_context,
- })
- }
-
- fn consume_bad_declaration(&mut self, nested: Nested) {
- loop {
- match self.next_kind() {
- None | Some(ParserTokenKind::Semicolon) => {
- self.position += usize::from(self.next_kind().is_some());
- return;
- }
- Some(ParserTokenKind::CloseCurly) if nested == Nested::Yes => return,
- _ => {
- if self.consume_component_value().is_err() {
- return;
- }
- }
- }
- }
- }
-
- fn declaration_is_valid(&self, name: &[u16]) -> bool {
- let Some(context) = self.rule_context.last() else {
- return false;
- };
- match context {
- RuleContext::Unknown | RuleContext::AtKeyframes => false,
- RuleContext::Keyframe => ![
- b"animation".as_slice(),
- b"animation-delay",
- b"animation-direction",
- b"animation-duration",
- b"animation-fill-mode",
- b"animation-iteration-count",
- b"animation-name",
- b"animation-play-state",
- b"animation-timeline",
- ]
- .iter()
- .any(|property| equals_ascii_case_insensitive(name, property)),
- RuleContext::AtContainer | RuleContext::AtLayer | RuleContext::AtMedia | RuleContext::AtSupports => self
- .rule_context
- .iter()
- .any(|context| matches!(context, RuleContext::Style | RuleContext::AtFunction)),
- RuleContext::AtPositionTry => property_id_from_name(name).is_some_and(is_accepted_position_try_property),
- _ => true,
- }
- }
-
- fn declaration_is_property(&self) -> bool {
- match self.rule_context.last() {
- Some(
- RuleContext::Style
- | RuleContext::Keyframe
- | RuleContext::AtScope
- | RuleContext::Margin
- | RuleContext::AtPositionTry,
- ) => true,
- Some(RuleContext::AtContainer | RuleContext::AtLayer | RuleContext::AtMedia | RuleContext::AtSupports) => {
- self.rule_context.contains(&RuleContext::Style)
- }
- _ => false,
- }
- }
-
- fn at_rule_is_valid(&self, rule: &AtRule) -> bool {
- let name = rule.name.as_ref();
- // NB: Margin and font feature value rules are only meaningful inside @page and
- // @font-feature-values. The C++ converter dropped them anywhere else, so they must not
- // count as valid rules for the top-level @import and @namespace ordering windows.
- if self.rule_context.is_empty() {
- return !is_margin_rule_name(name) && !is_font_feature_value_rule_name(name);
- }
- if self.rule_context.contains(&RuleContext::Style) {
- return [b"container".as_slice(), b"layer", b"media", b"scope", b"supports"]
- .iter()
- .any(|expected| equals_ascii_case_insensitive(name, expected));
- }
- if self.rule_context.contains(&RuleContext::AtFunction) {
- return [b"container".as_slice(), b"media", b"supports"]
- .iter()
- .any(|expected| equals_ascii_case_insensitive(name, expected));
- }
- match self.rule_context.last().unwrap() {
- RuleContext::AtContainer
- | RuleContext::AtLayer
- | RuleContext::AtMedia
- | RuleContext::AtScope
- | RuleContext::AtSupports => {
- !equals_ascii_case_insensitive(name, b"import")
- && !equals_ascii_case_insensitive(name, b"namespace")
- && !is_font_feature_value_rule_name(name)
- }
- RuleContext::AtPage => is_margin_rule_name(name),
- RuleContext::AtFontFeatureValues => is_font_feature_value_rule_name(name),
- _ => false,
- }
- }
-
- fn qualified_rule_is_valid(&self) -> bool {
- matches!(
- self.rule_context.last(),
- None | Some(
- RuleContext::Style
- | RuleContext::AtContainer
- | RuleContext::AtLayer
- | RuleContext::AtMedia
- | RuleContext::AtScope
- | RuleContext::AtSupports
- | RuleContext::AtKeyframes
- )
- )
- }
-}
-
#[cfg(test)]
pub(crate) fn parse_stylesheet<'a>(source: impl Into<TokenizerInput<'a>>) -> Vec<Rule> {
- let mut parser = Parser::streaming(source);
+ let source = source_of(source.into());
+ let mut parser = Parser::new(&source, Vec::new());
std::iter::from_fn(|| parser.consume_next_stylesheet_rule()).collect()
}
-fn parse_rule_from_tokens(tokens: Vec<ParserToken>, rule_context: Vec<RuleContext>, nested: bool) -> Option<Rule> {
- let mut parser = Parser::new(tokens, rule_context);
- let nested = if nested { Nested::Yes } else { Nested::No };
- parser.discard_whitespace();
- let rule = match parser.next_kind() {
- None => return None,
- Some(ParserTokenKind::AtKeyword(_)) => Rule::At(parser.consume_at_rule(nested)?),
- _ => Rule::Qualified(parser.consume_qualified_rule(None, nested).ok()?),
- };
- parser.discard_whitespace();
- parser.next_kind().is_none().then_some(rule)
-}
-
#[cfg(test)]
pub(crate) fn parse_rule<'a>(
source: impl Into<TokenizerInput<'a>>,
rule_context: Vec<RuleContext>,
nested: bool,
) -> Option<Rule> {
- let (parser, _) = Parser::from_source(source, rule_context);
- parse_rule_from_tokens(parser.tokens.tokens, parser.rule_context, nested)
+ Parser::new(&source_of(source.into()), rule_context).consume_only_rule(nested)
}
#[cfg(test)]
@@ -2047,12 +1452,12 @@ pub(crate) fn parse_block_contents<'a>(
source: impl Into<TokenizerInput<'a>>,
rule_context: Vec<RuleContext>,
) -> Vec<RuleOrDeclarations> {
- Parser::from_source(source, rule_context).0.consume_block_contents()
+ Parser::new(&source_of(source.into()), rule_context).consume_block_contents()
}
pub(crate) fn supports_declaration_matches(context: &ParseContext, source: &[u16]) -> bool {
- let (mut parser, _) = Parser::from_source(source, vec![RuleContext::SupportsCondition]);
- let items = parser.consume_block_contents();
+ let source = source_of(source.into());
+ let items = Parser::new(&source, vec![RuleContext::SupportsCondition]).consume_block_contents();
let [RuleOrDeclarations::Declarations(declarations)] = items.as_slice() else {
return false;
};
@@ -2063,7 +1468,8 @@ pub(crate) fn supports_declaration_matches(context: &ParseContext, source: &[u16
return false;
};
- let source = component_list_source(&declaration.value);
+ let source = declaration.value.text();
+ let values = declaration.value.component_values();
let property_context = FfiValueParsingContext {
kind: FfiValueParsingContextKind::Property,
value: property_id,
@@ -2074,7 +1480,7 @@ pub(crate) fn supports_declaration_matches(context: &ParseContext, source: &[u16
value_context.is_ua_style_sheet = false;
value_context.value_contexts = ak::Span::new(std::slice::from_ref(&property_context));
value_context.length_resolution_context = None;
- let outcome = parse_css_value_with_utf16_source(&value_context, property_id, &declaration.value, source.as_ref());
+ let outcome = parse_css_value_with_utf16_source(&value_context, property_id, &values, source.as_ref());
if let Some(random_function_index) = context.random_function_index {
random_function_index.set(0);
}
@@ -2482,21 +1888,22 @@ struct SyntaxParseBuilder<'a> {
parent: Cell<Option<NestingTarget>>,
}
-/// What was parsed for each key, by the key's hash.
-type DedupBuckets<T> = std::collections::HashMap<u64, Vec<(std::ops::Range<usize>, T)>>;
-
/// Lets the declarations and declaration blocks a sheet repeats share one parse, for the length of the sheet's parse.
/// Most of a large sheet's declarations repeat earlier ones: of YouTube's 83k declarations, 11k are distinct, and so
/// are 13k of its 24k blocks. Within one sheet, the same text parses the same way.
#[derive(Default)]
struct DeclarationDedup {
- /// Each declaration's name and value, each after its length, then whether it is important. The lengths keep the
- /// keys of two different declarations, or runs of declarations, from being equal.
- keys: Vec<u16>,
- /// The range of `keys` for each declaration, by index; `None` for one that is never shared.
- declaration_keys: Vec<Option<std::ops::Range<usize>>>,
- values: DedupBuckets<ParsedDeclarationValue>,
- blocks: DedupBuckets<SharedDeclarationBlock>,
+ /// What each declaration text parsed to, by the hash of the text. A text is the name and the value of a declaration
+ /// as the source has them, and the declarations with one text have one number, which is its index in the order the
+ /// texts came in.
+ values: std::collections::HashMap<u64, Vec<(DeclarationValue, u32, ParsedDeclarationValue)>>,
+ text_count: u32,
+ /// For each declaration, by index: twice the number of its text, plus one if it is important. `UNSHARED` for one
+ /// that is never shared.
+ declaration_keys: Vec<u32>,
+ /// The blocks that runs of declarations made, by the hash of the keys of the run. Each is with where the
+ /// declarations of the run that made it are.
+ blocks: std::collections::HashMap<u64, Vec<(std::ops::Range<usize>, SharedDeclarationBlock)>>,
/// The values the sheet's declarations parsed to, by their content's hash, so that declarations
/// of different properties, or differently written, that parse to the same value hold one
/// allocation of it.
@@ -2509,17 +1916,7 @@ struct DeclarationDedup {
}
impl DeclarationDedup {
- fn hash(&self, key: &std::ops::Range<usize>) -> u64 {
- use std::hash::BuildHasher;
- self.hasher.hash_one(&self.keys[key.clone()])
- }
-
- fn push_with_length(&mut self, units: &[u16]) {
- let length = u32::try_from(units.len()).expect("declaration text length exceeds u32");
- self.keys.push((length >> 16) as u16);
- self.keys.push(length as u16);
- self.keys.extend_from_slice(units);
- }
+ const UNSHARED: u32 = u32::MAX;
/// The allocation of a value equal to `value` the sheet already holds, or `value` itself, which
/// later equal values then share.
@@ -2532,31 +1929,22 @@ impl DeclarationDedup {
value.clone()
}
- fn find<'a, T>(&self, candidates: &'a DedupBuckets<T>, hash: u64, key: &std::ops::Range<usize>) -> Option<&'a T> {
- candidates
- .get(&hash)?
- .iter()
- .find(|(candidate, _)| self.keys[candidate.clone()] == self.keys[key.clone()])
- .map(|(_, value)| value)
+ /// The keys of the `count` declarations from `start`, when all of them may be shared, and the hash of the keys.
+ fn block_key(&self, start: usize, count: usize) -> Option<(u64, &[u32])> {
+ use std::hash::BuildHasher;
+ if count == 0 {
+ return None;
+ }
+ let keys = self.declaration_keys.get(start..start + count)?;
+ if keys.contains(&Self::UNSHARED) {
+ return None;
+ }
+ Some((self.hasher.hash_one(keys), keys))
}
}
type ParsedDeclarationValue = (u16, u8, FfiDeclarationRejection, Option<StyleValueArc>);
-/// Whether parsing `values` may do more than produce a value, which sharing the result would skip: `attr()` records
-/// the attribute names it reads, and `random()` values have an identity of their own.
-fn value_may_not_be_shared(values: &[ComponentValue]) -> bool {
- values.iter().any(|value| match &value.kind {
- ComponentKind::Function { name, values } => {
- equals_ascii_case_insensitive(name, b"attr")
- || equals_ascii_case_insensitive(name, b"random")
- || value_may_not_be_shared(values)
- }
- ComponentKind::SimpleBlock { values, .. } => value_may_not_be_shared(values),
- ComponentKind::Token(_) => false,
- })
-}
-
// The shared graph owns typed Rust payloads, independently of any FFI views.
pub struct ParsedStyleSheet {
identity_count: u64,
@@ -2837,13 +2225,12 @@ fn collect_descriptors<'a>(
let Some(at_rule) = descriptor_at_rule(declaration.rule_context) else {
continue;
};
- let source = component_list_source(&declaration.value);
let Some(descriptor) = parse_descriptor(
context,
at_rule,
declaration.name.as_ref(),
- &declaration.value,
- source.as_ref(),
+ &declaration.value.component_values(),
+ declaration.value.text().as_ref(),
) else {
continue;
};
@@ -2891,6 +2278,7 @@ fn parse_font_feature_values(declaration: &Declaration, maximum_value_count: usi
}
let values = declaration
.value
+ .component_values()
.iter()
.filter(|value| !value.is_whitespace())
.map(|value| match value.kind {
@@ -3349,22 +2737,20 @@ impl<'a> SyntaxParseBuilder<'a> {
font_feature_maximum_value_count: Option<usize>,
) -> usize {
let (name_offset, name_length) = self.append_declaration_text(declaration.name.as_ref());
- let value_source = component_list_source(&declaration.value);
- let shareable = declaration.is_property && !value_may_not_be_shared(&declaration.value);
- let value_key = shareable.then(|| {
- let start = self.dedup.keys.len();
- self.dedup.push_with_length(declaration.name.as_ref());
- self.dedup.push_with_length(value_source.as_ref());
- let key = start..self.dedup.keys.len();
- (self.dedup.hash(&key), key)
+ let shareable = declaration.is_property && !declaration.value.may_not_be_shared;
+ let hash = shareable.then(|| declaration.value.hash_of_text(&self.dedup.hasher));
+ let shared_value = hash.and_then(|hash| {
+ self.dedup
+ .values
+ .get(&hash)?
+ .iter()
+ .find(|(text, ..)| text.is_same_text(&declaration.value))
+ .map(|(_, number, value)| (*number, value.clone()))
});
- let shared_value = value_key
- .as_ref()
- .and_then(|(hash, key)| self.dedup.find(&self.dedup.values, *hash, key).cloned());
- let (property_id, descriptor_id, rejection, parsed_value) = match shared_value {
- Some(value) => value,
+ let (text_number, (property_id, descriptor_id, rejection, parsed_value)) = match shared_value {
+ Some((number, value)) => (number, value),
None => {
- let mut value = self.parse_declaration_value(declaration, value_source.as_ref());
+ let mut value = self.parse_declaration_value(declaration);
// NB: A value taking part in a substitution keeps its own: it is resolved for the
// property declaring it, and the longhands a shorthand awaiting substitution
// expands to name it by identity.
@@ -3379,23 +2765,27 @@ impl<'a> SyntaxParseBuilder<'a> {
{
*parsed = self.dedup.intern_value(parsed);
}
- if let Some((hash, key)) = &value_key {
+ let number = self.dedup.text_count;
+ if let Some(hash) = hash {
+ self.dedup.text_count += 1;
self.dedup
.values
- .entry(*hash)
+ .entry(hash)
.or_default()
- .push((key.clone(), value.clone()));
+ .push((declaration.value.clone(), number, value.clone()));
}
- value
+ (number, value)
}
};
- let declaration_key = value_key.map(|(_, key)| {
- self.dedup.keys.push(u16::from(declaration.important));
- key.start..self.dedup.keys.len()
- });
+ let declaration_key = match hash {
+ Some(_) => text_number * 2 + u32::from(declaration.important),
+ None => DeclarationDedup::UNSHARED,
+ };
let declaration_index = self.declarations.len();
if self.dedup.declaration_keys.len() < declaration_index {
- self.dedup.declaration_keys.resize(declaration_index, None);
+ self.dedup
+ .declaration_keys
+ .resize(declaration_index, DeclarationDedup::UNSHARED);
}
self.dedup.declaration_keys.push(declaration_key);
let font_feature_values = font_feature_maximum_value_count
@@ -3410,7 +2800,7 @@ impl<'a> SyntaxParseBuilder<'a> {
};
let needs_value_text = self.preserve_property_source_text || rejection == FfiDeclarationRejection::InvalidValue;
let (value_source_offset, value_source_length) = if needs_value_text {
- self.append_declaration_text(value_source.as_ref())
+ self.append_declaration_text(&declaration.value.text())
} else {
(0, 0)
};
@@ -3438,7 +2828,6 @@ impl<'a> SyntaxParseBuilder<'a> {
fn parse_declaration_value(
&mut self,
declaration: &Declaration,
- source_utf16: &[u16],
) -> (u16, u8, FfiDeclarationRejection, Option<StyleValueArc>) {
let Some(parse_context) = self.parse_context else {
return (u16::MAX, u8::MAX, FfiDeclarationRejection::None, None);
@@ -3451,8 +2840,8 @@ impl<'a> SyntaxParseBuilder<'a> {
parse_context,
at_rule,
declaration.name.as_ref(),
- &declaration.value,
- source_utf16,
+ &declaration.value.component_values(),
+ &declaration.value.text(),
) {
Some(descriptor) => (
u16::MAX,
@@ -3484,7 +2873,12 @@ impl<'a> SyntaxParseBuilder<'a> {
let mut context = *parse_context;
context.value_contexts = ak::Span::new(&value_contexts);
- let outcome = parse_css_value_with_utf16_source(&context, property_id, &declaration.value, source_utf16);
+ let outcome = parse_css_value_with_utf16_source(
+ &context,
+ property_id,
+ &declaration.value.component_values(),
+ &declaration.value.text(),
+ );
if let Some(random_function_index) = parse_context.random_function_index {
random_function_index.set(0);
}
@@ -3598,25 +2992,6 @@ impl<'a> SyntaxParseBuilder<'a> {
}
}
- /// The range of dedup keys spanning `count` declarations from `start`, when all of them may be shared.
- fn declaration_block_key(&self, start: usize, count: usize) -> Option<std::ops::Range<usize>> {
- if count == 0 {
- return None;
- }
- let keys = self.dedup.declaration_keys.get(start..start + count)?;
- let first = keys.first()?.as_ref()?.start;
- let mut end = first;
- for key in keys {
- let key = key.as_ref()?;
- // The keys of one block are appended one after the other.
- if key.start != end {
- return None;
- }
- end = key.end;
- }
- Some(first..end)
- }
-
fn next_identity(&mut self) -> u64 {
let identity = self.identity_count;
self.identity_count = identity.checked_add(1).expect("parsed rule identity overflow");
@@ -3747,7 +3122,6 @@ impl<'a> SyntaxParseBuilder<'a> {
rule.source_position,
),
};
- let prelude_source = component_list_source(prelude);
let font_feature_maximum_value_count = match rule {
Rule::At(rule) => font_feature_values_rule(rule.name.as_ref()).map(|(_, maximum)| maximum),
Rule::Qualified(_) => None,
@@ -3807,6 +3181,7 @@ 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);
self.append_rule_validation_diagnostic(rule, original_rule_kind, code, prelude_source.as_ref());
ParsedRuleKind::Invalid
} else {
@@ -3984,13 +3359,17 @@ impl<'a> SyntaxParseBuilder<'a> {
// NB: A style rule's block is its own declarations, so the same text gives the same block.
let block_key = qualified_rule
.prelude_is_selector
- .then(|| self.declaration_block_key(declarations_start, declaration_count))
- .flatten()
- .map(|key| (self.dedup.hash(&key), key));
- if let Some(shared) = block_key
- .as_ref()
- .and_then(|(hash, key)| self.dedup.find(&self.dedup.blocks, *hash, key))
- {
+ .then(|| self.dedup.block_key(declarations_start, declaration_count))
+ .flatten();
+ let block_hash = block_key.map(|(hash, _)| hash);
+ if let Some(shared) = block_key.and_then(|(hash, keys)| {
+ self.dedup
+ .blocks
+ .get(&hash)?
+ .iter()
+ .find(|(run, _)| self.dedup.declaration_keys[run.clone()] == *keys)
+ .map(|(_, block)| block)
+ }) {
Some(shared.clone())
} else {
let mut block = DeclarationBlockBuilder::default();
@@ -4009,8 +3388,11 @@ impl<'a> SyntaxParseBuilder<'a> {
}
}
let block = block.finish();
- if let Some((hash, key)) = block_key {
- self.dedup.blocks.entry(hash).or_default().push((key, block.clone()));
+ if let Some(hash) = block_hash {
+ self.dedup.blocks.entry(hash).or_default().push((
+ declarations_start..declarations_start + declaration_count,
+ block.clone(),
+ ));
}
Some(block)
}
@@ -4203,32 +3585,6 @@ impl<'a> SyntaxParseBuilder<'a> {
}
}
-fn token_diagnostics(tokens: &[ParserToken]) -> Vec<FfiSyntaxDiagnostic> {
- tokens
- .iter()
- .filter_map(|token| {
- let code = match &token.kind {
- ParserTokenKind::BadString => FfiSyntaxDiagnosticCode::BadString,
- ParserTokenKind::BadUrl => FfiSyntaxDiagnosticCode::BadUrl,
- _ => return None,
- };
- Some(FfiSyntaxDiagnostic {
- code,
- start_line: token.start_position.line,
- start_column: token.start_position.column,
- end_line: token.end_position.line,
- end_column: token.end_position.column,
- primary_offset: usize::MAX,
- primary_length: 0,
- secondary_offset: usize::MAX,
- secondary_length: 0,
- prelude_offset: usize::MAX,
- prelude_length: 0,
- })
- })
- .collect()
-}
-
pub(crate) fn parse_shared_stylesheet(
source: TokenizerInput<'_>,
parse_context: Option<&ParseContext<'_>>,
@@ -4243,13 +3599,14 @@ pub(crate) fn parse_stylesheet_uncached(
source: TokenizerInput<'_>,
parse_context: Option<&ParseContext<'_>>,
) -> ParsedStyleSheet {
- let mut parser = Parser::streaming(source);
+ let text = source_of(source);
+ let mut parser = Parser::new(&text, Vec::new());
let mut parse = SyntaxParseBuilder::new(parse_context, false);
while let Some(rule) = parser.consume_next_stylesheet_rule() {
parse.append_root(&rule);
}
- // As in every other parse, the tokens' own diagnostics come ahead of the rules'.
- parse.diagnostics.splice(0..0, parser.tokens.diagnostics);
+ // The tokens' own diagnostics come ahead of the rules'.
+ parse.diagnostics.splice(0..0, parser.token_diagnostics());
let mut parsed = parse.finish();
parsed.source_text = SheetSourceText::new(source);
parsed
@@ -4328,16 +3685,16 @@ pub(crate) fn parse_shared_rule(
nested: bool,
parse_context: Option<&ParseContext<'_>>,
) -> Arc<ParsedStyleSheet> {
- let (parser, diagnostics) = Parser::from_source(source, contexts);
+ let source = source_of(source);
+ let mut parser = Parser::new(&source, contexts);
let mut parse = SyntaxParseBuilder::new(parse_context, false);
- if parser.rule_context.contains(&RuleContext::AtFunction) {
+ if parser.rule_context().contains(&RuleContext::AtFunction) {
parse.declarations_kind = NestedDeclarationsKind::Function;
}
- parse.diagnostics = diagnostics;
- let rule = parse_rule_from_tokens(parser.tokens.tokens, parser.rule_context, nested);
- if let Some(rule) = rule {
+ if let Some(rule) = parser.consume_only_rule(nested) {
parse.append_root(&rule);
}
+ parse.diagnostics.splice(0..0, parser.token_diagnostics());
Arc::new(parse.finish())
}
@@ -4485,14 +3842,15 @@ pub(crate) fn parse_shared_block(
parse_context: Option<&ParseContext<'_>>,
preserve_property_source_text: bool,
) -> Arc<ParsedStyleSheet> {
- let (mut parser, diagnostics) = Parser::from_source(source, contexts);
+ let source = source_of(source);
+ let mut parser = Parser::new(&source, contexts);
let mut parse = SyntaxParseBuilder::new(parse_context, preserve_property_source_text);
- if parser.rule_context.contains(&RuleContext::AtFunction) {
+ if parser.rule_context().contains(&RuleContext::AtFunction) {
parse.declarations_kind = NestedDeclarationsKind::Function;
}
- parse.diagnostics = diagnostics;
let items = parser.consume_block_contents();
parse.append_root_items(&items);
+ parse.diagnostics.splice(0..0, parser.token_diagnostics());
Arc::new(parse.finish())
}
@@ -4504,12 +3862,12 @@ pub extern "C" fn rust_css_syntax_parse_free(parse: OwnedArc<ParsedStyleSheet>)
#[cfg(test)]
mod tests {
use super::{
- Declaration, FfiSyntaxDiagnostic, FfiSyntaxDiagnosticCode, FontFeatureValuesRuleKind, PagePseudoClass,
- ParsedRuleChild, ParsedRuleKind, ParsedRulePrelude, ParsedStyleSheet, Parser, ParserTokenKind, Rule,
- RuleContext, RuleOrDeclarations, SyntaxNode, SyntaxParseBuilder, TOKEN_WINDOW_CHUNK_SIZE, at_rule_is_supported,
- at_rule_kind, collect_descriptors, consume_a_list_of_component_values, has_ignored_vendor_prefix,
- parse_block_contents, parse_font_feature_values, parse_keyframe_selectors, parse_page_selector_list,
- parse_rule, parse_rule_prelude, parse_stylesheet, rule_kind, token_diagnostics, tokenize_for_parser,
+ Declaration, FfiSyntaxDiagnosticCode, FontFeatureValuesRuleKind, PagePseudoClass, ParsedRuleChild,
+ ParsedRuleKind, ParsedRulePrelude, ParsedStyleSheet, Parser, Rule, RuleContext, RuleOrDeclarations, SyntaxNode,
+ SyntaxParseBuilder, at_rule_is_supported, at_rule_kind, collect_descriptors,
+ consume_a_list_of_component_values, has_ignored_vendor_prefix, parse_block_contents, parse_font_feature_values,
+ parse_keyframe_selectors, parse_page_selector_list, parse_rule, parse_rule_prelude, parse_stylesheet,
+ rule_kind, source_of, tokenize_for_parser,
};
use crate::css::parser::value_parser::ParseContext;
@@ -4750,16 +4108,29 @@ mod tests {
#[test]
fn exposes_token_diagnostics_with_source_spans() {
- let mut parse = SyntaxParseBuilder::new(None, false);
- let tokens =
- crate::css::css_tokenizer::tokenize_for_parser(&utf16("a { color: \"bad\n; background: url(foo\"bar) }"));
- parse.diagnostics = token_diagnostics(&tokens);
+ let parse = super::parse_stylesheet_uncached(
+ b"a { color: \"bad\n; background: url(foo\"bar) }".as_slice().into(),
+ None,
+ );
assert_eq!(parse.diagnostics.len(), 2);
assert_eq!(parse.diagnostics[0].code, FfiSyntaxDiagnosticCode::BadString);
- assert_eq!(parse.diagnostics[0].start_line, 0);
- assert!(parse.diagnostics[0].end_column > parse.diagnostics[0].start_column);
+ assert_eq!(
+ (parse.diagnostics[0].start_line, parse.diagnostics[0].start_column),
+ (0, 11)
+ );
+ assert_eq!(
+ (parse.diagnostics[0].end_line, parse.diagnostics[0].end_column),
+ (0, 15)
+ );
assert_eq!(parse.diagnostics[1].code, FfiSyntaxDiagnosticCode::BadUrl);
- assert!(parse.diagnostics[1].end_column > parse.diagnostics[1].start_column);
+ assert_eq!(
+ (parse.diagnostics[1].start_line, parse.diagnostics[1].start_column),
+ (1, 14)
+ );
+ assert_eq!(
+ (parse.diagnostics[1].end_line, parse.diagnostics[1].end_column),
+ (1, 26)
+ );
}
#[test]
@@ -4892,11 +4263,11 @@ mod tests {
#[test]
fn hands_out_each_stylesheet_rule_before_consuming_the_next() {
- let mut parser = Parser::streaming(b"a { color: red } @media screen { b { width: 1px } }");
+ let source = source_of(b"a { color: red } @media screen { b { width: 1px } }".as_slice().into());
+ let mut parser = Parser::new(&source, Vec::new());
let Some(Rule::Qualified(_)) = parser.consume_next_stylesheet_rule() else {
panic!("expected style rule");
};
- assert!(matches!(parser.peek_kind(1), Some(ParserTokenKind::AtKeyword(_))));
let Some(Rule::At(media)) = parser.consume_next_stylesheet_rule() else {
panic!("expected @media");
};
@@ -4904,67 +4275,24 @@ mod tests {
assert!(parser.consume_next_stylesheet_rule().is_none());
}
- fn stylesheet_spanning_many_token_chunks() -> String {
- let mut source = String::new();
- for index in 0..400 {
- source.push_str(&format!(
- ".rule-{index} {{ color: red; margin: {index}px 2px; background: url(a{index}.png) }}\n"
- ));
- if index % 97 == 0 {
- source.push_str("a { content: \"unterminated\n; background: url(bad url) }\n");
- }
- }
- // A rule far longer than a chunk of tokens, so the window is extended in the middle of it.
- source.push_str("@media screen { .long { ");
- for index in 0..300 {
- source.push_str(&format!("--custom-{index}: calc({index}px + 1em) foo(bar, [baz]); "));
- }
- source.push_str("} }\n.last { color: blue }");
- source
- }
-
#[test]
- fn a_streamed_stylesheet_parses_like_one_tokenized_up_front() {
- let source = stylesheet_spanning_many_token_chunks();
- let (mut tokenized, diagnostics) = Parser::from_source(source.as_bytes(), Vec::new());
- let expected = std::iter::from_fn(|| tokenized.consume_next_stylesheet_rule()).collect::<Vec<_>>();
- let mut streamed = Parser::streaming(source.as_bytes());
- let rules = std::iter::from_fn(|| streamed.consume_next_stylesheet_rule()).collect::<Vec<_>>();
- assert_eq!(rules.len(), 407);
- assert_eq!(rules, expected);
-
- let ranges = |diagnostics: &[FfiSyntaxDiagnostic]| {
+ fn reports_a_bad_token_once_when_a_declaration_is_read_again_as_a_rule() {
+ // NB: Each of these looks like a declaration until its curly bracket, so the parser goes back and reads it as
+ // a rule, with its bad tokens.
+ let source = source_of(b"a { b:c \"bad\n {} d:e url(bad url) {} f: \"bad\n }".as_slice().into());
+ let mut parser = Parser::new(&source, Vec::new());
+ assert!(parser.consume_next_stylesheet_rule().is_some());
+ let diagnostics = parser.token_diagnostics();
+ assert_eq!(
diagnostics
.iter()
- .map(|diagnostic| {
- (
- diagnostic.code,
- diagnostic.start_line,
- diagnostic.start_column,
- diagnostic.end_line,
- diagnostic.end_column,
- )
- })
- .collect::<Vec<_>>()
- };
- assert_eq!(diagnostics.len(), 10);
- assert_eq!(ranges(&streamed.tokens.diagnostics), ranges(&diagnostics));
- }
-
- #[test]
- fn a_streamed_stylesheet_holds_only_a_window_of_its_tokens() {
- let source = ".rule { color: red }\n".repeat(2000);
- let mut parser = Parser::streaming(source.as_bytes());
- let mut rule_count = 0;
- let mut largest_window = 0;
- while parser.consume_next_stylesheet_rule().is_some() {
- rule_count += 1;
- largest_window = largest_window.max(parser.tokens.tokens.len());
- }
- assert_eq!(rule_count, 2000);
- assert!(
- largest_window < 4 * TOKEN_WINDOW_CHUNK_SIZE,
- "the window grew to {largest_window} tokens"
+ .map(|diagnostic| (diagnostic.code, diagnostic.start_line, diagnostic.start_column))
+ .collect::<Vec<_>>(),
+ [
+ (FfiSyntaxDiagnosticCode::BadString, 0, 8),
+ (FfiSyntaxDiagnosticCode::BadUrl, 1, 8),
+ (FfiSyntaxDiagnosticCode::BadString, 1, 27),
+ ]
);
}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs
new file mode 100644
index 00000000000..a6238a92ae3
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs
@@ -0,0 +1,1281 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The structure of a style sheet: its rules, their preludes and the declarations in their blocks. The parser reads
+//! the tokens of the lexer as it goes, and holds one token.
+//!
+//! A prelude is made into component values, for the grammar that reads it. The value of a declaration is not: the
+//! parser finds where it ends, and a declaration says where its value is in the source. Whoever needs the component
+//! values of the value makes them from there.
+//!
+//! https://drafts.csswg.org/css-syntax-3/#parsing
+
+use super::{
+ AtRule, Declaration, FfiSyntaxDiagnostic, FfiSyntaxDiagnosticCode, Nested, QualifiedRule, QualifiedRuleResult,
+ Rule, RuleContext, RuleOrDeclarations, at_rule_name, context_for_at_rule, context_rule_name,
+ equals_ascii_case_insensitive, is_accepted_position_try_property, is_font_feature_value_rule_name,
+ is_margin_rule_name, starts_with_ascii,
+};
+use crate::css::css_tokenizer::{
+ CssNumberType, ParserSource, ParserString, ParserTokenKind, SourcePosition, SourceStorage, TokenizerInput,
+ filter_code_points,
+};
+use crate::css::parser::block::Unit;
+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::property_metadata::property_id_from_name;
+use crate::css::selector_parser::StyleNestingParent;
+use smallvec::SmallVec;
+use std::borrow::Cow;
+use std::ops::Range;
+use std::sync::Arc;
+
+/// The text of `input` as a parser reads it: preprocessed, and held for the component values that point into it.
+// https://drafts.csswg.org/css-syntax-3/#input-preprocessing
+pub(super) fn source_of(input: TokenizerInput<'_>) -> Arc<SourceStorage> {
+ Arc::new(SourceStorage::from_input(filter_code_points(input).as_input()))
+}
+
+fn parser_string(text: Text<'_>) -> ParserString {
+ fn widen<T: Copy + Into<u16>>(units: &[T]) -> ParserString {
+ if units.len() <= 16 {
+ ParserString::Inline(units.iter().map(|&unit| unit.into()).collect())
+ } else {
+ ParserString::Owned(units.iter().map(|&unit| unit.into()).collect())
+ }
+ }
+ match text {
+ Text::Source(TokenizerInput::Latin1(units)) => widen(units),
+ Text::Source(TokenizerInput::Utf16(units)) => widen(units),
+ Text::Unescaped(units) if units.len() <= 16 => ParserString::Inline(SmallVec::from_slice(&units)),
+ Text::Unescaped(units) => ParserString::Owned(units.into_boxed_slice()),
+ }
+}
+
+/// 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,
+ _ => unreachable!("a component value of the parser is in the source"),
+ }
+}
+
+/// The tokens of a source, one at a time, and the component values they make.
+struct Stream<'a, U: Unit> {
+ lexer: Lexer<'a, U>,
+ units: &'a [U],
+ storage: &'a Arc<SourceStorage>,
+ /// The next token.
+ token: Token,
+ /// Where the token before the next one ends, which is where the whitespace and comments before the next one start.
+ previous_end: usize,
+ /// Where the stream ends: a token that starts here or later is the end of the source.
+ limit: usize,
+ /// Where the bad string and bad URL tokens are, and whether each is a URL.
+ bad_tokens: Vec<(u32, u32, bool)>,
+ /// Where the last token that the stream has handed out ends. The stream goes back when a declaration turns out to
+ /// be a rule, and reads tokens before this a second time.
+ seen_end: usize,
+}
+
+impl<'a, U: Unit> Stream<'a, U> {
+ fn new(units: &'a [U], storage: &'a Arc<SourceStorage>, range: Range<usize>) -> Self {
+ let mut lexer = Lexer::new(units);
+ lexer.set_position(range.start);
+ let mut stream = Self {
+ units: lexer.units(),
+ lexer,
+ storage,
+ token: Token {
+ start: range.start as u32,
+ end: range.start as u32,
+ part: 0,
+ kind: Kind::EndOfFile,
+ flags: 0,
+ },
+ previous_end: range.start,
+ limit: range.end,
+ bad_tokens: Vec::new(),
+ seen_end: range.start,
+ };
+ stream.advance();
+ stream
+ }
+
+ #[inline]
+ 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 {
+ let limit = self.limit as u32;
+ token = Token {
+ start: limit,
+ end: limit,
+ part: limit,
+ kind: Kind::EndOfFile,
+ flags: 0,
+ };
+ }
+ if token.end as usize > self.seen_end {
+ self.seen_end = token.end as usize;
+ if matches!(token.kind, Kind::BadString | Kind::BadUrl) {
+ self.bad_tokens
+ .push((token.start, token.end, token.kind == Kind::BadUrl));
+ }
+ }
+ self.token = token;
+ }
+
+ /// Where to go back to, to read the next token again.
+ fn checkpoint(&self) -> usize {
+ self.previous_end
+ }
+
+ fn restore(&mut self, checkpoint: usize) {
+ self.lexer.set_position(checkpoint);
+ self.token.end = checkpoint as u32;
+ self.advance();
+ }
+
+ fn source(&self, start: usize, end: usize) -> ParserSource {
+ ParserSource::shared(self.storage.clone(), start..end)
+ }
+
+ fn name(&self, token: Token) -> ParserString {
+ parser_string(name_of(self.units, token))
+ }
+
+ fn kind_of(&self, token: Token) -> ParserTokenKind {
+ let number = || {
+ let (start, end) = token.number_range();
+ let number_type = if !token.has(flag::INTEGER) {
+ CssNumberType::Number
+ } else if token.has(flag::SIGNED) {
+ CssNumberType::IntegerWithExplicitSign
+ } else {
+ CssNumberType::Integer
+ };
+ (number_of(&self.units[start..end]), number_type)
+ };
+ match token.kind {
+ Kind::EndOfFile => ParserTokenKind::EndOfFile,
+ Kind::Ident => ParserTokenKind::Ident(self.name(token)),
+ Kind::Function => ParserTokenKind::Function(self.name(token)),
+ Kind::AtKeyword => ParserTokenKind::AtKeyword(self.name(token)),
+ Kind::Hash => ParserTokenKind::Hash {
+ value: self.name(token),
+ is_id: token.has(flag::ID),
+ },
+ Kind::String => ParserTokenKind::String(parser_string(string_of(self.units, token))),
+ Kind::BadString => ParserTokenKind::BadString,
+ Kind::Url => ParserTokenKind::Url(parser_string(url_of(self.units, token))),
+ Kind::BadUrl => ParserTokenKind::BadUrl,
+ Kind::Delim => ParserTokenKind::Delim(self.units[token.start as usize].code()),
+ Kind::Number => {
+ let (value, number_type) = number();
+ ParserTokenKind::Number { value, number_type }
+ }
+ Kind::Percentage => {
+ let (value, number_type) = number();
+ ParserTokenKind::Percentage { value, number_type }
+ }
+ Kind::Dimension => {
+ let (value, number_type) = number();
+ ParserTokenKind::Dimension {
+ value,
+ number_type,
+ unit: self.name(token),
+ }
+ }
+ Kind::Cdo => ParserTokenKind::Cdo,
+ Kind::Cdc => ParserTokenKind::Cdc,
+ Kind::Colon => ParserTokenKind::Colon,
+ Kind::Semicolon => ParserTokenKind::Semicolon,
+ Kind::Comma => ParserTokenKind::Comma,
+ Kind::OpenSquare => ParserTokenKind::OpenSquare,
+ Kind::CloseSquare => ParserTokenKind::CloseSquare,
+ Kind::OpenParen => ParserTokenKind::OpenParen,
+ Kind::CloseParen => ParserTokenKind::CloseParen,
+ Kind::OpenCurly => ParserTokenKind::OpenCurly,
+ Kind::CloseCurly => ParserTokenKind::CloseCurly,
+ }
+ }
+
+ fn token_value(&self, kind: ParserTokenKind, start: usize, end: usize) -> ComponentValue {
+ ComponentValue {
+ kind: ComponentKind::Token(kind),
+ original_source_text: self.source(start, end),
+ opening_source_length: end - start,
+ closing_source_length: 0,
+ start_position: SourcePosition::default(),
+ end_position: SourcePosition::default(),
+ }
+ }
+
+ /// Appends the whitespace and comments before the next token to `values`, as the whitespace tokens that component
+ /// values have for them: one for each run of whitespace, and one for each run of comments.
+ ///
+ /// The next token then no longer says that it follows them: a block that the source ends in has them, and what
+ /// the block is in must not have them too.
+ #[inline]
+ fn push_gap(&mut self, values: &mut Vec<ComponentValue>) {
+ if self.token.follows_a_gap() {
+ self.push_gap_slow(values);
+ self.token.flags &= !(flag::SPACE_BEFORE | flag::COMMENT_BEFORE);
+ }
+ }
+
+ fn push_gap_slow(&self, values: &mut Vec<ComponentValue>) {
+ let (start, end) = (self.previous_end, self.token.start as usize);
+ if !self.token.has(flag::COMMENT_BEFORE) {
+ values.push(self.token_value(ParserTokenKind::Whitespace, start, end));
+ return;
+ }
+ let at = |index: usize| self.units[index].code();
+ let mut position = start;
+ while position < end {
+ let run_start = position;
+ if at(position) == 0x2F {
+ // NB: Whitespace and comments are all that is here, so a solidus starts a comment.
+ loop {
+ let mut close = position + 2;
+ while close + 1 < end && !(at(close) == 0x2A && at(close + 1) == 0x2F) {
+ close += 1;
+ }
+ position = if close + 1 < end { close + 2 } else { end };
+ if !(position + 1 < end && at(position) == 0x2F && at(position + 1) == 0x2A) {
+ break;
+ }
+ }
+ } else {
+ while position < end && at(position) != 0x2F {
+ position += 1;
+ }
+ }
+ values.push(self.token_value(ParserTokenKind::Whitespace, run_start, position));
+ }
+ }
+
+ // https://drafts.csswg.org/css-syntax-3/#consume-component-value
+ fn consume_component_value(&mut self, depth: usize) -> Result<ComponentValue, ()> {
+ if depth > MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH {
+ return Err(());
+ }
+ let token = self.token;
+ self.advance();
+ let (start, end) = (token.start as usize, token.end as usize);
+ let Some(closer) = closer_of(token.kind) else {
+ return Ok(self.token_value(self.kind_of(token), start, end));
+ };
+ if depth + 1 > MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH {
+ return Err(());
+ }
+ let mut values = Vec::with_capacity(4);
+ let mut token_count = 0;
+ loop {
+ let first_of_gap = values.len();
+ self.push_gap(&mut values);
+ token_count += values.len() - first_of_gap;
+ if self.token.kind == closer || self.token.kind == Kind::EndOfFile {
+ break;
+ }
+ let value = self.consume_component_value(depth + 1)?;
+ token_count += value.token_count();
+ values.push(value);
+ }
+ let (source_end, closing_source_length) = if self.token.kind == closer {
+ let closing = self.token;
+ self.advance();
+ (closing.end as usize, (closing.end - closing.start) as usize)
+ } else {
+ (values.last().map_or(end, source_end), 0)
+ };
+ let values = ComponentValueList::with_token_count(values, token_count).into_boxed();
+ Ok(ComponentValue {
+ kind: if token.kind == Kind::Function {
+ ComponentKind::Function {
+ name: self.name(token),
+ values,
+ }
+ } else {
+ ComponentKind::SimpleBlock {
+ opening: self.kind_of(token),
+ values,
+ }
+ },
+ original_source_text: self.source(start, source_end),
+ opening_source_length: end - start,
+ closing_source_length,
+ start_position: SourcePosition::default(),
+ end_position: SourcePosition::default(),
+ })
+ }
+
+ /// 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) {
+ return equals_ascii_case_insensitive(&self.name(token), expected);
+ }
+ let (start, end) = token.name_range();
+ let name = &self.units[start..end];
+ name.len() == expected.len()
+ && name
+ .iter()
+ .zip(expected)
+ .all(|(unit, &expected)| unit.code() | 0x20 == u32::from(expected) && unit.code() >= 0x41)
+ }
+}
+
+/// The component values of the text in `range` of a source.
+fn component_values_in<U: Unit>(units: &[U], storage: &Arc<SourceStorage>, range: Range<usize>) -> Vec<ComponentValue> {
+ let mut stream = Stream::new(units, storage, range);
+ let mut values = Vec::with_capacity(4);
+ loop {
+ stream.push_gap(&mut values);
+ if stream.token.kind == Kind::EndOfFile {
+ break;
+ }
+ let Ok(value) = stream.consume_component_value(0) else {
+ break;
+ };
+ values.push(value);
+ }
+ values
+}
+
+/// The value of a declaration: where it is in the source. It ends where the last component value before a
+/// `!important` ends.
+#[derive(Clone)]
+pub(crate) struct DeclarationValue {
+ source: Arc<SourceStorage>,
+ /// Where the name of the declaration is, as written.
+ name: Range<u32>,
+ range: Range<u32>,
+ /// Whether parsing the value may do more than produce a value, which sharing the result would skip: `attr()`
+ /// records the attribute names it reads, and `random()` values have an identity of their own.
+ pub(super) may_not_be_shared: bool,
+}
+
+impl DeclarationValue {
+ fn range(&self) -> Range<usize> {
+ self.range.start as usize..self.range.end as usize
+ }
+
+ #[cfg(test)]
+ pub(crate) fn is_empty(&self) -> bool {
+ self.range.is_empty()
+ }
+
+ /// The component values of the value.
+ 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()),
+ }
+ }
+
+ /// The text of the value.
+ pub(crate) fn text(&self) -> Cow<'_, [u16]> {
+ match self.source.as_ref() {
+ SourceStorage::Latin1(units) => Cow::Owned(units[self.range()].iter().copied().map(u16::from).collect()),
+ SourceStorage::Utf16(units) => Cow::Borrowed(&units[self.range()]),
+ }
+ }
+
+ /// A hash of the declaration as written, without its `!important`.
+ pub(super) fn hash_of_text(&self, hasher: &impl std::hash::BuildHasher) -> u64 {
+ let name = self.name.start as usize..self.name.end as usize;
+ match self.source.as_ref() {
+ SourceStorage::Latin1(units) => hasher.hash_one((&units[name], &units[self.range()])),
+ SourceStorage::Utf16(units) => hasher.hash_one((&units[name], &units[self.range()])),
+ }
+ }
+
+ /// Whether the declaration is written like that of `other`, which is in the same source.
+ pub(super) fn is_same_text(&self, other: &Self) -> bool {
+ debug_assert!(Arc::ptr_eq(&self.source, &other.source));
+ fn same<U: Unit>(units: &[U], first: &Range<u32>, second: &Range<u32>) -> bool {
+ units[first.start as usize..first.end as usize] == units[second.start as usize..second.end as usize]
+ }
+ match self.source.as_ref() {
+ SourceStorage::Latin1(units) => {
+ same(units, &self.name, &other.name) && same(units, &self.range, &other.range)
+ }
+ SourceStorage::Utf16(units) => {
+ same(units, &self.name, &other.name) && same(units, &self.range, &other.range)
+ }
+ }
+ }
+}
+
+impl PartialEq for DeclarationValue {
+ fn eq(&self, other: &Self) -> bool {
+ self.text() == other.text()
+ }
+}
+
+impl std::fmt::Debug for DeclarationValue {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(formatter, "{:?}", String::from_utf16_lossy(&self.text()))
+ }
+}
+
+/// Finds the line and column of places in a source that it is asked for in order.
+#[derive(Default)]
+struct LineCursor {
+ offset: usize,
+ line: usize,
+ column: usize,
+}
+
+impl LineCursor {
+ fn position<U: Unit>(&mut self, units: &[U], offset: usize) -> SourcePosition {
+ fn code_points<U: Unit>(units: &[U]) -> usize {
+ if !U::WIDE {
+ return units.len();
+ }
+ // NB: The source has no lone surrogate, so each low surrogate is the second unit of a code point.
+ units.iter().filter(|unit| unit.code() & 0xFC00 != 0xDC00).count()
+ }
+ if offset < self.offset {
+ *self = Self::default();
+ }
+ let units = &units[self.offset..offset];
+ let is_newline = |unit: &U| unit.code() == 0x0A;
+ let lines = units.iter().filter(|unit| is_newline(unit)).count();
+ if lines == 0 {
+ self.column += code_points(units);
+ } else {
+ let last = units.iter().rposition(is_newline).unwrap();
+ self.line += lines;
+ self.column = code_points(&units[last + 1..]);
+ }
+ self.offset = offset;
+ SourcePosition {
+ line: self.line,
+ column: self.column,
+ }
+ }
+}
+
+/// What a component value at the top level of a declaration's value is to the declaration.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum TopLevel {
+ Other,
+ CurlyBlock,
+ Bang,
+ Important,
+}
+
+/// How deep the blocks of rules can be nested. The contents of a block that is deeper are skipped.
+const MAXIMUM_RULE_NESTING_DEPTH: usize = 256;
+
+pub(super) struct Core<'a, U: Unit> {
+ stream: Stream<'a, U>,
+ rule_context: Vec<RuleContext>,
+ rule_names: Vec<Option<ParserString>>,
+ lines: LineCursor,
+ /// The tokens that end the blocks and functions that are open, while a component value is skipped.
+ closers: Vec<Kind>,
+}
+
+impl<'a, U: Unit> Core<'a, U> {
+ fn new(units: &'a [U], storage: &'a Arc<SourceStorage>, rule_context: Vec<RuleContext>) -> Self {
+ let rule_names = rule_context.iter().copied().map(context_rule_name).collect();
+ Self {
+ stream: Stream::new(units, storage, 0..usize::MAX),
+ rule_context,
+ rule_names,
+ lines: LineCursor::default(),
+ closers: Vec::new(),
+ }
+ }
+
+ #[inline]
+ fn kind(&self) -> Kind {
+ self.stream.token.kind
+ }
+
+ fn style_nesting_parent(&self) -> StyleNestingParent {
+ self.rule_context
+ .iter()
+ .rev()
+ .find_map(|context| match context {
+ RuleContext::Style => Some(StyleNestingParent::Style),
+ RuleContext::AtScope => Some(StyleNestingParent::Scope),
+ _ => None,
+ })
+ .unwrap_or(StyleNestingParent::None)
+ }
+
+ /// Consumes the component value that the next token starts, without making it, and returns where it ends. Sets
+ /// `may_not_be_shared` if an `attr()` or `random()` function is in it.
+ fn skip_component_value(&mut self, may_not_be_shared: &mut bool) -> Result<usize, ()> {
+ let token = self.stream.token;
+ self.stream.advance();
+ let Some(closer) = closer_of(token.kind) else {
+ return Ok(token.end as usize);
+ };
+ let mut note_function = |stream: &Stream<'a, U>, token: Token| {
+ if token.kind == Kind::Function && (stream.name_is(token, b"attr") || stream.name_is(token, b"random")) {
+ *may_not_be_shared = true;
+ }
+ };
+ note_function(&self.stream, token);
+ self.closers.clear();
+ self.closers.push(closer);
+ loop {
+ if self.closers.len() > MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH {
+ return Err(());
+ }
+ let token = self.stream.token;
+ if token.kind == Kind::EndOfFile {
+ return Ok(token.start as usize);
+ }
+ self.stream.advance();
+ if self.closers.last() == Some(&token.kind) {
+ self.closers.pop();
+ if self.closers.is_empty() {
+ return Ok(token.end as usize);
+ }
+ } else if let Some(closer) = closer_of(token.kind) {
+ note_function(&self.stream, token);
+ self.closers.push(closer);
+ }
+ }
+ }
+
+ // https://drafts.csswg.org/css-syntax-3/#consume-stylesheet-contents
+ // OPTIMIZATION: Returns the next rule of the list that algorithm builds, or None once the input is exhausted — so a
+ // caller can process each rule and drop its component values before the next one is consumed, rather than holding
+ // the component values of the whole sheet at once.
+ fn consume_next_stylesheet_rule(&mut self) -> Option<Rule> {
+ loop {
+ match self.kind() {
+ Kind::Cdo | Kind::Cdc => self.stream.advance(),
+ Kind::EndOfFile => return None,
+ Kind::AtKeyword => {
+ if let Some(rule) = self.consume_at_rule(Nested::No) {
+ return Some(Rule::At(rule));
+ }
+ }
+ _ => {
+ if let Ok(rule) = self.consume_qualified_rule(None, Nested::No) {
+ return Some(Rule::Qualified(rule));
+ }
+ }
+ }
+ }
+ }
+
+ /// Consumes the one rule that the source is, if it is one rule.
+ fn consume_only_rule(&mut self, nested: Nested) -> Option<Rule> {
+ let rule = match self.kind() {
+ Kind::EndOfFile => return None,
+ Kind::AtKeyword => Rule::At(self.consume_at_rule(nested)?),
+ _ => Rule::Qualified(self.consume_qualified_rule(None, nested).ok()?),
+ };
+ (self.kind() == Kind::EndOfFile).then_some(rule)
+ }
+
+ // https://drafts.csswg.org/css-syntax-3/#consume-at-rule
+ fn consume_at_rule(&mut self, nested: Nested) -> Option<AtRule> {
+ debug_assert_eq!(self.kind(), Kind::AtKeyword);
+ let name = self.stream.name(self.stream.token);
+ self.stream.advance();
+ let mut rule = AtRule {
+ name,
+ prelude: Vec::with_capacity(4),
+ children: Vec::new(),
+ has_block: false,
+ nesting_parent: self.style_nesting_parent(),
+ valid_in_context: false,
+ outer_rule_name: self.rule_names.last().cloned().flatten(),
+ };
+ loop {
+ self.stream.push_gap(&mut rule.prelude);
+ match self.kind() {
+ Kind::EndOfFile | Kind::Semicolon => {
+ if self.kind() == Kind::Semicolon {
+ self.stream.advance();
+ }
+ rule.valid_in_context = self.at_rule_is_valid(&rule);
+ return Some(rule);
+ }
+ Kind::CloseCurly if nested == Nested::Yes => {
+ rule.valid_in_context = self.at_rule_is_valid(&rule);
+ return Some(rule);
+ }
+ Kind::OpenCurly => {
+ let context = context_for_at_rule(rule.name.as_ref());
+ self.rule_context.push(context);
+ self.rule_names.push(Some(at_rule_name(rule.name.as_ref())));
+ rule.children = self.consume_block();
+ self.rule_names.pop();
+ self.rule_context.pop();
+ rule.has_block = true;
+ rule.valid_in_context = self.at_rule_is_valid(&rule);
+ return Some(rule);
+ }
+ _ => rule.prelude.push(self.stream.consume_component_value(0).ok()?),
+ }
+ }
+ }
+
+ // https://drafts.csswg.org/css-syntax-3/#consume-qualified-rule
+ fn consume_qualified_rule(
+ &mut self,
+ stop: Option<Kind>,
+ nested: Nested,
+ ) -> Result<QualifiedRule, QualifiedRuleResult> {
+ let qualified_context = if self.rule_context.last() == Some(&RuleContext::AtKeyframes) {
+ RuleContext::Keyframe
+ } 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;
+ 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();
+ 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);
+ } else {
+ self.consume_block();
+ }
+ return Err(QualifiedRuleResult::Invalid);
+ }
+ self.rule_context.push(qualified_context);
+ self.rule_names.push(context_rule_name(qualified_context));
+ rule.children = self.consume_block();
+ self.rule_names.pop();
+ self.rule_context.pop();
+ if matches!(rule.children.first(), Some(RuleOrDeclarations::Declarations(_))) {
+ let RuleOrDeclarations::Declarations(declarations) = rule.children.remove(0) else {
+ unreachable!();
+ };
+ rule.declarations = declarations;
+ }
+ rule.valid_in_context = self.qualified_rule_is_valid();
+ 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));
+ }
+ let value = self
+ .stream
+ .consume_component_value(0)
+ .map_err(|()| QualifiedRuleResult::Invalid)?;
+ rule.prelude.push(value);
+ }
+ }
+ }
+ }
+
+ // https://drafts.csswg.org/css-syntax-3/#consume-block
+ fn consume_block(&mut self) -> Vec<RuleOrDeclarations> {
+ debug_assert_eq!(self.kind(), Kind::OpenCurly);
+ // NB: The blocks of rules are consumed by recursion, so the contents of a block that is too deep are skipped.
+ if self.rule_context.len() > MAXIMUM_RULE_NESTING_DEPTH {
+ self.skip_block();
+ return Vec::new();
+ }
+ self.stream.advance();
+ let result = self.consume_block_contents();
+ if self.kind() == Kind::CloseCurly {
+ self.stream.advance();
+ }
+ result
+ }
+
+ /// Consumes a block and its contents, without making them.
+ fn skip_block(&mut self) {
+ debug_assert_eq!(self.kind(), Kind::OpenCurly);
+ self.stream.advance();
+ self.closers.clear();
+ self.closers.push(Kind::CloseCurly);
+ while !self.closers.is_empty() {
+ let token = self.stream.token;
+ if token.kind == Kind::EndOfFile {
+ return;
+ }
+ self.stream.advance();
+ if self.closers.last() == Some(&token.kind) {
+ self.closers.pop();
+ } else if let Some(closer) = closer_of(token.kind) {
+ self.closers.push(closer);
+ }
+ }
+ }
+
+ // https://drafts.csswg.org/css-syntax-3/#consume-block-contents
+ fn consume_block_contents(&mut self) -> Vec<RuleOrDeclarations> {
+ let mut result = Vec::with_capacity(4);
+ let mut declarations = Vec::with_capacity(8);
+ loop {
+ match self.kind() {
+ Kind::Semicolon => self.stream.advance(),
+ Kind::EndOfFile | Kind::CloseCurly => {
+ if !declarations.is_empty() {
+ result.push(RuleOrDeclarations::Declarations(declarations));
+ }
+ return result;
+ }
+ Kind::AtKeyword => {
+ if !declarations.is_empty() {
+ result.push(RuleOrDeclarations::Declarations(std::mem::take(&mut declarations)));
+ }
+ if let Some(rule) = self.consume_at_rule(Nested::Yes) {
+ result.push(RuleOrDeclarations::Rule(Rule::At(rule)));
+ }
+ }
+ kind => {
+ if kind == Kind::Ident {
+ let start = self.stream.checkpoint();
+ let name = self.stream.token;
+ self.stream.advance();
+ if self.kind() == Kind::Colon {
+ self.stream.advance();
+ if let Some(declaration) = self.consume_declaration_value(name) {
+ declarations.push(declaration);
+ continue;
+ }
+ }
+ self.stream.restore(start);
+ }
+ match self.consume_qualified_rule(Some(Kind::Semicolon), Nested::Yes) {
+ Ok(rule) => {
+ if !declarations.is_empty() {
+ result.push(RuleOrDeclarations::Declarations(std::mem::take(&mut declarations)));
+ }
+ result.push(RuleOrDeclarations::Rule(Rule::Qualified(rule)));
+ }
+ Err(QualifiedRuleResult::Invalid) => {
+ if self.kind() == Kind::Semicolon {
+ self.stream.advance();
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // https://drafts.csswg.org/css-syntax-3/#consume-declaration
+ /// Consumes the rest of a declaration whose name is the token `name`, from after its colon.
+ fn consume_declaration_value(&mut self, name_token: Token) -> Option<Declaration> {
+ let value_start = self.stream.token.start as usize;
+ let mut may_not_be_shared = false;
+ // What the last two component values at the top level are, and where the last three end.
+ let mut kinds = [TopLevel::Other; 2];
+ let mut ends = [value_start; 3];
+ let mut count = 0usize;
+ let mut curly_block_count = 0usize;
+ loop {
+ let token = self.stream.token;
+ let top_level = match token.kind {
+ Kind::EndOfFile | Kind::Semicolon | Kind::CloseCurly => break,
+ Kind::OpenCurly => TopLevel::CurlyBlock,
+ Kind::Delim if self.stream.units[token.start as usize].code() == 0x21 => TopLevel::Bang,
+ Kind::Ident if self.stream.name_is(token, b"important") => TopLevel::Important,
+ _ => TopLevel::Other,
+ };
+ let Ok(end) = self.skip_component_value(&mut may_not_be_shared) else {
+ break;
+ };
+ kinds = [kinds[1], top_level];
+ ends = [ends[1], ends[2], end];
+ count += 1;
+ curly_block_count += usize::from(top_level == TopLevel::CurlyBlock);
+ }
+ let important = count >= 2 && kinds == [TopLevel::Bang, TopLevel::Important];
+ let (value_end, count) = if important {
+ (ends[0], count - 2)
+ } else {
+ (ends[2], count)
+ };
+
+ let name = self.stream.name(name_token);
+ let is_custom_property = starts_with_ascii(name.as_ref(), b"--");
+ if is_custom_property && name.as_ref().len() == 2 {
+ return None;
+ }
+ // INTEROP: The initial-value descriptor accepts arbitrary component values, including mixed curly blocks.
+ let is_initial_value_descriptor = self.rule_context.last() == Some(&RuleContext::AtProperty)
+ && equals_ascii_case_insensitive(name.as_ref(), b"initial-value");
+ if !is_custom_property && !is_initial_value_descriptor && curly_block_count != 0 && curly_block_count != count {
+ return None;
+ }
+ if !self.declaration_is_valid(name.as_ref()) {
+ return None;
+ }
+ let is_property = self.declaration_is_property();
+ let rule_context = if !is_property && self.rule_context.contains(&RuleContext::AtFunction) {
+ RuleContext::AtFunction
+ } else {
+ self.rule_context.last().copied().unwrap_or(RuleContext::Unknown)
+ };
+ Some(Declaration {
+ name,
+ value: DeclarationValue {
+ source: self.stream.storage.clone(),
+ name: name_token.start..name_token.end,
+ range: value_start as u32..value_end as u32,
+ may_not_be_shared,
+ },
+ important,
+ source_position: self.lines.position(self.stream.units, name_token.start as usize),
+ is_property,
+ rule_context,
+ })
+ }
+
+ fn consume_bad_declaration(&mut self, nested: Nested) {
+ let mut may_not_be_shared = false;
+ loop {
+ match self.kind() {
+ Kind::EndOfFile => return,
+ Kind::Semicolon => {
+ self.stream.advance();
+ return;
+ }
+ Kind::CloseCurly if nested == Nested::Yes => return,
+ _ => {
+ if self.skip_component_value(&mut may_not_be_shared).is_err() {
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ fn declaration_is_valid(&self, name: &[u16]) -> bool {
+ let Some(context) = self.rule_context.last() else {
+ return false;
+ };
+ match context {
+ RuleContext::Unknown | RuleContext::AtKeyframes => false,
+ RuleContext::Keyframe => ![
+ b"animation".as_slice(),
+ b"animation-delay",
+ b"animation-direction",
+ b"animation-duration",
+ b"animation-fill-mode",
+ b"animation-iteration-count",
+ b"animation-name",
+ b"animation-play-state",
+ b"animation-timeline",
+ ]
+ .iter()
+ .any(|property| equals_ascii_case_insensitive(name, property)),
+ RuleContext::AtContainer | RuleContext::AtLayer | RuleContext::AtMedia | RuleContext::AtSupports => self
+ .rule_context
+ .iter()
+ .any(|context| matches!(context, RuleContext::Style | RuleContext::AtFunction)),
+ RuleContext::AtPositionTry => property_id_from_name(name).is_some_and(is_accepted_position_try_property),
+ _ => true,
+ }
+ }
+
+ fn declaration_is_property(&self) -> bool {
+ match self.rule_context.last() {
+ Some(
+ RuleContext::Style
+ | RuleContext::Keyframe
+ | RuleContext::AtScope
+ | RuleContext::Margin
+ | RuleContext::AtPositionTry,
+ ) => true,
+ Some(RuleContext::AtContainer | RuleContext::AtLayer | RuleContext::AtMedia | RuleContext::AtSupports) => {
+ self.rule_context.contains(&RuleContext::Style)
+ }
+ _ => false,
+ }
+ }
+
+ fn at_rule_is_valid(&self, rule: &AtRule) -> bool {
+ let name = rule.name.as_ref();
+ // NB: Margin and font feature value rules are only meaningful inside @page and
+ // @font-feature-values. The C++ converter dropped them anywhere else, so they must not
+ // count as valid rules for the top-level @import and @namespace ordering windows.
+ if self.rule_context.is_empty() {
+ return !is_margin_rule_name(name) && !is_font_feature_value_rule_name(name);
+ }
+ if self.rule_context.contains(&RuleContext::Style) {
+ return [b"container".as_slice(), b"layer", b"media", b"scope", b"supports"]
+ .iter()
+ .any(|expected| equals_ascii_case_insensitive(name, expected));
+ }
+ if self.rule_context.contains(&RuleContext::AtFunction) {
+ return [b"container".as_slice(), b"media", b"supports"]
+ .iter()
+ .any(|expected| equals_ascii_case_insensitive(name, expected));
+ }
+ match self.rule_context.last().unwrap() {
+ RuleContext::AtContainer
+ | RuleContext::AtLayer
+ | RuleContext::AtMedia
+ | RuleContext::AtScope
+ | RuleContext::AtSupports => {
+ !equals_ascii_case_insensitive(name, b"import")
+ && !equals_ascii_case_insensitive(name, b"namespace")
+ && !is_font_feature_value_rule_name(name)
+ }
+ RuleContext::AtPage => is_margin_rule_name(name),
+ RuleContext::AtFontFeatureValues => is_font_feature_value_rule_name(name),
+ _ => false,
+ }
+ }
+
+ fn qualified_rule_is_valid(&self) -> bool {
+ matches!(
+ self.rule_context.last(),
+ None | Some(
+ RuleContext::Style
+ | RuleContext::AtContainer
+ | RuleContext::AtLayer
+ | RuleContext::AtMedia
+ | RuleContext::AtScope
+ | RuleContext::AtSupports
+ | RuleContext::AtKeyframes
+ )
+ )
+ }
+
+ /// A diagnostic for each bad string and bad URL token that the parser has read, in the order of the source.
+ fn token_diagnostics(&self) -> Vec<FfiSyntaxDiagnostic> {
+ let mut lines = LineCursor::default();
+ self.stream
+ .bad_tokens
+ .iter()
+ .map(|&(start, end, is_url)| {
+ let start = lines.position(self.stream.units, start as usize);
+ let end = lines.position(self.stream.units, end as usize);
+ FfiSyntaxDiagnostic {
+ code: if is_url {
+ FfiSyntaxDiagnosticCode::BadUrl
+ } else {
+ FfiSyntaxDiagnosticCode::BadString
+ },
+ start_line: start.line,
+ start_column: start.column,
+ end_line: end.line,
+ end_column: end.column,
+ primary_offset: usize::MAX,
+ primary_length: 0,
+ secondary_offset: usize::MAX,
+ secondary_length: 0,
+ prelude_offset: usize::MAX,
+ prelude_length: 0,
+ }
+ })
+ .collect()
+ }
+}
+
+/// A parser of the structure of a source, which is 8-bit or 16-bit text.
+pub(super) enum Parser<'a> {
+ Narrow(Core<'a, u8>),
+ Wide(Core<'a, u16>),
+}
+
+macro_rules! each_width {
+ ($self:expr, $core:ident => $body:expr) => {
+ match $self {
+ Parser::Narrow($core) => $body,
+ Parser::Wide($core) => $body,
+ }
+ };
+}
+
+impl<'a> Parser<'a> {
+ /// A parser of `source`, which [`source_of`] made, for text in the rules that `rule_context` names.
+ pub(super) fn new(source: &'a Arc<SourceStorage>, rule_context: Vec<RuleContext>) -> Self {
+ match source.as_ref() {
+ SourceStorage::Latin1(units) => Self::Narrow(Core::new(units, source, rule_context)),
+ SourceStorage::Utf16(units) => Self::Wide(Core::new(units, source, rule_context)),
+ }
+ }
+
+ pub(super) fn rule_context(&self) -> &[RuleContext] {
+ each_width!(self, core => &core.rule_context)
+ }
+
+ pub(super) fn consume_next_stylesheet_rule(&mut self) -> Option<Rule> {
+ each_width!(self, core => core.consume_next_stylesheet_rule())
+ }
+
+ pub(super) fn consume_only_rule(&mut self, nested: bool) -> Option<Rule> {
+ let nested = if nested { Nested::Yes } else { Nested::No };
+ each_width!(self, core => core.consume_only_rule(nested))
+ }
+
+ pub(super) fn consume_block_contents(&mut self) -> Vec<RuleOrDeclarations> {
+ each_width!(self, core => core.consume_block_contents())
+ }
+
+ /// A diagnostic for each bad string and bad URL token that the parser has read, in the order of the source.
+ pub(super) fn token_diagnostics(&self) -> Vec<FfiSyntaxDiagnostic> {
+ each_width!(self, core => core.token_diagnostics())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{LineCursor, Parser, component_values_in, source_of};
+ use crate::css::css_tokenizer::{ParserTokenKind, SourceStorage, tokenize_for_parser};
+ use crate::css::parser::component_value::{ComponentKind, ComponentValue, consume_a_list_of_component_values};
+ use crate::css::parser::syntax_parser::{Rule, RuleContext, RuleOrDeclarations};
+ use std::fmt::Write;
+
+ /// A token, with its string as text: the two tokenizers hold strings in different ways.
+ fn token(kind: &ParserTokenKind) -> String {
+ let text = |string: &[u16]| String::from_utf16_lossy(string);
+ match kind {
+ ParserTokenKind::Ident(value) => format!("ident {:?}", text(value)),
+ ParserTokenKind::Function(value) => format!("function {:?}", text(value)),
+ ParserTokenKind::AtKeyword(value) => format!("at-keyword {:?}", text(value)),
+ ParserTokenKind::Hash { value, is_id } => format!("hash {:?} {is_id}", text(value)),
+ ParserTokenKind::String(value) => format!("string {:?}", text(value)),
+ ParserTokenKind::Url(value) => format!("url {:?}", text(value)),
+ ParserTokenKind::Dimension {
+ value,
+ number_type,
+ unit,
+ } => format!("dimension {value} {number_type:?} {:?}", text(unit)),
+ kind => format!("{kind:?}"),
+ }
+ }
+
+ /// What component values are, without where they are.
+ fn shape(values: &[ComponentValue], output: &mut String) {
+ for value in values {
+ let source = String::from_utf16_lossy(&value.original_source_text.to_vec());
+ match &value.kind {
+ ComponentKind::Token(kind) => write!(output, "{} {source:?}, ", token(kind)).unwrap(),
+ ComponentKind::Function { name, values } => {
+ write!(output, "function {:?} {source:?} [", String::from_utf16_lossy(name)).unwrap();
+ shape(values, output);
+ write!(output, "] {} {}, ", values.token_count, value.closing_source_length).unwrap();
+ }
+ ComponentKind::SimpleBlock { opening, values } => {
+ write!(output, "block {} {source:?} [", token(opening)).unwrap();
+ shape(values, output);
+ write!(output, "] {} {}, ", values.token_count, value.closing_source_length).unwrap();
+ }
+ }
+ }
+ }
+
+ fn values_of(source: &str) -> String {
+ let text = if source.is_ascii() {
+ source_of(source.as_bytes().into())
+ } else {
+ source_of(source.encode_utf16().collect::<Vec<_>>().as_slice().into())
+ };
+ let values = match text.as_ref() {
+ SourceStorage::Latin1(units) => component_values_in(units, &text, 0..units.len()),
+ SourceStorage::Utf16(units) => component_values_in(units, &text, 0..units.len()),
+ };
+ let mut output = String::new();
+ shape(&values, &mut output);
+ output
+ }
+
+ #[test]
+ fn makes_the_component_values_of_the_tokenizer() {
+ for source in [
+ "",
+ " ",
+ "a",
+ " a ",
+ "a b",
+ "a/**/b",
+ "a /**/ b",
+ "a/* c *//* d */b",
+ "a /* c */ /* d */\n/* e */ b",
+ "/**/a/**/",
+ "a /* c */",
+ "/***/a/**//***/b",
+ "/*/ */a",
+ "f(a, b) [c d] {e:f} (g)",
+ "f( a , g( b ) )",
+ "f(a",
+ "f( a ",
+ "f( g( a /**/ ",
+ "@x ( a ",
+ "f(",
+ "[ ( { a",
+ "a ) ] } b",
+ "( ] ) [ ) ]",
+ "1 +2 -3.5 1e3 10% 12px 1.5em #abc #1bc 'string' \"s\\\"s\" url(a) url( 'a' )",
+ "a\\62 c \\31 23 f\\6fo(x)",
+ "@media <!-- --> u+123 , ; : !important",
+ "\"bad\nstring url(bad url) x",
+ "caf\u{e9} \u{1f600}(a) '\u{1f600}'",
+ "var(--a, calc(1px + 2 * (3em - 4%)))",
+ ] {
+ let mut expected = String::new();
+ let text: Vec<u16> = source.encode_utf16().collect();
+ shape(
+ &consume_a_list_of_component_values(tokenize_for_parser(text.as_slice())).unwrap(),
+ &mut expected,
+ );
+ assert_eq!(values_of(source), expected, "{source:?}");
+ }
+ }
+
+ #[test]
+ fn a_comment_that_the_source_ends_in_is_whitespace() {
+ assert_eq!(values_of("a /* b"), values_of("a /* b*/").replace("/* b*/", "/* b"));
+ assert_eq!(values_of("a/*"), "ident \"a\" \"a\", Whitespace \"/*\", ");
+ }
+
+ #[test]
+ fn does_not_make_component_values_deeper_than_the_limit() {
+ // NB: Neither the parser nor the making of component values may use up the stack.
+ let deep = format!("a {{ b: {} c; d: e }} f {{ g: h }}", "(".repeat(100_000));
+ let source = source_of(deep.as_bytes().into());
+ let mut parser = Parser::new(&source, Vec::new());
+ while let Some(rule) = parser.consume_next_stylesheet_rule() {
+ let Rule::Qualified(rule) = rule else {
+ panic!("expected a qualified rule");
+ };
+ for declaration in &rule.declarations {
+ declaration.value.component_values();
+ }
+ }
+
+ let source = source_of(format!("{} {{}}", "[".repeat(100_000)).as_bytes().into());
+ assert!(
+ Parser::new(&source, Vec::new())
+ .consume_next_stylesheet_rule()
+ .is_none()
+ );
+ }
+
+ #[test]
+ fn does_not_nest_rules_deeper_than_the_limit() {
+ use super::MAXIMUM_RULE_NESTING_DEPTH;
+ // NB: The parser may not use up the stack.
+ let count = 100_000;
+ let deep = "@media all {".repeat(count) + "a { b: c }" + &"}".repeat(count) + " d { e: f }";
+ let source = source_of(deep.as_bytes().into());
+ let mut parser = Parser::new(&source, Vec::new());
+ let Some(Rule::At(mut rule)) = parser.consume_next_stylesheet_rule() else {
+ panic!("expected an at-rule");
+ };
+ let mut depth = 1;
+ while let Some(RuleOrDeclarations::Rule(Rule::At(child))) = rule.children.pop() {
+ rule = child;
+ depth += 1;
+ }
+ assert_eq!(depth, MAXIMUM_RULE_NESTING_DEPTH + 1);
+ assert!(rule.has_block && rule.children.is_empty());
+ assert!(matches!(parser.consume_next_stylesheet_rule(), Some(Rule::Qualified(_))));
+ assert!(parser.consume_next_stylesheet_rule().is_none());
+
+ let source = source_of(format!("{}}}", "a {".repeat(count)).as_bytes().into());
+ let mut parser = Parser::new(&source, Vec::new());
+ assert!(matches!(parser.consume_next_stylesheet_rule(), Some(Rule::Qualified(_))));
+ assert!(parser.consume_next_stylesheet_rule().is_none());
+ }
+
+ #[test]
+ fn a_declaration_says_where_its_value_is() {
+ let source = source_of(
+ b"a: b c ; d : e!important; --f: g( ! important ) ! IMPORTANT ;h:;i: \\69mportant !\\49MPORTANT; j: attr(k) l(Random(m))"
+ .as_slice()
+ .into(),
+ );
+ let items = Parser::new(&source, vec![RuleContext::Style]).consume_block_contents();
+ let [RuleOrDeclarations::Declarations(declarations)] = items.as_slice() else {
+ panic!("expected declarations");
+ };
+ let found: Vec<_> = declarations
+ .iter()
+ .map(|declaration| {
+ (
+ String::from_utf16_lossy(&declaration.name),
+ String::from_utf16_lossy(&declaration.value.text()),
+ declaration.important,
+ declaration.value.may_not_be_shared,
+ )
+ })
+ .collect();
+ let expected = [
+ ("a", "b c", false, false),
+ ("d", "e", true, false),
+ ("--f", "g( ! important )", true, false),
+ ("h", "", false, false),
+ ("i", "\\69mportant", true, false),
+ ("j", "attr(k) l(Random(m))", false, true),
+ ]
+ .map(|(name, value, important, may_not_be_shared)| {
+ (name.to_string(), value.to_string(), important, may_not_be_shared)
+ });
+ assert_eq!(found, expected);
+ }
+
+ #[test]
+ fn counts_lines_and_code_points() {
+ let text: Vec<u16> = "a\n\u{1f600}b\u{e9}\n\nc".encode_utf16().collect();
+ let mut lines = LineCursor::default();
+ let mut positions = |offset: usize| {
+ let position = lines.position(&text, offset);
+ (position.line, position.column)
+ };
+ assert_eq!(positions(0), (0, 0));
+ assert_eq!(positions(1), (0, 1));
+ assert_eq!(positions(2), (1, 0));
+ assert_eq!(positions(4), (1, 1));
+ assert_eq!(positions(6), (1, 3));
+ assert_eq!(positions(8), (3, 0));
+ // NB: A place before the last one is found too.
+ assert_eq!(positions(5), (1, 2));
+ assert_eq!(positions(9), (3, 1));
+ }
+}