Skip to main content

rust_css_parser/ast/
arena_node.rs

1//! Port of `src/ast/arena-node.ts`: object view of an arena node or token.
2//!
3//! The properties (`typ`, `nam`, `sel`, `val`, `chi`, `tokens`, `unit`, `cal`, `attr`, `kin`, `sign`, `op`, `op1`,
4//! `op2`, `l`, `r`, `loc`, `state`, `errors`, `parent`) are read and written in the arena: nothing is copied. The
5//! javascript `AstArenaNode` class forwards each getter / setter to [`AstArenaNode::get`] / [`AstArenaNode::set`]
6//! and wraps the node ids it receives in views, lazily.
7
8use super::arena::{is_node_object_type, is_numeric_token_type, structured_fields, AstArena};
9use super::types::{ColorType, EnumAstNodeStatus, EnumToken};
10use crate::plain::Plain;
11use crate::types::{ErrorDescription, SourceLocation};
12use std::rc::Rc;
13
14/// keyed symbol names (`Symbol.for()`) of the view properties
15pub const ARENAID: &str = "@tbela99/css-parser/ARENAID";
16pub const ARENA: &str = "@tbela99/css-parser/ARENA";
17
18/// value read from a view
19#[derive(Clone, Debug, PartialEq)]
20pub enum NodeValue {
21    Undefined,
22    Null,
23    Str(Rc<str>),
24    Num(f64),
25    /// a view of a node / token
26    Node(u32),
27    /// views of a list, frozen
28    Nodes(Vec<u32>),
29    Location(SourceLocation),
30    Errors(Vec<ErrorDescription>),
31}
32
33/// value assigned to a view property (`AstArenaNodeInput`, strings, numbers)
34#[derive(Clone, Debug)]
35pub enum NodeInput {
36    Null,
37    Str(Rc<str>),
38    Num(f64),
39    /// node id of the arena (views of the arena are passed as ids)
40    Id(u32),
41    /// a plain object (or a view of another arena exported as a plain object)
42    Plain(Plain),
43    List(Vec<NodeInput>),
44    Location(Option<SourceLocation>),
45    Errors(Option<Vec<ErrorDescription>>),
46}
47
48/// node types whose value (`val`) is the token list: declarations and css module variables
49fn has_value_tokens(typ: u8) -> bool {
50    matches!(
51        typ,
52        EnumToken::DeclarationNodeType
53            | EnumToken::CssVariableTokenType
54            | EnumToken::CssVariableImportTokenType
55            | EnumToken::CssVariableDeclarationMapTokenType
56    )
57}
58
59/// convert setter values to node ids of the arena: ids are used as is, plain objects are allocated
60pub fn to_ids(arena: &AstArena, values: &NodeInput) -> Vec<u32> {
61    match values {
62        NodeInput::Null => Vec::new(),
63        NodeInput::List(list) => list.iter().flat_map(|v| to_ids(arena, v)).collect(),
64        NodeInput::Id(id) => vec![*id],
65        NodeInput::Num(n) => vec![*n as u32],
66        NodeInput::Plain(p) => vec![arena.from_object(p)],
67        _ => Vec::new(),
68    }
69}
70
71/// ids of a linked list
72fn list_views(arena: &AstArena, first: u32) -> NodeValue {
73    let mut result = Vec::new();
74    let mut id = first;
75    while id != 0 {
76        result.push(id);
77        id = arena.next_sibling.get(id);
78    }
79    NodeValue::Nodes(result)
80}
81
82/// object view of an arena node or token
83pub struct AstArenaNode<'a> {
84    pub arena: &'a AstArena,
85    pub id: u32,
86}
87
88impl<'a> AstArenaNode<'a> {
89    pub fn new(arena: &'a AstArena, id: u32) -> Self {
90        Self { arena, id }
91    }
92
93    /// read a property
94    pub fn get(&self, key: &str) -> NodeValue {
95        match key {
96            "typ" => NodeValue::Num(self.arena.data_types.get(self.id) as f64),
97            "nam" => self.nam(),
98            "sel" => self.sel(),
99            "val" => self.val(),
100            "chi" => self.chi(),
101            "tokens" => self.tokens(),
102            "unit" => self.unit(),
103            "cal" => self.unit_of(EnumToken::ColorTokenType),
104            "attr" => self.unit_of(EnumToken::MatchExpressionTokenType),
105            "kin" => self.kin(),
106            "sign" => self.sign(),
107            "op" => self.op(),
108            "op1" | "op2" => self.get_field(key),
109            "l" => self.lr(true),
110            "r" => self.lr(false),
111            "loc" => self.arena.get_location(self.id).map_or(NodeValue::Null, NodeValue::Location),
112            "state" => NodeValue::Num((self.arena.flags.get(self.id) & EnumAstNodeStatus::StateMask) as f64),
113            "errors" => self.arena.errors.borrow().get(&self.id).map_or(NodeValue::Null, |e| NodeValue::Errors(e.clone())),
114            "parent" => {
115                let parent = self.arena.get_value_parent(self.id);
116                if parent == 0 {
117                    NodeValue::Null
118                } else {
119                    NodeValue::Node(parent)
120                }
121            }
122            _ => NodeValue::Undefined,
123        }
124    }
125
126    /// write a property. returns false when the property is not a view property
127    pub fn set(&self, key: &str, value: NodeInput) -> bool {
128        let arena = self.arena;
129        let id = self.id;
130        match key {
131            "typ" => {
132                if let NodeInput::Num(n) = value {
133                    arena.data_types.set(id, n as u8);
134                }
135            }
136            "nam" | "sel" => {
137                if let NodeInput::Str(s) = &value {
138                    arena.name.set(id, arena.intern_rc(s));
139                }
140            }
141            "val" => self.set_val(value),
142            "chi" => self.set_chi(value),
143            "tokens" => arena.set_token_list(id, &to_ids(arena, &value)),
144            "unit" | "cal" | "attr" => match &value {
145                NodeInput::Str(s) => arena.set_unit_string(id, Some(s)),
146                _ => arena.set_unit_string(id, None),
147            },
148            "kin" => arena.color_type.set(id, if let NodeInput::Num(n) = value { n as u8 } else { ColorType::NONE }),
149            "sign" => {
150                if let NodeInput::Num(n) = value {
151                    arena.numeric_value.set(id, n);
152                }
153            }
154            "op" => {
155                if arena.data_types.get(id) == EnumToken::BinaryExpressionTokenType {
156                    if let NodeInput::Num(n) = value {
157                        arena.numeric_value.set(id, n);
158                    }
159                } else {
160                    self.set_field("op", &value);
161                }
162            }
163            "op1" | "op2" => {
164                self.set_field(key, &value);
165            }
166            "l" => self.set_lr(true, value),
167            "r" => self.set_lr(false, value),
168            "loc" => {
169                let loc = match value {
170                    NodeInput::Location(loc) => loc,
171                    _ => None,
172                };
173                arena.set_location(id, loc.map(|l| l.src_id), loc.map(|l| l.sta), loc.map(|l| l.end));
174            }
175            "state" => arena.set_state(id, if let NodeInput::Num(n) = value { n as u32 } else { 0 }),
176            "errors" => arena.set_errors(id, if let NodeInput::Errors(e) = value { e } else { None }),
177            _ => return false,
178        }
179        true
180    }
181
182    fn nam(&self) -> NodeValue {
183        let arena = self.arena;
184        let id = self.id;
185        let typ = arena.data_types.get(id);
186        if is_node_object_type(typ) {
187            return if typ == EnumToken::AtRuleNodeType || typ == EnumToken::KeyframesAtRuleNodeType || has_value_tokens(typ) {
188                NodeValue::Str(arena.resolve_string(arena.name.get(id)).into())
189            } else {
190                NodeValue::Undefined
191            };
192        }
193        if arena.name.get(id) == 0 {
194            NodeValue::Undefined
195        } else {
196            NodeValue::Str(arena.resolve_string(arena.name.get(id)).into())
197        }
198    }
199
200    fn sel(&self) -> NodeValue {
201        let typ = self.arena.data_types.get(self.id);
202        if typ == EnumToken::RuleNodeType || typ == EnumToken::KeyframesRuleNodeType {
203            NodeValue::Str(self.arena.resolve_string(self.arena.name.get(self.id)).into())
204        } else {
205            NodeValue::Undefined
206        }
207    }
208
209    fn val(&self) -> NodeValue {
210        let arena = self.arena;
211        let id = self.id;
212        let typ = arena.data_types.get(id);
213        if is_node_object_type(typ) {
214            if has_value_tokens(typ) {
215                return list_views(arena, arena.first_token.get(id));
216            }
217            return if matches!(typ, EnumToken::StyleSheetNodeType | EnumToken::RuleNodeType | EnumToken::KeyframesRuleNodeType) {
218                NodeValue::Undefined
219            } else {
220                NodeValue::Str(arena.resolve_string(arena.string_value.get(id)).into())
221            };
222        }
223        if typ == EnumToken::BinaryExpressionTokenType || typ == EnumToken::FractionTokenType {
224            return NodeValue::Undefined;
225        }
226        if typ == EnumToken::UnaryExpressionTokenType {
227            let child = arena.first_child.get(id);
228            return if child == 0 { NodeValue::Null } else { NodeValue::Node(child) };
229        }
230        if is_numeric_token_type(typ) {
231            let fraction = arena.get_fraction(id);
232            return if fraction == 0 { NodeValue::Num(arena.numeric_value.get(id)) } else { NodeValue::Node(fraction) };
233        }
234        let field = self.get_field("val");
235        if field != NodeValue::Undefined {
236            return field;
237        }
238        if arena.string_value.get(id) != 0 || typ == EnumToken::IdenTokenType || typ == EnumToken::StringTokenType {
239            NodeValue::Str(arena.resolve_string(arena.string_value.get(id)).into())
240        } else {
241            NodeValue::Undefined
242        }
243    }
244
245    fn set_val(&self, val: NodeInput) {
246        let arena = self.arena;
247        let id = self.id;
248        let typ = arena.data_types.get(id);
249        if is_node_object_type(typ) && has_value_tokens(typ) {
250            arena.set_token_list(id, &to_ids(arena, &val));
251            return;
252        }
253        match &val {
254            NodeInput::Str(s) => {
255                if is_numeric_token_type(typ) {
256                    arena.numeric_value.set(id, crate::utils::number::js_parse_number(s));
257                    arena.set_fraction(id, None);
258                } else {
259                    arena.string_value.set(id, arena.intern_rc(s));
260                }
261                return;
262            }
263            NodeInput::Num(n) => {
264                arena.numeric_value.set(id, *n);
265                if is_numeric_token_type(typ) {
266                    arena.set_fraction(id, None);
267                }
268                return;
269            }
270            _ => {}
271        }
272        if typ == EnumToken::UnaryExpressionTokenType {
273            arena.set_child_list(id, &to_ids(arena, &val));
274        } else if is_numeric_token_type(typ) {
275            let fraction = match val {
276                NodeInput::Null => None,
277                _ => to_ids(arena, &val).first().copied(),
278            };
279            arena.set_fraction(id, fraction);
280        } else if !self.set_field("val", &val) {
281            arena.string_value.set(id, 0);
282        }
283    }
284
285    fn chi(&self) -> NodeValue {
286        let arena = self.arena;
287        let id = self.id;
288        if arena.flags.get(id) & EnumAstNodeStatus::HasChildren != 0 {
289            return list_views(arena, arena.first_child.get(id));
290        }
291        if is_node_object_type(arena.data_types.get(id)) || arena.first_token.get(id) == 0 {
292            return NodeValue::Undefined;
293        }
294        list_views(arena, arena.first_token.get(id))
295    }
296
297    fn set_chi(&self, chi: NodeInput) {
298        let arena = self.arena;
299        let id = self.id;
300        let typ = arena.data_types.get(id);
301        if matches!(
302            typ,
303            EnumToken::StyleSheetNodeType
304                | EnumToken::RuleNodeType
305                | EnumToken::KeyframesRuleNodeType
306                | EnumToken::AtRuleNodeType
307                | EnumToken::KeyframesAtRuleNodeType
308        ) {
309            if matches!(chi, NodeInput::Null) {
310                arena.set_child_list(id, &[]);
311                if typ == EnumToken::AtRuleNodeType || typ == EnumToken::KeyframesAtRuleNodeType {
312                    arena.flags.set(id, arena.flags.get(id) & !EnumAstNodeStatus::HasChildren);
313                }
314                return;
315            }
316            arena.flags.set(id, arena.flags.get(id) | EnumAstNodeStatus::HasChildren);
317            arena.set_child_list(id, &to_ids(arena, &chi));
318            return;
319        }
320        arena.set_token_list(id, &to_ids(arena, &chi));
321    }
322
323    fn tokens(&self) -> NodeValue {
324        let arena = self.arena;
325        let id = self.id;
326        if arena.flags.get(id) & EnumAstNodeStatus::HasValues != 0 || arena.first_token.get(id) == 0 {
327            NodeValue::Null
328        } else {
329            list_views(arena, arena.first_token.get(id))
330        }
331    }
332
333    fn unit(&self) -> NodeValue {
334        let arena = self.arena;
335        let id = self.id;
336        let typ = arena.data_types.get(id);
337        if arena.unit.get(id) == 0 || typ == EnumToken::ColorTokenType || typ == EnumToken::MatchExpressionTokenType {
338            NodeValue::Undefined
339        } else {
340            NodeValue::Str(arena.resolve_string(arena.unit.get(id)).into())
341        }
342    }
343
344    /// `cal` of a color, `attr` of a match expression
345    fn unit_of(&self, typ: u8) -> NodeValue {
346        let arena = self.arena;
347        if arena.unit.get(self.id) == 0 || arena.data_types.get(self.id) != typ {
348            NodeValue::Undefined
349        } else {
350            NodeValue::Str(arena.resolve_string(arena.unit.get(self.id)).into())
351        }
352    }
353
354    fn kin(&self) -> NodeValue {
355        let arena = self.arena;
356        if arena.data_types.get(self.id) != EnumToken::ColorTokenType || arena.color_type.get(self.id) == ColorType::NONE {
357            NodeValue::Undefined
358        } else {
359            NodeValue::Num(arena.color_type.get(self.id) as f64)
360        }
361    }
362
363    fn sign(&self) -> NodeValue {
364        if self.arena.data_types.get(self.id) == EnumToken::UnaryExpressionTokenType {
365            NodeValue::Num(self.arena.numeric_value.get(self.id))
366        } else {
367            NodeValue::Undefined
368        }
369    }
370
371    fn op(&self) -> NodeValue {
372        if self.arena.data_types.get(self.id) == EnumToken::BinaryExpressionTokenType {
373            NodeValue::Num(self.arena.numeric_value.get(self.id))
374        } else {
375            self.get_field("op")
376        }
377    }
378
379    fn lr(&self, left: bool) -> NodeValue {
380        let arena = self.arena;
381        if arena.data_types.get(self.id) == EnumToken::FractionTokenType {
382            let child = if left { arena.first_child.get(self.id) } else { arena.last_child.get(self.id) };
383            return if child == 0 { NodeValue::Null } else { NodeValue::Node(child) };
384        }
385        self.get_field(if left { "l" } else { "r" })
386    }
387
388    fn set_lr(&self, left: bool, value: NodeInput) {
389        let arena = self.arena;
390        let id = self.id;
391        if arena.data_types.get(id) == EnumToken::FractionTokenType {
392            let mut values = to_ids(arena, &value);
393            if left {
394                let r = arena.last_child.get(id);
395                if r != 0 && r != arena.first_child.get(id) {
396                    values.push(r);
397                }
398            } else {
399                let l = arena.first_child.get(id);
400                if l != 0 {
401                    values.insert(0, l);
402                }
403            }
404            arena.set_child_list(id, &values);
405            return;
406        }
407        self.set_field(if left { "l" } else { "r" }, &value);
408    }
409
410    /// value of a structured token field. undefined when the token has no such field
411    fn get_field(&self, key: &str) -> NodeValue {
412        let arena = self.arena;
413        for (name, field, single) in structured_fields(arena.data_types.get(self.id)) {
414            if name != key {
415                continue;
416            }
417            let Some(list) = arena.get_child_at(self.id, field) else {
418                return NodeValue::Undefined;
419            };
420            if single {
421                let first = arena.first_token.get(list);
422                return if first == 0 { NodeValue::Null } else { NodeValue::Node(first) };
423            }
424            return list_views(arena, arena.first_token.get(list));
425        }
426        NodeValue::Undefined
427    }
428
429    /// set the value of a structured token field. false when the token has no such field
430    fn set_field(&self, key: &str, value: &NodeInput) -> bool {
431        let arena = self.arena;
432        for (name, field, _) in structured_fields(arena.data_types.get(self.id)) {
433            if name == key {
434                arena.set_token_list(arena.field_list(self.id, field), &to_ids(arena, value));
435                return true;
436            }
437        }
438        false
439    }
440
441    /// deep plain copy of the node
442    pub fn to_json(&self) -> Plain {
443        self.arena.to_plain_object(self.id)
444    }
445}