Skip to content

Truly independent web browser

Meta: Remove the CSS value grammar parser

Aliaksandr Kalenikf9acd1fc57e3
diff --git a/Meta/Utils/CSSGrammar/Parser/component_values.py b/Meta/Utils/CSSGrammar/Parser/component_values.py
deleted file mode 100644
index f8faa1294d8..00000000000
--- a/Meta/Utils/CSSGrammar/Parser/component_values.py
+++ /dev/null
@@ -1,72 +0,0 @@
-from dataclasses import dataclass
-from math import inf
-from typing import Optional
-from typing import Union
-
-from Utils.css_dimensions import get_css_dimensions
-
-
-@dataclass(frozen=True)
-class NumericTypeRangeRestriction:
- minimum: float
- maximum: float
-
- def dump(self) -> str:
- return f"[{bound_value_to_string(self.minimum)},{bound_value_to_string(self.maximum)}]"
-
-
-def bound_value_to_string(value: float) -> str:
- if value == -inf:
- return "-∞"
- if value == inf:
- return "∞"
- return str(value)
-
-
-def is_dimension_type(type_name: str) -> bool:
- return type_name in get_css_dimensions().keys()
-
-
-def is_dimension_percentage_mix_type(type_name: str) -> bool:
- # https://drafts.csswg.org/css-values-4/#mixed-percentages
- return type_name in (
- "angle-percentage",
- "frequency-percentage",
- "length-percentage",
- "time-percentage",
- )
-
-
-def is_numeric_type(type_name: str) -> bool:
- # https://drafts.csswg.org/css-values-4/#numeric-data-types
- return type_name in ("integer", "number", "percentage") or is_dimension_type(type_name)
-
-
-@dataclass(frozen=True)
-class Type:
- name: str
- custom_ident_blacklist: list[str]
- numeric_type_accepted_range: Optional[NumericTypeRangeRestriction]
-
- def dump(self, indent: int) -> str:
- output = f"{'': >{indent}}Type: {self.name}"
-
- if self.custom_ident_blacklist:
- output += f" ![{', '.join(self.custom_ident_blacklist)}]"
-
- if self.numeric_type_accepted_range:
- output += f" {self.numeric_type_accepted_range.dump()}"
-
- return output + "\n"
-
-
-@dataclass(frozen=True)
-class Keyword:
- value: str
-
- def dump(self, indent: int) -> str:
- return f"{'': >{indent}}Keyword: {self.value}\n"
-
-
-# https://drafts.csswg.org/css-values-4/#component-types
-ComponentValue = Union[Type, Keyword]
diff --git a/Meta/Utils/CSSGrammar/Parser/grammar_node.py b/Meta/Utils/CSSGrammar/Parser/grammar_node.py
deleted file mode 100644
index eaf415ebbab..00000000000
--- a/Meta/Utils/CSSGrammar/Parser/grammar_node.py
+++ /dev/null
@@ -1,59 +0,0 @@
-from dataclasses import dataclass
-from enum import Enum
-
-from Utils.CSSGrammar.Parser.component_values import ComponentValue
-
-
-class GrammarNode:
- def dump(self, indent: int = 0) -> str:
- raise NotImplementedError
-
-
-# https://drafts.csswg.org/css-values-4/#component-types
-@dataclass(frozen=True)
-class ComponentValueGrammarNode(GrammarNode):
- component_value: ComponentValue
-
- def dump(self, indent: int = 0) -> str:
- return f"{'': >{indent}}ComponentValue\n" + self.component_value.dump(indent + 2)
-
-
-class CombinatorType(Enum):
- # https://drafts.csswg.org/css-values-4/#component-combinators
- # Juxtaposing components means that all of them must occur, in the given order.
- JUXTAPOSITION = "Juxtaposition"
-
- # https://drafts.csswg.org/css-values-4/#comb-one
- # A bar (|) separates two or more alternatives: exactly one of them must occur.
- ALTERNATIVES = "Alternatives"
-
-
-# https://drafts.csswg.org/css-values-4/#component-combinators
-@dataclass(frozen=True)
-class CombinatorGrammarNode(GrammarNode):
- combinator_type: CombinatorType
- children: list[GrammarNode]
-
- def dump(self, indent: int = 0) -> str:
- output = f"{'': >{indent}}Combinator({self.combinator_type.value}):\n"
-
- for child in self.children:
- output += child.dump(indent + 2)
-
- return output
-
-
-@dataclass(frozen=True)
-class GroupGrammarNode(GrammarNode):
- child: GrammarNode
-
- def dump(self, indent: int = 0) -> str:
- return f"{'': >{indent}}Group:\n" + self.child.dump(indent + 2)
-
-
-@dataclass(frozen=True)
-class OptionalGrammarNode(GrammarNode):
- child: GrammarNode
-
- def dump(self, indent: int = 0) -> str:
- return f"{'': >{indent}}Optional:\n" + self.child.dump(indent + 2)
diff --git a/Meta/Utils/CSSGrammar/Parser/parser.py b/Meta/Utils/CSSGrammar/Parser/parser.py
deleted file mode 100644
index b8bfe5f8faa..00000000000
--- a/Meta/Utils/CSSGrammar/Parser/parser.py
+++ /dev/null
@@ -1,101 +0,0 @@
-from Utils.CSSGrammar.Parser.grammar_node import CombinatorGrammarNode
-from Utils.CSSGrammar.Parser.grammar_node import CombinatorType
-from Utils.CSSGrammar.Parser.grammar_node import ComponentValueGrammarNode
-from Utils.CSSGrammar.Parser.grammar_node import GrammarNode
-from Utils.CSSGrammar.Parser.grammar_node import GroupGrammarNode
-from Utils.CSSGrammar.Parser.grammar_node import OptionalGrammarNode
-from Utils.CSSGrammar.Parser.token import Token
-from Utils.CSSGrammar.Parser.token import TokenType
-from Utils.CSSGrammar.Parser.tokenizer import Tokenizer
-
-
-class Parser:
- def __init__(self, tokens: list[Token]) -> None:
- self.tokens = tokens
- self.index = 0
-
- @classmethod
- def parse_value_definition_grammar(cls, input: str) -> GrammarNode:
- parser = cls(Tokenizer.tokenize(input))
-
- value = parser.parse_alternatives()
-
- if not parser.peek().is_token_type(TokenType.END_OF_FILE):
- raise SyntaxError("CSSGrammar::Parser: Unexpected trailing input")
-
- return value
-
- def parse_alternatives(self) -> GrammarNode:
- children = [self.parse_juxtaposition()]
-
- while self.peek().is_token_type(TokenType.SINGLE_BAR):
- self.consume()
- children.append(self.parse_juxtaposition())
-
- if len(children) == 1:
- return children[0]
-
- return CombinatorGrammarNode(CombinatorType.ALTERNATIVES, children)
-
- def parse_juxtaposition(self) -> GrammarNode:
- children = [self.parse_component_value()]
-
- while self.next_token_starts_component_value():
- children.append(self.parse_component_value())
-
- if len(children) == 1:
- return children[0]
-
- return CombinatorGrammarNode(CombinatorType.JUXTAPOSITION, children)
-
- def parse_component_value(self) -> GrammarNode:
- # https://drafts.csswg.org/css-values-4/#component-multipliers
- # FIXME: Support component multipliers
-
- peeked = self.peek()
- component_value = None
-
- if peeked.is_token_type(TokenType.OPEN_SQUARE_BRACKET):
- self.consume()
- group = self.parse_alternatives()
-
- if not self.peek().is_token_type(TokenType.CLOSE_SQUARE_BRACKET):
- raise SyntaxError("CSSGrammar::Parser: Expected ']'")
-
- # FIXME: Support required groups (e.g. [ <foo>? ]!)
- self.consume()
- component_value = GroupGrammarNode(group)
-
- if peeked.is_token_type(TokenType.COMPONENT_VALUE):
- component_value = ComponentValueGrammarNode(self.consume().component_value())
-
- if component_value is None:
- raise SyntaxError("CSSGrammar::Parser: Expected a component value")
-
- if self.peek().is_token_type(TokenType.QUESTION_MARK):
- self.consume()
- component_value = OptionalGrammarNode(component_value)
-
- return component_value
-
- def next_token_starts_component_value(self) -> bool:
- return self.peek().token_type in (
- TokenType.OPEN_SQUARE_BRACKET,
- TokenType.COMPONENT_VALUE,
- )
-
- def peek(self, offset: int = 0) -> Token:
- index = min(self.index + offset, len(self.tokens) - 1)
- return self.tokens[index]
-
- def consume(self) -> Token:
- token = self.peek()
-
- if not token.is_token_type(TokenType.END_OF_FILE):
- self.index += 1
-
- return token
-
-
-def parse_value_definition_grammar(input: str) -> GrammarNode:
- return Parser.parse_value_definition_grammar(input)
diff --git a/Meta/Utils/CSSGrammar/Parser/token.py b/Meta/Utils/CSSGrammar/Parser/token.py
deleted file mode 100644
index edf98156f6b..00000000000
--- a/Meta/Utils/CSSGrammar/Parser/token.py
+++ /dev/null
@@ -1,36 +0,0 @@
-from dataclasses import dataclass
-from enum import Enum
-from typing import Optional
-
-from Utils.CSSGrammar.Parser.component_values import ComponentValue
-
-
-class TokenType(Enum):
- END_OF_FILE = "end-of-file"
- SINGLE_BAR = "single-bar"
- OPEN_SQUARE_BRACKET = "open-square-bracket"
- CLOSE_SQUARE_BRACKET = "close-square-bracket"
- QUESTION_MARK = "question-mark"
- COMPONENT_VALUE = "component-value"
-
-
-@dataclass(frozen=True)
-class Token:
- token_type: TokenType
- value: Optional[ComponentValue]
-
- @classmethod
- def create(cls, token_type: TokenType) -> "Token":
- return cls(token_type, None)
-
- @classmethod
- def create_component_value(cls, component_value: ComponentValue) -> "Token":
- return cls(TokenType.COMPONENT_VALUE, component_value)
-
- def is_token_type(self, token_type: TokenType) -> bool:
- return self.token_type == token_type
-
- def component_value(self) -> ComponentValue:
- assert self.token_type == TokenType.COMPONENT_VALUE and self.value is not None
-
- return self.value
diff --git a/Meta/Utils/CSSGrammar/Parser/tokenizer.py b/Meta/Utils/CSSGrammar/Parser/tokenizer.py
deleted file mode 100644
index 7a4053ebb4d..00000000000
--- a/Meta/Utils/CSSGrammar/Parser/tokenizer.py
+++ /dev/null
@@ -1,179 +0,0 @@
-from math import inf
-
-from Utils.CSSGrammar.Parser.component_values import Keyword
-from Utils.CSSGrammar.Parser.component_values import NumericTypeRangeRestriction
-from Utils.CSSGrammar.Parser.component_values import Type
-from Utils.CSSGrammar.Parser.component_values import is_dimension_percentage_mix_type
-from Utils.CSSGrammar.Parser.component_values import is_dimension_type
-from Utils.CSSGrammar.Parser.component_values import is_numeric_type
-from Utils.CSSGrammar.Parser.token import Token
-from Utils.CSSGrammar.Parser.token import TokenType
-from Utils.lexer import Lexer
-
-
-def is_identifier_character(ch: str) -> bool:
- return ch.isascii() and (ch.isalnum() or ch == "-")
-
-
-class Tokenizer:
- def __init__(self, input: str) -> None:
- self.lexer = Lexer(input)
-
- @classmethod
- def tokenize(cls, input: str) -> list[Token]:
- return cls(input).tokenize_impl()
-
- def tokenize_impl(self) -> list[Token]:
- tokens: list[Token] = []
-
- while True:
- self.discard_whitespace()
- if self.lexer.is_eof():
- tokens.append(Token.create(TokenType.END_OF_FILE))
- return tokens
-
- tokens.append(self.consume_a_token())
-
- def discard_whitespace(self) -> None:
- self.lexer.ignore_while(lambda ch: ch.isspace() and ch.isascii())
-
- def consume_an_identifier(self) -> str:
- return self.lexer.consume_while(is_identifier_character)
-
- def consume_a_token(self) -> Token:
- peeked = self.lexer.peek()
- if peeked == "|":
- self.lexer.consume()
- return Token.create(TokenType.SINGLE_BAR)
- if peeked == "[":
- self.lexer.consume()
- return Token.create(TokenType.OPEN_SQUARE_BRACKET)
- if peeked == "]":
- self.lexer.consume()
- return Token.create(TokenType.CLOSE_SQUARE_BRACKET)
- if peeked == "?":
- self.lexer.consume()
- return Token.create(TokenType.QUESTION_MARK)
- if peeked == "<":
- return self.consume_a_non_terminal_token()
-
- if is_identifier_character(peeked):
- return self.consume_a_keyword_token()
-
- raise SyntaxError("CSSGrammar::Tokenizer: Unexpected character")
-
- def consume_custom_ident_blacklist(self) -> list[str]:
- # NB: This notation isn't yet included in the spec but we use it internally and the CSSWG has resolved to add it in
- # https://github.com/w3c/csswg-drafts/issues/11924
-
- self.discard_whitespace()
-
- if not self.lexer.consume_specific("!["):
- return []
-
- blacklist: list[str] = []
-
- while True:
- self.discard_whitespace()
-
- ident = self.consume_an_identifier()
- if not ident:
- raise SyntaxError("Expected identifier in custom-ident blacklist")
-
- blacklist.append(ident)
-
- self.discard_whitespace()
- if self.lexer.consume_specific("]"):
- return blacklist
-
- if not self.lexer.consume_specific(","):
- raise SyntaxError("Expected ',' in custom-ident blacklist")
-
- # https://drafts.csswg.org/css-values-4/#css-bracketed-range-notation
- def consume_bracketed_range_notation(self, type_name: str) -> NumericTypeRangeRestriction:
- self.discard_whitespace()
-
- # If no range is indicated, either by using the bracketed range notation or in the property description, then
- # [-∞,∞] is assumed.
- if not self.lexer.consume_specific("["):
- return NumericTypeRangeRestriction(-inf, inf)
-
- self.discard_whitespace()
- minimum = self.consume_bracketed_range_bound(type_name)
-
- self.discard_whitespace()
- if not self.lexer.consume_specific(","):
- raise SyntaxError("Expected ',' in bracketed range notation")
-
- self.discard_whitespace()
- maximum = self.consume_bracketed_range_bound(type_name)
-
- self.discard_whitespace()
- if not self.lexer.consume_specific("]"):
- raise SyntaxError("Expected ']' to close bracketed range notation")
-
- return NumericTypeRangeRestriction(minimum, maximum)
-
- def consume_bracketed_range_bound(self, type_name: str) -> float:
- # Values of -∞ or ∞ must be written without units, even if the value type uses units.
- if self.lexer.consume_specific("-∞"):
- return -inf
-
- if self.lexer.consume_specific("∞"):
- return inf
-
- # FIXME: Do we need to allow non-integer values?
- bound_value = self.consume_decimal_integer()
-
- if bound_value != 0 and (is_dimension_percentage_mix_type(type_name) or type_name == "length"):
- raise SyntaxError("Types with units not resolvable at parse time only support zero and infinite bounds")
-
- # FIXME: Validate and store the unit, for now we drop it and assume it was the relevant canonical unit.
- unit = self.lexer.consume_while(is_identifier_character)
-
- if unit and not is_dimension_type(type_name) and not is_dimension_percentage_mix_type(type_name):
- raise SyntaxError("Unexpected unit for unitless bound value")
-
- if not unit and bound_value != 0 and is_dimension_type(type_name):
- raise SyntaxError("Expected unit for non-zero, non-infinite bound value")
-
- return float(bound_value)
-
- def consume_decimal_integer(self) -> int:
- sign = 1
- if self.lexer.consume_specific("-"):
- sign = -1
-
- digits = self.lexer.consume_while(lambda ch: ch.isdigit())
- if not digits:
- raise SyntaxError("Expected decimal integer")
-
- return sign * int(digits)
-
- def consume_a_non_terminal_token(self) -> Token:
- assert self.lexer.consume_specific("<")
-
- name = self.consume_an_identifier()
-
- if not name:
- raise SyntaxError("CSSGrammar::Tokenizer: Expected a type name")
-
- custom_ident_blacklist = []
- if name == "custom-ident":
- custom_ident_blacklist = self.consume_custom_ident_blacklist()
-
- numeric_type_accepted_range = None
- if is_numeric_type(name) or is_dimension_percentage_mix_type(name):
- numeric_type_accepted_range = self.consume_bracketed_range_notation(name)
-
- if not self.lexer.consume_specific(">"):
- raise SyntaxError("CSSGrammar::Tokenizer: Expected '>'")
-
- return Token.create_component_value(Type(name, custom_ident_blacklist, numeric_type_accepted_range))
-
- def consume_a_keyword_token(self) -> Token:
- value = self.consume_an_identifier()
-
- assert value
-
- return Token.create_component_value(Keyword(value))
diff --git a/Meta/Utils/CSSGrammar/generator.py b/Meta/Utils/CSSGrammar/generator.py
deleted file mode 100644
index 6b3dade6fb8..00000000000
--- a/Meta/Utils/CSSGrammar/generator.py
+++ /dev/null
@@ -1,179 +0,0 @@
-from math import inf
-from typing import TextIO
-
-from Utils.CSSGrammar.Parser.component_values import Keyword
-from Utils.CSSGrammar.Parser.component_values import Type
-from Utils.CSSGrammar.Parser.component_values import is_dimension_percentage_mix_type
-from Utils.CSSGrammar.Parser.grammar_node import CombinatorGrammarNode
-from Utils.CSSGrammar.Parser.grammar_node import CombinatorType
-from Utils.CSSGrammar.Parser.grammar_node import ComponentValueGrammarNode
-from Utils.CSSGrammar.Parser.grammar_node import GrammarNode
-from Utils.CSSGrammar.Parser.grammar_node import GroupGrammarNode
-from Utils.CSSGrammar.Parser.grammar_node import OptionalGrammarNode
-from Utils.CSSGrammar.Parser.parser import parse_value_definition_grammar
-from Utils.utils import snake_casify
-from Utils.utils import title_casify
-
-
-def bound_value_to_code(value: float, type_name: str) -> str:
- if value == -inf:
- return "AK::NumericLimits<i32>::min()" if type_name == "integer" else "AK::NumericLimits<float>::lowest()"
- if value == inf:
- return "AK::NumericLimits<i32>::max()" if type_name == "integer" else "AK::NumericLimits<float>::max()"
- return str(value)
-
-
-def generate_css_parser_expression_for_type_component_value(out: TextIO, cpp_name: str, type: Type) -> None:
- type_name = snake_casify(type.name)
-
- additional_arguments = ""
- if type.custom_ident_blacklist:
- additional_arguments = ", ReadonlySpan<Utf16View> { "
-
- if len(type.custom_ident_blacklist) > 0:
- disallowed_idents = "".join(f'"{disallowed_ident}"sv, ' for disallowed_ident in type.custom_ident_blacklist)
- additional_arguments += f"Array<Utf16View, {len(type.custom_ident_blacklist)}> {{{disallowed_idents}}}"
-
- additional_arguments += "}"
-
- if type.numeric_type_accepted_range is not None:
- minimum = bound_value_to_code(type.numeric_type_accepted_range.minimum, type_name)
- maximum = bound_value_to_code(type.numeric_type_accepted_range.maximum, type_name)
- accepted_range = f", {{ {minimum}, {maximum} }}"
-
- additional_arguments += accepted_range
-
- # NB: Pass the accepted range twice for dimension-percentage mixes, once for the dimension and once for the percentage.
- if is_dimension_percentage_mix_type(type.name):
- additional_arguments += accepted_range
-
- out.write(f"auto {cpp_name} = parse_{type_name}_value(tokens{additional_arguments});\n")
-
-
-def generate_css_parser_expression_for_keyword_component_value(out: TextIO, cpp_name: str, keyword: Keyword) -> None:
- keyword_name = title_casify(keyword.value)
- out.write(f"auto {cpp_name} = parse_specific_keyword_value(tokens, {{ {{ Keyword::{keyword_name} }} }});\n")
-
-
-def generate_css_parser_expression_for_component_value_grammar_node(
- out: TextIO, cpp_name: str, grammar_node: ComponentValueGrammarNode
-) -> None:
- component_value = grammar_node.component_value
- if isinstance(component_value, Type):
- generate_css_parser_expression_for_type_component_value(out, cpp_name, component_value)
- return
- assert isinstance(component_value, Keyword)
- generate_css_parser_expression_for_keyword_component_value(out, cpp_name, component_value)
-
-
-def generate_css_parser_expression_for_alternatives(
- out: TextIO, cpp_name: str, alternatives: list[GrammarNode]
-) -> None:
- out.write(f"auto const parse_{cpp_name}_alternatives = [&]() -> RefPtr<StyleValue const> {{\n")
-
- # NB: As an optimization we combine all keyword alternatives into a single parse_specific_keyword_value call to
- # avoid unnecessary backtracking in the common case of multiple keyword alternatives.
- keyword_alternatives: list[str] = []
-
- for i, alternative in enumerate(alternatives):
- if isinstance(alternative, ComponentValueGrammarNode) and isinstance(alternative.component_value, Keyword):
- keyword_alternatives.append(alternative.component_value.value)
- continue
-
- alternative_name = f"{cpp_name}_alternative_{i}"
- generate_css_parser_expression_for_grammar_node(out, alternative_name, alternative)
- out.write(f"""if ({alternative_name})
- return {alternative_name};
-""")
-
- if keyword_alternatives:
- keyword_alternatives_names = ", ".join(f"Keyword::{title_casify(keyword)}" for keyword in keyword_alternatives)
- out.write(f"""auto {cpp_name}_keyword_alternative = parse_specific_keyword_value(tokens, {{ {{ {keyword_alternatives_names} }} }});
-if ({cpp_name}_keyword_alternative)
- return {cpp_name}_keyword_alternative;
-""")
-
- out.write(f"""return nullptr;
-}};
-
-auto {cpp_name} = parse_{cpp_name}_alternatives();
-""")
-
-
-def generate_css_parser_expression_for_juxtaposition(out: TextIO, cpp_name: str, children: list[GrammarNode]) -> None:
- out.write(f"""auto const parse_{cpp_name}_juxtaposition = [&]() -> RefPtr<StyleValue const> {{
-auto {cpp_name}_transaction = tokens.begin_transaction();
-StyleValueVector {cpp_name}_values;
-{cpp_name}_values.ensure_capacity({len(children)});
-
-""")
-
- for i, component in enumerate(children):
- component_name = f"{cpp_name}_component_{i}"
- generate_css_parser_expression_for_grammar_node(out, component_name, component)
- out.write(f"""if (!{component_name})
- return nullptr;
-
-{cpp_name}_values.append({component_name}.release_nonnull());
-""")
-
- out.write(f"""{cpp_name}_transaction.commit();
-return StyleValueList::create(move({cpp_name}_values), StyleValueList::Separator::Space, StyleValueList::Collapsible::No);
-}};
-
-auto {cpp_name} = parse_{cpp_name}_juxtaposition();
-""")
-
-
-def generate_css_parser_expression_for_combinator_grammar_node(
- out: TextIO, cpp_name: str, grammar_node: CombinatorGrammarNode
-) -> None:
- if grammar_node.combinator_type == CombinatorType.JUXTAPOSITION:
- generate_css_parser_expression_for_juxtaposition(out, cpp_name, grammar_node.children)
- return
-
- if grammar_node.combinator_type == CombinatorType.ALTERNATIVES:
- generate_css_parser_expression_for_alternatives(out, cpp_name, grammar_node.children)
- return
-
- raise TypeError(f"Unhandled combinator type: {grammar_node.combinator_type}")
-
-
-def generate_css_parser_expression_for_group_grammar_node(
- out: TextIO, cpp_name: str, grammar_node: GroupGrammarNode
-) -> None:
- generate_css_parser_expression_for_grammar_node(out, cpp_name, grammar_node.child)
-
-
-def generate_css_parser_expression_for_optional_grammar_node(
- out: TextIO, cpp_name: str, grammar_node: OptionalGrammarNode
-) -> None:
- out.write(f"""RefPtr<StyleValue const> {cpp_name} = StyleValue::create_empty_optional();
-""")
-
- generate_css_parser_expression_for_grammar_node(out, f"maybe_{cpp_name}", grammar_node.child)
-
- out.write(f"""if (maybe_{cpp_name})
- {cpp_name} = maybe_{cpp_name};
-""")
-
-
-def generate_css_parser_expression_for_grammar_node(out: TextIO, cpp_name: str, grammar_node: GrammarNode) -> None:
- if isinstance(grammar_node, ComponentValueGrammarNode):
- generate_css_parser_expression_for_component_value_grammar_node(out, cpp_name, grammar_node)
- return
- if isinstance(grammar_node, GroupGrammarNode):
- generate_css_parser_expression_for_group_grammar_node(out, cpp_name, grammar_node)
- return
- if isinstance(grammar_node, OptionalGrammarNode):
- generate_css_parser_expression_for_optional_grammar_node(out, cpp_name, grammar_node)
- return
- if isinstance(grammar_node, CombinatorGrammarNode):
- generate_css_parser_expression_for_combinator_grammar_node(out, cpp_name, grammar_node)
- return
-
- raise TypeError(f"Unhandled grammar node type: {type(grammar_node).__name__}")
-
-
-def generate_css_parser_expression_for_grammar(out: TextIO, cpp_name: str, grammar: str) -> None:
- generate_css_parser_expression_for_grammar_node(out, cpp_name, parse_value_definition_grammar(grammar))
diff --git a/Tests/Meta/CMakeLists.txt b/Tests/Meta/CMakeLists.txt
index 6f05a8c94c5..90cb2123a9c 100644
--- a/Tests/Meta/CMakeLists.txt
+++ b/Tests/Meta/CMakeLists.txt
@@ -1,13 +1,4 @@
if (NOT WIN32)
- add_custom_target(test-css-grammar-parser ALL DEPENDS "${CMAKE_BINARY_DIR}/bin/test-css-grammar-parser.py")
- add_custom_command(
- OUTPUT "${CMAKE_BINARY_DIR}/bin/test-css-grammar-parser.py"
- COMMAND "${CMAKE_COMMAND}" -E copy "${ladybird_SOURCE_DIR}/Tests/Meta/test-css-grammar-parser.py" "${CMAKE_BINARY_DIR}/bin/test-css-grammar-parser.py"
- DEPENDS "${ladybird_SOURCE_DIR}/Tests/Meta/test-css-grammar-parser.py"
- )
- add_test(NAME test-css-grammar-parser COMMAND "${Python3_EXECUTABLE}" "${CMAKE_BINARY_DIR}/bin/test-css-grammar-parser.py")
- set_tests_properties(test-css-grammar-parser PROPERTIES ENVIRONMENT LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR})
-
add_custom_target(test-xctrace-time-profile ALL DEPENDS "${CMAKE_BINARY_DIR}/bin/test-xctrace-time-profile.py")
add_custom_command(
OUTPUT "${CMAKE_BINARY_DIR}/bin/test-xctrace-time-profile.py"
diff --git a/Tests/Meta/test-css-grammar-parser.py b/Tests/Meta/test-css-grammar-parser.py
deleted file mode 100644
index 40774ec54dc..00000000000
--- a/Tests/Meta/test-css-grammar-parser.py
+++ /dev/null
@@ -1,347 +0,0 @@
-import os
-import sys
-import unittest
-
-from pathlib import Path
-
-sys.path.insert(0, str(Path(os.environ["LADYBIRD_SOURCE_DIR"]) / "Meta"))
-
-from Utils.css_dimensions import load_css_dimensions
-from Utils.CSSGrammar.Parser.parser import parse_value_definition_grammar
-
-load_css_dimensions(str(Path(os.environ["LADYBIRD_SOURCE_DIR"]).joinpath("Libraries/LibWeb/CSS/Units.json")))
-
-
-class TestCSSGrammarParser(unittest.TestCase):
- def test_parse_type_reference(self) -> None:
- syntax = parse_value_definition_grammar("<foo>")
- self.assertEqual(
- syntax.dump(),
- """ComponentValue
- Type: foo
-""",
- )
-
- def test_parse_hyphenated_type_reference(self) -> None:
- syntax = parse_value_definition_grammar("<foo-bar>")
- self.assertEqual(
- syntax.dump(),
- """ComponentValue
- Type: foo-bar
-""",
- )
-
- def test_parse_custom_ident_blacklist(self) -> None:
- syntax = parse_value_definition_grammar("<custom-ident ![foo, bar-baz]>")
- self.assertEqual(
- syntax.dump(),
- """ComponentValue
- Type: custom-ident ![foo, bar-baz]
-""",
- )
-
- def test_parse_unitless_numeric_type_bracketed_range_notation(self) -> None:
- for value, expected in (
- ("<number [1,∞]>", "number [1.0,∞]"),
- ("<integer [1,∞]>", "integer [1.0,∞]"),
- ("<percentage [1,100]>", "percentage [1.0,100.0]"),
- ):
- with self.subTest(value=value):
- syntax = parse_value_definition_grammar(value)
- self.assertEqual(
- syntax.dump(),
- f"""ComponentValue
- Type: {expected}
-""",
- )
-
- def test_parse_type_percentage_bracketed_range_notation(self) -> None:
- syntax = parse_value_definition_grammar("<length-percentage [0,∞]>")
- self.assertEqual(
- syntax.dump(),
- """ComponentValue
- Type: length-percentage [0.0,∞]
-""",
- )
-
- def test_parse_numeric_type_without_bracketed_range_notation_defaults_to_infinite_range(self) -> None:
- syntax = parse_value_definition_grammar("<number>")
- self.assertEqual(
- syntax.dump(),
- """ComponentValue
- Type: number [-∞,∞]
-""",
- )
-
- def test_parse_keyword(self) -> None:
- syntax = parse_value_definition_grammar("auto")
- self.assertEqual(
- syntax.dump(),
- """ComponentValue
- Keyword: auto
-""",
- )
-
- def test_parse_hyphenated_keyword(self) -> None:
- syntax = parse_value_definition_grammar("max-content")
- self.assertEqual(
- syntax.dump(),
- """ComponentValue
- Keyword: max-content
-""",
- )
-
- def test_parse_keyword_alternatives(self) -> None:
- syntax = parse_value_definition_grammar("auto | none | <length>")
- self.assertEqual(
- syntax.dump(),
- """Combinator(Alternatives):
- ComponentValue
- Keyword: auto
- ComponentValue
- Keyword: none
- ComponentValue
- Type: length [-∞,∞]
-""",
- )
-
- def test_parse_alternatives(self) -> None:
- syntax = parse_value_definition_grammar("<foo> | <bar> | <baz>")
- self.assertEqual(
- syntax.dump(),
- """Combinator(Alternatives):
- ComponentValue
- Type: foo
- ComponentValue
- Type: bar
- ComponentValue
- Type: baz
-""",
- )
-
- def test_parse_juxtaposition(self) -> None:
- syntax = parse_value_definition_grammar("<foo> <bar> baz")
- self.assertEqual(
- syntax.dump(),
- """Combinator(Juxtaposition):
- ComponentValue
- Type: foo
- ComponentValue
- Type: bar
- ComponentValue
- Keyword: baz
-""",
- )
-
- def test_parse_juxtaposition_has_higher_precedence_than_alternatives(self) -> None:
- syntax = parse_value_definition_grammar("<foo> <bar> | <baz>")
- self.assertEqual(
- syntax.dump(),
- """Combinator(Alternatives):
- Combinator(Juxtaposition):
- ComponentValue
- Type: foo
- ComponentValue
- Type: bar
- ComponentValue
- Type: baz
-""",
- )
-
- def test_parse_grouped_alternatives_in_juxtaposition(self) -> None:
- syntax = parse_value_definition_grammar("[ <foo> | <bar> ] <baz>")
- self.assertEqual(
- syntax.dump(),
- """Combinator(Juxtaposition):
- Group:
- Combinator(Alternatives):
- ComponentValue
- Type: foo
- ComponentValue
- Type: bar
- ComponentValue
- Type: baz
-""",
- )
-
- def test_parse_group(self) -> None:
- syntax = parse_value_definition_grammar("[ <length> ]")
- self.assertEqual(
- syntax.dump(),
- """Group:
- ComponentValue
- Type: length [-∞,∞]
-""",
- )
-
- def test_parse_grouped_alternatives(self) -> None:
- syntax = parse_value_definition_grammar("[ auto | none | <length> ]")
- self.assertEqual(
- syntax.dump(),
- """Group:
- Combinator(Alternatives):
- ComponentValue
- Keyword: auto
- ComponentValue
- Keyword: none
- ComponentValue
- Type: length [-∞,∞]
-""",
- )
-
- def test_parse_groups_as_alternative(self) -> None:
- syntax = parse_value_definition_grammar("[ auto | none ] | <length>")
- self.assertEqual(
- syntax.dump(),
- """Combinator(Alternatives):
- Group:
- Combinator(Alternatives):
- ComponentValue
- Keyword: auto
- ComponentValue
- Keyword: none
- ComponentValue
- Type: length [-∞,∞]
-""",
- )
-
- def test_parse_optional_type_reference(self) -> None:
- syntax = parse_value_definition_grammar("<foo>?")
- self.assertEqual(
- syntax.dump(),
- """Optional:
- ComponentValue
- Type: foo
-""",
- )
-
- def test_parse_optional_group(self) -> None:
- syntax = parse_value_definition_grammar("[ auto | none ]?")
- self.assertEqual(
- syntax.dump(),
- """Optional:
- Group:
- Combinator(Alternatives):
- ComponentValue
- Keyword: auto
- ComponentValue
- Keyword: none
-""",
- )
-
- def test_parse_ignores_whitespace_around_tokens(self) -> None:
- syntax = parse_value_definition_grammar(" <foo>\t|\n<bar> ")
- self.assertEqual(
- syntax.dump(),
- """Combinator(Alternatives):
- ComponentValue
- Type: foo
- ComponentValue
- Type: bar
-""",
- )
-
- def test_reject_empty_input(self) -> None:
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar("")
-
- def test_reject_standalone_bar(self) -> None:
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar("|")
-
- def test_reject_trailing_bar(self) -> None:
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar("<foo> |")
-
- def test_reject_invalid_optional(self) -> None:
- for value in (
- "?",
- "<foo>??",
- "[ <foo> ]??",
- ):
- with self.subTest(value=value):
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar(value)
-
- def test_reject_invalid_group(self) -> None:
- for value in (
- "[]",
- "[ <foo>",
- "<foo> ]",
- "[ <foo> | ]",
- ):
- with self.subTest(value=value):
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar(value)
-
- def test_reject_invalid_type_reference(self) -> None:
- for value in (
- "<>",
- "<foo",
- "<foo/auto>",
- "<length ![foo]>",
- "<custom-ident ![]>",
- "<custom-ident ![foo bar]>",
- "<custom-ident ![foo,]>",
- "<custom-ident ![foo>",
- ):
- with self.subTest(value=value):
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar(value)
-
- def test_reject_invalid_bracketed_range_notation(self) -> None:
- for value in (
- "<number [0 ∞]>",
- "<number [0,∞>",
- "<number [,∞]>",
- "<number [1,]>",
- "<number [1]>",
- ):
- with self.subTest(value=value):
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar(value)
-
- def test_reject_bracketed_range_notation_on_non_numeric_data_types(self) -> None:
- for value in (
- "<color [0,∞]>",
- "<custom-ident [0,∞]>",
- ):
- with self.subTest(value=value):
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar(value)
-
- def test_reject_units_on_unitless_bracketed_range_bounds(self) -> None:
- for value in (
- "<number [1px,∞]>",
- "<integer [1px,∞]>",
- "<percentage [1px,100px]>",
- ):
- with self.subTest(value=value):
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar(value)
-
- def test_reject_units_on_infinite_bracketed_range_bounds(self) -> None:
- for value in (
- "<length [0,∞px]>",
- "<length [-∞px,0]>",
- ):
- with self.subTest(value=value):
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar(value)
-
- def test_reject_non_zero_non_infinite_bounds_on_types_with_units_not_resolvable_at_parse_time(self) -> None:
- for value in (
- "<length [1px,10px]>",
- "<angle-percentage [1deg,360deg]>",
- ):
- with self.subTest(value=value):
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar(value)
-
- def test_unit_required_for_non_zero_non_infinite_bounds(self) -> None:
- with self.assertRaises(SyntaxError):
- parse_value_definition_grammar("<angle [-90,90]>")
-
-
-if __name__ == "__main__":
- unittest.main()