Skip to main content

muskitty_css_parser/
types.rs

1//! CSS Parsing Results data structures (§5.2).
2//!
3//! Per §5.2 L1625-1721 of CSS Syntax Module Level 3: the result of
4//! parsing can be a stylesheet, a rule (at-rule or qualified rule), a
5//! declaration, or a component value (preserved token, function, or
6//! simple block).
7
8use muskitty_css_tokenizer::Token;
9
10/// §5.2 L1632-1633: A stylesheet has a list of rules.
11#[derive(Debug, Clone, Default)]
12pub struct Stylesheet {
13    pub rules: Vec<Rule>,
14}
15
16/// §5.2 L1635-1637: A rule is either an at-rule or a qualified rule.
17///
18/// Also carries a `Declarations` variant (§5.5.5 L2492-2498) for the
19/// mixed list output of `consume_a_blocks_contents` — a block's
20/// contents can be a sequence of declarations interleaved with rules,
21/// and we model each declaration-list run as a `Rule::Declarations`.
22#[derive(Debug, Clone)]
23pub enum Rule {
24    AtRule(AtRule),
25    QualifiedRule(QualifiedRule),
26    /// §5.5.5: a list of declarations (a "run" of consecutive
27    /// declarations inside a block, before the next child rule). At
28    /// the CSSOM boundary this gets materialized as either
29    /// `CSSStyleDeclaration` or `CSSNestedDeclarations`.
30    Declarations(Vec<Declaration>),
31}
32
33/// §5.2 L1639-1650: An at-rule has a name, a prelude (list of component
34/// values), and optionally a list of declarations and a list of child
35/// rules (only for "block at-rules" ending in a {}-block).
36#[derive(Debug, Clone)]
37pub struct AtRule {
38    /// The at-rule name (e.g. "media", "import"). Does not include the
39    /// leading `@`.
40    pub name: String,
41    /// The prelude: component values between the name and the block
42    /// or semicolon.
43    pub prelude: Vec<ComponentValue>,
44    /// Block at-rules only: declarations inside the {}-block. `None`
45    /// for statement at-rules (ending in `;`).
46    pub declarations: Option<Vec<Declaration>>,
47    /// Block at-rules only: child rules inside the {}-block. `None`
48    /// for statement at-rules.
49    pub child_rules: Option<Vec<Rule>>,
50}
51
52/// §5.2 L1652-1657: A qualified rule has a prelude, declarations, and
53/// child rules.
54#[derive(Debug, Clone)]
55pub struct QualifiedRule {
56    /// The prelude (e.g. a selector for style rules).
57    pub prelude: Vec<ComponentValue>,
58    /// Declarations inside the {}-block.
59    pub declarations: Vec<Declaration>,
60    /// Child rules inside the {}-block (for nested rules like
61    /// `@media`).
62    pub child_rules: Vec<Rule>,
63}
64
65/// §5.2 L1663-1669: A declaration has a name, a value (list of
66/// component values), an `important` flag, and an optional
67/// `original_text`.
68#[derive(Debug, Clone)]
69pub struct Declaration {
70    /// The property or descriptor name (e.g. "color",
71    /// "font-family").
72    pub name: String,
73    /// The value: component values between `:` and `;` (or end of
74    /// block).
75    pub value: Vec<ComponentValue>,
76    /// Whether the declaration had an `!important` flag.
77    pub important: bool,
78    /// §5.2 L1668-1669 + §5.5.6 L2693-2698: only set for custom
79    /// property declarations (`--foo: ...`), to allow var()
80    /// resolution to access the original source text.
81    pub original_text: Option<String>,
82}
83
84/// §5.2 L1681-1685: A component value is one of the preserved tokens,
85/// a function, or a simple block.
86#[derive(Debug, Clone)]
87pub enum ComponentValue {
88    /// §5.2 L1687-1703: A preserved token (any token except
89    /// function-token, `{-token`, `(-token`, `[-token` — those are
90    /// always consumed into higher-level objects).
91    PreservedToken(Token),
92    /// §5.2 L1705-1708: A function.
93    Function(Function),
94    /// §5.2 L1710-1719: A simple block.
95    SimpleBlock(SimpleBlock),
96}
97
98/// §5.2 L1705-1708: A function has a name and a value (list of
99/// component values).
100#[derive(Debug, Clone)]
101pub struct Function {
102    /// The function name (e.g. "translate", "var"). Does not include
103    /// the leading ident or the trailing `(`.
104    pub name: String,
105    /// The arguments: component values between `(` and `)`.
106    pub value: Vec<ComponentValue>,
107}
108
109/// §5.2 L1710-1719: A simple block has an associated token (the
110/// opening token) and a value (list of component values).
111#[derive(Debug, Clone)]
112pub struct SimpleBlock {
113    /// Which kind of block this is: `{}`, `[]`, or `()`.
114    pub kind: BlockKind,
115    /// The component values inside the block.
116    pub value: Vec<ComponentValue>,
117}
118
119/// §5.2 L1710-1719: The associated token kind of a simple block,
120/// mirroring the opening `{` / `[` / `(`.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122pub enum BlockKind {
123    /// `{}-block` (L1718): opens with `{-token`, closes with
124    /// `}-token`.
125    Curly,
126    /// `[]-block` (L1718): opens with `[-token`, closes with
127    /// `]-token`.
128    Square,
129    /// `()-block` (L1718): opens with `(-token`, closes with
130    /// `)-token`.
131    Paren,
132}
133
134/// Error returned by parser algorithms when an explicit "parse error"
135/// path is taken per WHATWG §5.5 (e.g. `consume_a_qualified_rule`'s
136/// "parse error: return a syntax error" step at L2330).
137///
138/// This is a marker type — it carries no diagnostic payload because
139/// the WHATWG algorithms themselves do not specify any. Higher-level
140/// callers (CSSOM) decide whether to drop the result, log it, or
141/// surface a structured error.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub enum ParseError {
144    /// 通用语法错误,携带人类可读的诊断信息。
145    ///
146    /// Line/column tracking is deferred until the tokenizer exposes
147    /// per-token position metadata.
148    Generic(String),
149    /// 组件值嵌套深度超过 [`MAX_NESTING_DEPTH`]。
150    ///
151    /// 用于阻止恶意 CSS(如 10,000 层 `{{{{...}}}}` / `((((...))))`)
152    /// 触发递归栈溢出(DoS)。触发后解析器停止下降,按 §5.5 的
153    /// 解析错误恢复语义继续处理后续 token。
154    ///
155    /// [`MAX_NESTING_DEPTH`]: crate::token_stream::MAX_NESTING_DEPTH
156    NestingTooDeep { depth: u32, limit: u32 },
157}
158
159impl ParseError {
160    /// Create a parse error with a diagnostic message.
161    pub fn new(message: impl Into<String>) -> Self {
162        ParseError::Generic(message.into())
163    }
164}
165
166impl std::fmt::Display for ParseError {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        match self {
169            ParseError::Generic(msg) => write!(f, "CSS parse error: {}", msg),
170            ParseError::NestingTooDeep { depth, limit } => {
171                write!(
172                    f,
173                    "CSS parse error: nesting too deep (depth {}, limit {})",
174                    depth, limit
175                )
176            }
177        }
178    }
179}
180
181impl std::error::Error for ParseError {}