Skip to content

Truly independent web browser

LibWeb: Lex the prelude of a CSS rule once

Andreas Kling59e57352d364
diff --git a/Libraries/LibWeb/Rust/src/css/parser/rows.rs b/Libraries/LibWeb/Rust/src/css/parser/rows.rs
index e8b26d50679..63c35de1c5c 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/rows.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/rows.rs
@@ -38,48 +38,82 @@ pub(crate) struct Rows {
/// the end-of-file token if nothing closes it.
tokens: Vec<Token>,
open: Vec<u32>,
+ /// Whether a token that was pushed is nested too deep, so that the rows are not a list of component values.
+ is_too_deep: bool,
}
impl Rows {
+ /// Removes all rows, to take the tokens of another source range.
+ pub(crate) fn clear(&mut self) {
+ self.tokens.clear();
+ self.open.clear();
+ self.is_too_deep = false;
+ }
+
+ /// Appends `token`, which follows the tokens that the rows have.
+ #[inline]
+ pub(crate) fn push(&mut self, token: Token) {
+ let row = self.tokens.len() as u32;
+ if let Some(&open) = self.open.last()
+ && closer_of(self.tokens[open as usize].kind) == Some(token.kind)
+ {
+ self.open.pop();
+ self.tokens[open as usize].part = row;
+ } else if closer_of(token.kind).is_some() {
+ // NB: This is the depth at which a list of component values fails to parse.
+ if self.open.len() >= MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH {
+ self.is_too_deep = true;
+ return;
+ }
+ self.open.push(row);
+ }
+ self.tokens.push(token);
+ }
+
+ /// Ends the rows at `end`, where `next` is the token that follows them or the end of the source. Fails if the
+ /// functions and blocks are nested too deep.
+ pub(crate) fn finish(&mut self, next: Token, end: usize) -> Result<(), ()> {
+ if self.is_too_deep {
+ return Err(());
+ }
+ let row = self.tokens.len() as u32;
+ // NB: Whitespace and comments before the end of the range are before the token that starts there. Those after
+ // the end of the range, which starts where the last row ends, are not in the rows.
+ let end = (next.start as usize).min(end) as u32;
+ let has_gap_in_range = self.tokens.last().is_none_or(|last| last.end < end);
+ let flags = if has_gap_in_range {
+ next.flags & (flag::SPACE_BEFORE | flag::COMMENT_BEFORE)
+ } else {
+ 0
+ };
+ self.tokens.push(Token {
+ start: end,
+ end,
+ part: 0,
+ kind: Kind::EndOfFile,
+ flags,
+ });
+ for &open in &self.open {
+ self.tokens[open as usize].part = row;
+ }
+ Ok(())
+ }
+
/// Fills the rows with the tokens in `range` of `units`, which are preprocessed text. Fails if the functions and
/// blocks are nested too deep.
pub(crate) fn fill<U: Unit>(&mut self, units: &[U], range: Range<usize>) -> Result<(), ()> {
- self.tokens.clear();
- self.open.clear();
+ self.clear();
let mut lexer = Lexer::new(units);
lexer.set_position(range.start);
loop {
- let mut token = lexer.next();
- let row = self.tokens.len() as u32;
+ let token = lexer.next();
if token.kind == Kind::EndOfFile || token.start as usize >= range.end {
- // NB: Whitespace and comments before the end of the range are before the token that starts there.
- let end = (token.start as usize).min(range.end) as u32;
- token = Token {
- start: end,
- end,
- part: 0,
- kind: Kind::EndOfFile,
- flags: token.flags & (flag::SPACE_BEFORE | flag::COMMENT_BEFORE),
- };
- self.tokens.push(token);
- for &open in &self.open {
- self.tokens[open as usize].part = row;
- }
- return Ok(());
+ return self.finish(token, range.end);
}
- if let Some(&open) = self.open.last()
- && closer_of(self.tokens[open as usize].kind) == Some(token.kind)
- {
- self.open.pop();
- self.tokens[open as usize].part = row;
- } else if closer_of(token.kind).is_some() {
- // NB: This is the depth at which a list of component values fails to parse.
- if self.open.len() >= MAXIMUM_COMPONENT_VALUE_NESTING_DEPTH {
- return Err(());
- }
- self.open.push(row);
+ self.push(token);
+ if self.is_too_deep {
+ return Err(());
}
- self.tokens.push(token);
}
}
@@ -479,6 +513,22 @@ mod tests {
}
}
+ #[test]
+ fn rows_have_no_whitespace_from_after_their_range() {
+ let units: Vec<u16> = "a {".encode_utf16().collect();
+ let source = TokenizerInput::Utf16(&units);
+ let mut rows = Rows::default();
+ rows.fill(&units, 0..1).unwrap();
+ let mut values = rows.values(source, false);
+ assert!(values.next().is_some_and(|value| value.is_ident()));
+ assert!(values.is_empty());
+ rows.fill(&units, 0..3).unwrap();
+ let mut values = rows.values(source, false);
+ assert!(values.next().is_some_and(|value| value.is_ident()));
+ assert!(values.next().is_some_and(|value| value.is_whitespace()));
+ assert!(values.is_empty());
+ }
+
#[test]
fn has_the_component_values_of_the_tokenizer() {
for source in [
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
index 9dd5479b71e..484e2a9da32 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
@@ -38,6 +38,7 @@ use crate::css::parser::query_parser::{
parse_media_query_list_from_component_values, parse_supports_condition_from_component_values,
parse_supports_declaration_from_component_values, resolve_query_feature, supports_feature_matches,
};
+use crate::css::parser::rows::Rows;
use crate::css::parser::sheet_source_text::SheetSourceText;
use crate::css::parser::stylesheet_cache::{CachedParseMetadata, parse_with_cache};
use crate::css::parser::syntax::{SyntaxNode, parse_syntax, parse_with_syntax};
@@ -52,7 +53,7 @@ use crate::css::scope_selectors::ScopeSelectors;
use crate::css::selector_arena::{NestingTarget, RuleOrdinal};
use crate::css::selector_parser::{
RustParsedSelectorList, SelectorType, StyleNestingParent, parse_selector_list_from_component_values,
- parse_selector_list_of_prelude,
+ parse_selector_list_of_rows,
};
use crate::css::serialize::TextSink;
use crate::css::serialize::serialize_component_values_to_utf16;
@@ -1444,7 +1445,7 @@ pub(crate) fn supports_declaration_matches(context: &ParseContext, source: &[u16
is_in_list: bool,
}
impl structure::Sink for Declarations {
- fn begin_rule(&mut self, _: Rule) {
+ fn begin_rule(&mut self, _: Rule, _: Option<&Rows>) {
self.rule_count += 1;
}
fn end_rule(&mut self) {}
@@ -1927,8 +1928,6 @@ struct SyntaxParseBuilder<'a> {
value_scratch: Vec<ComponentValue>,
/// The memory for the text of the value that is parsed, where the source does not have it as UTF-16.
text_scratch: Vec<u16>,
- /// The tokens of the prelude that is parsed.
- rows: RefCell<crate::css::parser::rows::Rows>,
/// The names that the selectors of the style rules name.
names: RefCell<crate::css::selector_parser::NameCache>,
/// What a `&` in the rules being appended names, or none outside every rule.
@@ -2789,7 +2788,6 @@ impl<'a> SyntaxParseBuilder<'a> {
roots_are_items: false,
value_scratch: Vec::new(),
text_scratch: Vec::new(),
- rows: RefCell::default(),
names: RefCell::default(),
nesting: Cell::new(None),
parent: Cell::new(None),
@@ -3178,6 +3176,7 @@ impl<'a> SyntaxParseBuilder<'a> {
fn parse_selector_list(
&self,
prelude: &structure::Prelude,
+ prelude_rows: Option<&Rows>,
selector_type: SelectorType,
nesting_parent: StyleNestingParent,
nesting: NestingTarget,
@@ -3187,11 +3186,11 @@ impl<'a> SyntaxParseBuilder<'a> {
.iter()
.map(|namespace| TokenizerInput::Utf16(namespace.as_ref()))
.collect::<Vec<_>>();
- let selector_list = parse_selector_list_of_prelude(
- &mut self.rows.borrow_mut(),
+ // NB: Tokens that are nested too deep are not a list of component values, so they are not selectors.
+ let selector_list = parse_selector_list_of_rows(
+ prelude_rows?,
&self.names,
prelude.input(),
- prelude.range(),
&declared_namespaces,
selector_type,
)
@@ -3241,7 +3240,7 @@ impl<'a> SyntaxParseBuilder<'a> {
}
/// Starts a rule: parses its selectors, and says what a `&` names in the rules in it.
- fn begin_rule(&mut self, rule: Rule) {
+ fn begin_rule(&mut self, rule: Rule, prelude_rows: Option<&Rows>) {
let original_rule_kind = rule_kind(&rule);
let font_feature_maximum_value_count = match &rule {
Rule::At(rule) => font_feature_values_rule(rule.name.as_ref()).map(|(_, maximum)| maximum),
@@ -3258,6 +3257,7 @@ impl<'a> SyntaxParseBuilder<'a> {
Rule::Qualified(rule) if rule.prelude_is_selector => self
.parse_selector_list(
&rule.prelude,
+ prelude_rows,
if rule.nesting_parent != StyleNestingParent::None {
SelectorType::Relative
} else {
@@ -3781,8 +3781,8 @@ impl<'a> SyntaxParseBuilder<'a> {
}
impl structure::Sink for SyntaxParseBuilder<'_> {
- fn begin_rule(&mut self, rule: Rule) {
- SyntaxParseBuilder::begin_rule(self, rule);
+ fn begin_rule(&mut self, rule: Rule, prelude: Option<&Rows>) {
+ SyntaxParseBuilder::begin_rule(self, rule, prelude);
}
fn end_rule(&mut self) {
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs
index cb5cc92e380..e57562865d8 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/structure.rs
@@ -30,7 +30,7 @@ use crate::css::parser::component_value::{
use crate::css::parser::lexer::{
Escapes, Kind, Lexer, Text, Token, flag, name_of, number_of, string_of, unescape, url_of,
};
-use crate::css::parser::rows::{Name, closer_of};
+use crate::css::parser::rows::{Name, Rows, closer_of};
use crate::css::property_metadata::property_id_from_name;
use crate::css::selector_parser::StyleNestingParent;
use smallvec::SmallVec;
@@ -596,7 +596,9 @@ const MAXIMUM_RULE_NESTING_DEPTH: usize = 256;
/// What takes the rules and declarations of a source, in the order of the source.
pub(super) trait Sink {
/// A rule starts. `rule` has no declarations and no children: they come next, up to [`Sink::end_rule`].
- fn begin_rule(&mut self, rule: Rule);
+ /// `prelude` is the tokens of the prelude of a qualified rule that is a selector list, or none if they are nested
+ /// too deep to be a list of component values.
+ fn begin_rule(&mut self, rule: Rule, prelude: Option<&Rows>);
fn end_rule(&mut self);
/// A declaration of the list of declarations that is open, which the first declaration after a rule opens.
fn declaration(&mut self, declaration: Declaration);
@@ -608,7 +610,7 @@ pub(super) trait Sink {
struct NoSink;
impl Sink for NoSink {
- fn begin_rule(&mut self, _: Rule) {}
+ fn begin_rule(&mut self, _: Rule, _: Option<&Rows>) {}
fn end_rule(&mut self) {}
fn declaration(&mut self, _: Declaration) {}
fn end_declarations(&mut self) {}
@@ -621,6 +623,8 @@ pub(super) struct Core<'a, U: Unit> {
lines: LineCursor,
/// The tokens that end the blocks and functions that are open, while a component value is skipped.
closers: Vec<Kind>,
+ /// The tokens of the prelude of the qualified rule that is parsed, for the selector parser.
+ prelude_rows: Rows,
}
impl<'a, U: Unit> Core<'a, U> {
@@ -632,6 +636,7 @@ impl<'a, U: Unit> Core<'a, U> {
rule_names,
lines: LineCursor::default(),
closers: Vec::new(),
+ prelude_rows: Rows::default(),
}
}
@@ -654,8 +659,19 @@ impl<'a, U: Unit> Core<'a, U> {
/// 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.
+ #[inline]
fn skip_component_value(&mut self, may_not_be_shared: &mut bool) -> Result<usize, ()> {
+ self.skip_component_value_and::<false>(may_not_be_shared)
+ }
+
+ /// As [`Self::skip_component_value`]. With `RECORD`, appends the tokens of the component value to the rows of the
+ /// prelude.
+ #[inline(always)]
+ fn skip_component_value_and<const RECORD: bool>(&mut self, may_not_be_shared: &mut bool) -> Result<usize, ()> {
let token = self.stream.token;
+ if RECORD {
+ self.prelude_rows.push(token);
+ }
self.stream.advance();
let Some(closer) = closer_of(token.kind) else {
return Ok(token.end as usize);
@@ -676,6 +692,9 @@ impl<'a, U: Unit> Core<'a, U> {
if token.kind == Kind::EndOfFile {
return Ok(token.start as usize);
}
+ if RECORD {
+ self.prelude_rows.push(token);
+ }
self.stream.advance();
if self.closers.last() == Some(&token.kind) {
self.closers.pop();
@@ -750,7 +769,7 @@ impl<'a, U: Unit> Core<'a, U> {
rule.valid_in_context = self.at_rule_is_valid(&rule);
let context = context_for_at_rule(rule.name.as_ref());
let rule_name = OuterRuleName::At(rule.name.as_ref().into());
- sink.begin_rule(Rule::At(rule));
+ sink.begin_rule(Rule::At(rule), None);
self.rule_context.push(context);
self.rule_names.push(rule_name);
self.consume_block(sink);
@@ -768,7 +787,7 @@ impl<'a, U: Unit> Core<'a, U> {
}
}
rule.valid_in_context = self.at_rule_is_valid(&rule);
- sink.begin_rule(Rule::At(rule));
+ sink.begin_rule(Rule::At(rule), None);
sink.end_rule();
true
}
@@ -787,6 +806,8 @@ impl<'a, U: Unit> Core<'a, U> {
RuleContext::Style
};
let start = self.stream.token.start;
+ let is_selector = qualified_context == RuleContext::Style;
+ self.prelude_rows.clear();
let mut source_position = None;
// Whether the first two component values are a name that starts with two dashes, and a colon.
let mut count = 0usize;
@@ -813,17 +834,19 @@ impl<'a, U: Unit> Core<'a, U> {
}
// NB: The declarations before the rule are a list of their own.
sink.end_declarations();
- sink.begin_rule(Rule::Qualified(QualifiedRule {
+ let rows_are_valid = is_selector && self.prelude_rows.finish(token, token.start as usize).is_ok();
+ let rule = Rule::Qualified(QualifiedRule {
prelude: Prelude {
source: self.stream.storage.clone(),
range: start..token.start,
},
- prelude_is_selector: qualified_context == RuleContext::Style,
+ prelude_is_selector: is_selector,
nesting_parent: self.style_nesting_parent(),
valid_in_context: self.qualified_rule_is_valid(),
outer_rule_name: self.rule_names.last().cloned(),
source_position,
- }));
+ });
+ sink.begin_rule(rule, rows_are_valid.then_some(&self.prelude_rows));
self.rule_context.push(qualified_context);
self.rule_names.push(OuterRuleName::Context(qualified_context));
self.consume_block(sink);
@@ -840,8 +863,12 @@ impl<'a, U: Unit> Core<'a, U> {
looks_like_custom_property = starts_with_custom_name && kind == Kind::Colon;
}
count += 1;
- self.skip_component_value(&mut may_not_be_shared)
- .map_err(|()| QualifiedRuleResult::Invalid)?;
+ if is_selector {
+ self.skip_component_value_and::<true>(&mut may_not_be_shared)
+ } else {
+ self.skip_component_value(&mut may_not_be_shared)
+ }
+ .map_err(|()| QualifiedRuleResult::Invalid)?;
}
}
}
@@ -1307,7 +1334,7 @@ mod tests {
#[test]
fn does_not_nest_rules_deeper_than_the_limit() {
- use super::{Declaration, MAXIMUM_RULE_NESTING_DEPTH, Parser, Rule, Sink};
+ use super::{Declaration, MAXIMUM_RULE_NESTING_DEPTH, Parser, Rows, Rule, Sink};
#[derive(Default)]
struct Depths {
@@ -1317,7 +1344,7 @@ mod tests {
declarations: usize,
}
impl Sink for Depths {
- fn begin_rule(&mut self, _: Rule) {
+ fn begin_rule(&mut self, _: Rule, _: Option<&Rows>) {
self.rules += usize::from(self.open == 0);
self.open += 1;
self.deepest = self.deepest.max(self.open);
@@ -1348,13 +1375,13 @@ mod tests {
#[test]
fn a_value_has_no_whitespace_from_after_it() {
- use super::{Declaration, Parser, Rule, Sink, source_of};
+ use super::{Declaration, Parser, Rows, Rule, Sink, source_of};
use crate::css::parser::syntax_parser::RuleContext;
#[derive(Default)]
struct Declarations(Vec<Declaration>);
impl Sink for Declarations {
- fn begin_rule(&mut self, _: Rule) {}
+ fn begin_rule(&mut self, _: Rule, _: Option<&Rows>) {}
fn end_rule(&mut self) {}
fn declaration(&mut self, declaration: Declaration) {
self.0.push(declaration);
diff --git a/Libraries/LibWeb/Rust/src/css/selector_parser.rs b/Libraries/LibWeb/Rust/src/css/selector_parser.rs
index 492d645bb89..8bb29b18b62 100644
--- a/Libraries/LibWeb/Rust/src/css/selector_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/selector_parser.rs
@@ -1344,20 +1344,15 @@ pub(crate) fn parse_selector_list_from_component_values(
)
}
-/// Parses the selector list in `range` of `source`, which is the prelude of a qualified rule in preprocessed text.
-/// `rows` is scratch memory, and `names` holds the names of the selectors until their arena leases them.
-pub(crate) fn parse_selector_list_of_prelude(
- rows: &mut Rows,
+/// Parses the selector list whose tokens are `rows`, which is the prelude of a qualified rule in `source`, which is
+/// preprocessed text. `names` holds the names of the selectors until their arena leases them.
+pub(crate) fn parse_selector_list_of_rows(
+ rows: &Rows,
names: &std::cell::RefCell<NameCache>,
source: TokenizerInput<'_>,
- range: std::ops::Range<usize>,
declared_namespaces: &[TokenizerInput<'_>],
selector_type: SelectorType,
) -> Result<ParsedSelectorTree, ()> {
- match source {
- TokenizerInput::Latin1(units) => rows.fill(units, range)?,
- TokenizerInput::Utf16(units) => rows.fill(units, range)?,
- }
// NB: The whitespace before a rule is not part of its prelude.
parse_selector_list_with_mode(
rows.values(source, true),