Skip to main content

rust_css_parser/ast/
arena.rs

1//! Port of `src/ast/arena.ts`.
2//!
3//! Arena memory manager: ast nodes and value tokens are integer ids, their data is stored column-wise (structure of
4//! arrays) in Rust owned vectors, lists are doubly linked lists stored in the `first_child` / `last_child` /
5//! `first_token` / `last_token` / `next_sibling` / `previous_sibling` columns and strings are interned.
6//!
7//! The columns are interior mutable ([`Column`]): every method takes `&self`, like the typescript implementation
8//! where the arena is a shared mutable object (visitors re-enter the arena while it is transformed).
9
10use super::column::Column;
11use super::strings::SharedStr;
12use super::strings::{StringBuilder, StringDerived, StringFlag, StringTable, StringTableData};
13use super::types::{EnumAstNodeStatus, EnumToken};
14use super::walk::{NodeWalker, ValueWalker, WalkerFilter, WalkerOptions, WalkerValueOptions};
15use crate::parser::utils::codes::CodeUnits;
16use crate::types::ErrorDescription;
17use std::cell::{Cell, RefCell, UnsafeCell};
18use crate::utils::fx::HashMap;
19use std::rc::Rc;
20
21/// position of the structured token fields in the children list
22#[allow(non_snake_case)]
23pub mod TokenField {
24    /// left hand side (`l`)
25    pub const L: u32 = 0;
26    /// right hand side (`r`)
27    pub const R: u32 = 1;
28    /// operator (`op`, `op1`)
29    pub const Op: u32 = 2;
30    /// second operator (`op2`)
31    pub const Op2: u32 = 3;
32    /// value (`val`)
33    pub const Val: u32 = 4;
34}
35
36/// numeric token types: the value is stored in the `numeric_value` column
37pub fn is_numeric_token_type(typ: u8) -> bool {
38    matches!(
39        typ,
40        EnumToken::NumberTokenType
41            | EnumToken::DimensionTokenType
42            | EnumToken::LengthTokenType
43            | EnumToken::AngleTokenType
44            | EnumToken::TimeTokenType
45            | EnumToken::FrequencyTokenType
46            | EnumToken::ResolutionTokenType
47            | EnumToken::PercentageTokenType
48            | EnumToken::FlexTokenType
49            | EnumToken::UserDefinedDimensionTokenType
50    )
51}
52
53/// token types whose fields are stored as list children (see [`TokenField`])
54pub fn is_structured_token_type(typ: u8) -> bool {
55    matches!(
56        typ,
57        EnumToken::BinaryExpressionTokenType
58            | EnumToken::MatchExpressionTokenType
59            | EnumToken::MediaQueryConditionTokenType
60            | EnumToken::MediaQueryUnaryFeatureTokenType
61            | EnumToken::SupportsQueryConditionTokenType
62            | EnumToken::SupportsQueryUnaryConditionTokenType
63            | EnumToken::WhenElseQueryConditionTokenType
64            | EnumToken::WhenElseUnaryConditionTokenType
65            | EnumToken::IfConditionTokenType
66            | EnumToken::IfElseConditionTokenType
67            | EnumToken::ContainerStyleRangeTokenType
68            | EnumToken::MediaRangeQueryTokenType
69            | EnumToken::ComposesSelectorNodeType
70            | EnumToken::NameSpaceAttributeTokenType
71    )
72}
73
74/// plain object key, field and single value flag of a structured token field
75pub type StructuredField = (&'static str, u32, bool);
76
77/// fields of a structured token type: the plain object key (`l`, `r`, `op`, `op1`, `op2`, `val`), the field index and
78/// whether the field holds a single token. empty for the other token types
79pub fn structured_fields(typ: u8) -> Vec<StructuredField> {
80    if !is_structured_token_type(typ) {
81        return Vec::new();
82    }
83    let single = matches!(
84        typ,
85        EnumToken::BinaryExpressionTokenType
86            | EnumToken::IfElseConditionTokenType
87            | EnumToken::MatchExpressionTokenType
88            | EnumToken::NameSpaceAttributeTokenType
89    );
90    let single_left = single
91        || matches!(
92            typ,
93            EnumToken::MediaQueryConditionTokenType
94                | EnumToken::MediaQueryUnaryFeatureTokenType
95                | EnumToken::SupportsQueryUnaryConditionTokenType
96                | EnumToken::WhenElseUnaryConditionTokenType
97        );
98    let single_right = single || typ == EnumToken::ComposesSelectorNodeType;
99    vec![
100        ("l", TokenField::L, single_left),
101        ("r", TokenField::R, single_right),
102        (
103            if typ == EnumToken::MediaRangeQueryTokenType { "op1" } else { "op" },
104            TokenField::Op,
105            typ != EnumToken::ContainerStyleRangeTokenType,
106        ),
107        ("op2", TokenField::Op2, true),
108        ("val", TokenField::Val, false),
109    ]
110}
111
112/// arena columns, in the order of the transferable buffers
113pub const ARENA_COLUMNS: [&str; 15] = [
114    "dataTypes",
115    "parents",
116    "nextSibling",
117    "previousSibling",
118    "firstToken",
119    "lastToken",
120    "firstChild",
121    "lastChild",
122    "name",
123    "stringValue",
124    "numericValue",
125    "unit",
126    "flags",
127    "colorType",
128    "spans",
129];
130
131/// properties of an arena, see [`Arena::export_properties`] (`Arena.toTransferableArenaObject()`)
132#[derive(Clone, Debug, Default)]
133pub struct ArenaProperties {
134    pub kind: String,
135    pub current: u32,
136    pub strings: StringTableData,
137    pub errors: Vec<(u32, Vec<ErrorDescription>)>,
138    pub sources: Option<Vec<u32>>,
139    pub input_lengths: Option<Vec<Option<u32>>>,
140}
141
142/// column buffers of an arena, in the order of [`ARENA_COLUMNS`]
143#[derive(Clone, Debug, Default)]
144pub struct ArenaTransferables {
145    pub data_types: Vec<u8>,
146    pub parents: Vec<u32>,
147    pub next_sibling: Vec<u32>,
148    pub previous_sibling: Vec<u32>,
149    pub first_token: Vec<u32>,
150    pub last_token: Vec<u32>,
151    pub first_child: Vec<u32>,
152    pub last_child: Vec<u32>,
153    pub name: Vec<u32>,
154    pub string_value: Vec<u32>,
155    pub numeric_value: Vec<f64>,
156    pub unit: Vec<u32>,
157    pub flags: Vec<u32>,
158    pub color_type: Vec<u8>,
159    pub spans: Vec<u64>,
160}
161
162/// the nesting rules of these nodes are not expanded
163pub const SKIP_STATES: u32 = EnumAstNodeStatus::Invalid
164    | EnumAstNodeStatus::Disallowed
165    | EnumAstNodeStatus::Unknown
166    | EnumAstNodeStatus::Unparsed
167    | EnumAstNodeStatus::Malformed;
168
169/// Arena memory manager.
170///
171/// The node data is stored column-wise in vectors allocated for the capacity of the arena (62 bytes per node). The
172/// arena grows by doubling its capacity and never frees memory by itself: detached nodes keep their memory and their
173/// ids stay valid. [`Arena::release`], [`Arena::compact`], [`Arena::trim`] and [`Arena::compact_strings`] reclaim the
174/// memory.
175pub struct Arena {
176    /// interned strings
177    string_table: UnsafeCell<StringTable>,
178    /// root node
179    pub root: u32,
180    /// last allocated node id. 0 is never allocated: it means "no node"
181    current: Cell<u32>,
182    pub data_types: Column<u8>,
183    pub parents: Column<u32>,
184    pub next_sibling: Column<u32>,
185    pub previous_sibling: Column<u32>,
186    pub first_token: Column<u32>,
187    pub last_token: Column<u32>,
188    pub first_child: Column<u32>,
189    pub last_child: Column<u32>,
190    /// interned name (`nam`) of rules / declarations / at-rules
191    pub name: Column<u32>,
192    pub string_value: Column<u32>,
193    pub numeric_value: Column<f64>,
194    pub unit: Column<u32>,
195    pub flags: Column<u32>,
196    pub color_type: Column<u8>,
197    /// packed spans: 8 bits for the source, 28 bits for the start, 28 bits for the end
198    pub spans: Column<u64>,
199    /// validation errors by node id
200    pub errors: RefCell<HashMap<u32, Vec<ErrorDescription>>>,
201    /// head of the list of recycled node ids, linked through `next_sibling`
202    free_list: Cell<u32>,
203    /// incremented when the columns are reallocated: the javascript views are recreated
204    generation: Cell<u32>,
205    /// the columns have been transferred
206    transferred: Cell<bool>,
207    /// javascript has views of the columns (see [`Arena::column_raw`]): the buffers replaced by a growth are kept
208    viewed: Cell<bool>,
209}
210
211macro_rules! for_each_column {
212    ($self:ident, $m:ident $(, $arg:expr)*) => {{
213        $self.data_types.$m($($arg),*);
214        $self.parents.$m($($arg),*);
215        $self.next_sibling.$m($($arg),*);
216        $self.previous_sibling.$m($($arg),*);
217        $self.first_token.$m($($arg),*);
218        $self.last_token.$m($($arg),*);
219        $self.first_child.$m($($arg),*);
220        $self.last_child.$m($($arg),*);
221        $self.name.$m($($arg),*);
222        $self.string_value.$m($($arg),*);
223        $self.numeric_value.$m($($arg),*);
224        $self.unit.$m($($arg),*);
225        $self.flags.$m($($arg),*);
226        $self.color_type.$m($($arg),*);
227        $self.spans.$m($($arg),*);
228    }};
229}
230
231impl Default for Arena {
232    fn default() -> Self {
233        Self::new(4096)
234    }
235}
236
237impl Arena {
238    pub fn new(size: usize) -> Self {
239        let arena = Self {
240            string_table: UnsafeCell::new(StringTable::new()),
241            root: 1,
242            current: Cell::new(1),
243            data_types: Column::new(size),
244            parents: Column::new(size),
245            next_sibling: Column::new(size),
246            previous_sibling: Column::new(size),
247            first_token: Column::new(size),
248            last_token: Column::new(size),
249            first_child: Column::new(size),
250            last_child: Column::new(size),
251            name: Column::new(size),
252            string_value: Column::new(size),
253            numeric_value: Column::new(size),
254            unit: Column::new(size),
255            flags: Column::new(size),
256            color_type: Column::new(size),
257            spans: Column::new(size),
258            errors: RefCell::new(HashMap::default()),
259            free_list: Cell::new(0),
260            generation: Cell::new(0),
261            transferred: Cell::new(false),
262            viewed: Cell::new(false),
263        };
264        arena.data_types.set(1, EnumToken::StyleSheetNodeType);
265        arena
266    }
267
268    /// the string table. SAFETY: the table is never borrowed across a call that can re-enter the arena
269    #[inline(always)]
270    #[allow(clippy::mut_from_ref)]
271    pub(crate) fn strings(&self) -> &mut StringTable {
272        unsafe { &mut *self.string_table.get() }
273    }
274
275    /// last allocated node id
276    #[inline]
277    pub fn current(&self) -> u32 {
278        self.current.get()
279    }
280
281    pub fn set_current(&self, current: u32) {
282        self.current.set(current);
283    }
284
285    /// incremented when the columns are reallocated
286    pub fn generation(&self) -> u32 {
287        self.generation.get()
288    }
289
290    /// address of the generation counter: the javascript views read it to detect a growth of the columns
291    pub fn generation_ptr(&self) -> *const u32 {
292        self.generation.as_ptr()
293    }
294
295    /// pointer and length (in elements) of a column, by index of `arenaColumns`. the column views of javascript
296    pub fn column_raw(&self, index: u32) -> (*const u8, usize) {
297        self.viewed.set(true);
298        fn raw<T: Copy + Default>(c: &Column<T>) -> (*const u8, usize) {
299            (c.as_ptr() as *const u8, c.len())
300        }
301        match index {
302            0 => raw(&self.data_types),
303            1 => raw(&self.parents),
304            2 => raw(&self.next_sibling),
305            3 => raw(&self.previous_sibling),
306            4 => raw(&self.first_token),
307            5 => raw(&self.last_token),
308            6 => raw(&self.first_child),
309            7 => raw(&self.last_child),
310            8 => raw(&self.name),
311            9 => raw(&self.string_value),
312            10 => raw(&self.numeric_value),
313            11 => raw(&self.unit),
314            12 => raw(&self.flags),
315            13 => raw(&self.color_type),
316            14 => raw(&self.spans),
317            _ => (std::ptr::null(), 0),
318        }
319    }
320
321    /// true when the column buffers have been transferred: the arena can no longer be used
322    pub fn transferred(&self) -> bool {
323        self.transferred.get()
324    }
325
326    pub fn allocate(&self) -> u32 {
327        let id = self.free_list.get();
328        if id != 0 {
329            // reuse a recycled node: its record is already zeroed, except the free list link
330            self.free_list.set(self.next_sibling.get(id));
331            self.next_sibling.set(id, 0);
332            return id;
333        }
334        let id = self.current.get() + 1;
335        self.current.set(id);
336        if id as usize >= self.data_types.len() {
337            self.resize((self.data_types.len() * 2).max(16));
338        }
339        id
340    }
341
342    /// recycle a detached leaf node that is no longer referenced: its id is reused by the next allocation
343    pub fn recycle(&self, id: u32) {
344        self.data_types.set(id, 0);
345        self.name.set(id, 0);
346        self.string_value.set(id, 0);
347        self.numeric_value.set(id, 0.0);
348        self.unit.set(id, 0);
349        self.flags.set(id, 0);
350        self.color_type.set(id, 0);
351        self.spans.set(id, 0);
352        if !self.errors.borrow().is_empty() {
353            self.errors.borrow_mut().remove(&id);
354        }
355        self.next_sibling.set(id, self.free_list.get());
356        self.free_list.set(id);
357    }
358
359    // ---- strings ---------------------------------------------------------------------
360
361    /// intern a string, returns its id
362    pub fn intern_string(&self, str: &str) -> u32 {
363        self.strings().intern(str)
364    }
365
366    /// intern a shared string without copying it
367    pub fn intern_rc(&self, str: &Rc<str>) -> u32 {
368        self.strings().intern_rc(str)
369    }
370
371    /// intern a shared string: a shared `Rc<str>` is not copied
372    pub fn intern_shared(&self, str: &SharedStr) -> u32 {
373        self.strings().intern_shared(str)
374    }
375
376    /// intern a range of code units of a source (or of the canonical text / the pool, see `StringSource`)
377    pub fn intern_range(&self, codes: &CodeUnits, start: usize, end: usize, source: i32) -> u32 {
378        self.strings().intern_range(codes, start, end, source)
379    }
380
381    /// intern utf-16 code units
382    pub fn intern_units(&self, codes: &[u16]) -> u32 {
383        self.strings().intern_units(codes)
384    }
385
386    /// intern a range of the canonical text
387    pub fn intern_canonical(&self, start: u32, end: u32) -> u32 {
388        self.strings().intern_canonical(start, end)
389    }
390
391    /// set the code units of a source: the strings interned from the source are ranges of it
392    pub fn set_source_text(&self, source: usize, codes: CodeUnits) {
393        self.strings().set_text(source, codes);
394    }
395
396    pub fn release_source_codes(&self, source: usize) {
397        self.strings().release_codes(source);
398    }
399
400    /// code units of a source
401    pub fn source_text(&self, source: usize) -> Option<CodeUnits> {
402        self.strings().text(source).cloned()
403    }
404
405    /// id of an interned string, -1 when the string is not interned
406    pub fn string_id(&self, str: &str) -> i32 {
407        self.strings().lookup(str)
408    }
409
410    pub fn string_length(&self, id: u32) -> usize {
411        self.strings().length(id)
412    }
413
414    pub fn string_code_at(&self, id: u32, index: usize) -> u32 {
415        self.strings().code_at(id, index)
416    }
417
418    pub fn string_index_of(&self, id: u32, code: u32) -> isize {
419        self.strings().index_of_code(id, code)
420    }
421
422    pub fn string_equals(&self, id: u32, str: &str) -> bool {
423        self.strings().equals(id, str)
424    }
425
426    pub fn string_equals_ignore_case(&self, id: u32, str: &str) -> bool {
427        self.strings().equals_ignore_case(id, str)
428    }
429
430    pub fn string_starts_with(&self, id: u32, str: &str) -> bool {
431        self.strings().starts_with(id, str)
432    }
433
434    /// id of the lowercase version of an interned string
435    pub fn lower_string_id(&self, id: u32) -> u32 {
436        self.strings().lower(id)
437    }
438
439    /// append an interned string to a byte buffer when it is ascii. -1 when it is not ascii
440    pub fn copy_string_ascii(&self, id: u32, target: &mut Vec<u8>) -> isize {
441        self.strings().copy_ascii(id, target)
442    }
443
444    /// a boolean property of an interned string, computed once per string id
445    pub fn string_flag(&self, id: u32, flag: StringFlag, compute: impl FnOnce(&str) -> bool) -> bool {
446        if let Some(value) = self.strings().cached_flag(id, flag) {
447            return value;
448        }
449        // the computation may use the arena: the table is not borrowed while it runs
450        let value = self.with_string(id, compute);
451        self.strings().set_flag(id, flag, value);
452        value
453    }
454
455    /// a boolean property of an interned string, computed once per string id from the id
456    pub fn string_flag_id(&self, id: u32, flag: StringFlag, compute: impl FnOnce(u32) -> bool) -> bool {
457        if let Some(value) = self.strings().cached_flag(id, flag) {
458            return value;
459        }
460        let value = compute(id);
461        self.strings().set_flag(id, flag, value);
462        value
463    }
464
465    /// a value derived from an interned string, computed once per string id
466    pub fn string_derived<T: Clone + 'static>(&self, id: u32, slot: StringDerived, compute: impl FnOnce(u32) -> T) -> T {
467        if let Some(value) = self.strings().derived::<T>(id, slot) {
468            return value;
469        }
470        let value = compute(id);
471        self.strings().set_derived(id, slot, value.clone());
472        value
473    }
474
475    /// append the code units of an interned string to a buffer
476    pub fn copy_string(&self, id: u32, target: &mut Vec<u16>) -> usize {
477        self.strings().copy_into(id, target)
478    }
479
480    /// append an interned string to a builder
481    pub fn append_string<'b>(&self, builder: &'b mut StringBuilder, id: u32) -> &'b mut StringBuilder {
482        builder.append_id(self.strings(), id)
483    }
484
485    /// intern the string built by a builder
486    pub fn intern_builder(&self, builder: &StringBuilder) -> u32 {
487        builder.intern(self.strings())
488    }
489
490    /// identity of the string ids: changed when the strings are renumbered
491    pub fn string_epoch(&self) -> u64 {
492        self.strings().epoch
493    }
494
495    /// run a function with an interned string. ascii ranges of a source are borrowed: no string is created
496    pub fn with_string<R>(&self, id: u32, f: impl FnOnce(&str) -> R) -> R {
497        // copy out first when the table may be re-entered: `f` must not mutate the string table. the borrowed
498        // ascii range belongs to an immutable shared buffer
499        let table: &StringTable = self.strings();
500        table.with_str(id, f)
501    }
502
503    /// the string of an id (created and cached the first time it is read)
504    pub fn resolve_string(&self, id: u32) -> SharedStr {
505        self.strings().get(id)
506    }
507
508    // ---- columns ---------------------------------------------------------------------
509
510    #[inline]
511    pub fn get_type(&self, id: u32) -> u8 {
512        self.data_types.get(id)
513    }
514
515    /// type of a node or a token. None when the id is None
516    pub fn type_of(&self, id: Option<u32>) -> Option<u8> {
517        id.map(|id| self.data_types.get(id))
518    }
519
520    #[inline]
521    pub fn set_type(&self, id: u32, typ: u8) {
522        self.data_types.set(id, typ);
523    }
524
525    #[inline]
526    pub fn set_name(&self, id: u32, name_id: u32) {
527        self.name.set(id, name_id);
528    }
529
530    pub fn get_name(&self, id: u32) -> SharedStr {
531        self.resolve_string(self.name.get(id))
532    }
533
534    #[inline]
535    pub fn set_value(&self, id: u32, value_id: u32) {
536        self.string_value.set(id, value_id);
537    }
538
539    pub fn get_value(&self, id: u32) -> SharedStr {
540        self.resolve_string(self.string_value.get(id))
541    }
542
543    #[inline]
544    pub fn set_numeric_value(&self, id: u32, value: f64) {
545        self.numeric_value.set(id, value);
546    }
547
548    #[inline]
549    pub fn set_unit(&self, id: u32, unit: u32) {
550        self.unit.set(id, unit);
551    }
552
553    pub fn get_unit(&self, id: u32) -> SharedStr {
554        self.resolve_string(self.unit.get(id))
555    }
556
557    #[inline]
558    pub fn get_numeric_value(&self, id: u32) -> f64 {
559        self.numeric_value.get(id)
560    }
561
562    #[inline]
563    pub fn set_parent(&self, id: u32, parent: u32) {
564        self.parents.set(id, parent);
565    }
566
567    #[inline]
568    pub fn get_first_child(&self, id: u32) -> u32 {
569        self.first_child.get(id)
570    }
571
572    #[inline]
573    pub fn get_next_sibling(&self, id: u32) -> u32 {
574        self.next_sibling.get(id)
575    }
576
577    #[inline]
578    pub fn get_previous_sibling(&self, id: u32) -> u32 {
579        self.previous_sibling.get(id)
580    }
581
582    #[inline]
583    pub fn get_first_token(&self, id: u32) -> u32 {
584        self.first_token.get(id)
585    }
586
587    #[inline]
588    pub fn get_last_token(&self, id: u32) -> u32 {
589        self.last_token.get(id)
590    }
591
592    /// number of nodes the columns can hold
593    pub fn get_capacity(&self) -> usize {
594        self.data_types.len()
595    }
596
597    pub fn get_last_id(&self) -> u32 {
598        self.current.get()
599    }
600
601    /// approximate number of bytes held by the arena: the columns (62 bytes per node of the capacity) and the string
602    /// table
603    pub fn memory_size(&self) -> usize {
604        self.get_capacity() * 62 + self.strings().memory_size()
605    }
606
607    pub fn get_string_count(&self) -> u32 {
608        self.strings().count
609    }
610
611    /// replace the first child
612    pub fn set_first_child(&self, id: u32, first_child_id: u32) {
613        let first_child = self.first_child.get(id);
614        if first_child == first_child_id {
615            return;
616        }
617        self.detach(first_child_id);
618        if first_child != 0 {
619            self.insert_before(id, first_child, first_child_id);
620            self.detach(first_child);
621        } else {
622            self.append_child_list(id, &[first_child_id]);
623        }
624    }
625
626    #[inline]
627    pub fn get_last_child(&self, id: u32) -> u32 {
628        self.last_child.get(id)
629    }
630
631    /// replace the last child
632    pub fn set_last_child(&self, id: u32, last_child_id: u32) {
633        let last_child = self.last_child.get(id);
634        if last_child == last_child_id {
635            return;
636        }
637        self.detach(last_child_id);
638        if last_child != 0 {
639            self.detach(last_child);
640        }
641        self.append_child_list(id, &[last_child_id]);
642    }
643
644    /// insert a node after another one
645    pub fn set_next_sibling(&self, id: u32, next_sibling_id: u32) {
646        if id == next_sibling_id {
647            return;
648        }
649        self.detach(next_sibling_id);
650        let parent = self.parents.get(id);
651        let next = self.next_sibling.get(id);
652        self.next_sibling.set(next_sibling_id, next);
653        self.previous_sibling.set(next_sibling_id, id);
654        self.next_sibling.set(id, next_sibling_id);
655        self.parents.set(next_sibling_id, parent);
656        if next != 0 {
657            self.previous_sibling.set(next, next_sibling_id);
658        } else if self.last_child.get(parent) == id {
659            self.last_child.set(parent, next_sibling_id);
660        } else if self.last_token.get(parent) == id {
661            self.last_token.set(parent, next_sibling_id);
662        }
663    }
664
665    /// insert a node before another one
666    pub fn set_previous_sibling(&self, id: u32, previous_sibling_id: u32) {
667        if id == previous_sibling_id {
668            return;
669        }
670        self.detach(previous_sibling_id);
671        self.insert_before(self.parents.get(id), id, previous_sibling_id);
672    }
673
674    /// replace the first token
675    pub fn set_first_token(&self, id: u32, first_token_id: u32) {
676        let first_token = self.first_token.get(id);
677        if first_token == first_token_id {
678            return;
679        }
680        self.detach(first_token_id);
681        if first_token != 0 {
682            self.insert_before(id, first_token, first_token_id);
683            self.detach(first_token);
684        } else {
685            self.append_token_list(id, &[first_token_id]);
686        }
687    }
688
689    #[inline]
690    pub fn set_color_type(&self, id: u32, color_type: u8) {
691        self.color_type.set(id, color_type);
692    }
693
694    #[inline]
695    pub fn get_color_type(&self, id: u32) -> u8 {
696        self.color_type.get(id)
697    }
698
699    #[inline]
700    pub fn set_flags(&self, id: u32, flags: u32) {
701        self.flags.set(id, flags);
702    }
703
704    #[inline]
705    pub fn get_flags(&self, id: u32) -> u32 {
706        self.flags.get(id)
707    }
708
709    #[inline]
710    pub fn has_flags(&self, id: u32, flag: u32) -> bool {
711        self.flags.get(id) & flag == flag
712    }
713
714    /// child at an index
715    pub fn get_child_at(&self, id: u32, mut index: u32) -> Option<u32> {
716        let mut child = self.first_child.get(id);
717        while index > 0 && child != 0 {
718            child = self.next_sibling.get(child);
719            index -= 1;
720        }
721        if child == 0 {
722            None
723        } else {
724            Some(child)
725        }
726    }
727
728    /// token at an index of the token list
729    pub fn get_token_at(&self, id: u32, mut index: u32) -> Option<u32> {
730        let mut token = self.first_token.get(id);
731        while index > 0 && token != 0 {
732            token = self.next_sibling.get(token);
733            index -= 1;
734        }
735        if token == 0 {
736            None
737        } else {
738            Some(token)
739        }
740    }
741
742    /// replace the child at an index. the node is appended when the index is out of range
743    pub fn set_child_at(&self, id: u32, index: u32, child: u32) {
744        let current = self.get_child_at(id, index);
745        if current == Some(child) {
746            return;
747        }
748        self.detach(child);
749        match current {
750            None => self.append_child_list(id, &[child]),
751            Some(current) => {
752                self.insert_before(id, current, child);
753                self.detach(current);
754            }
755        }
756    }
757
758    // ---- structured token fields ---------------------------------------------------------
759
760    /// list node holding the tokens of a structured token field. created when missing
761    pub fn field_list(&self, id: u32, field: u32) -> u32 {
762        let mut child = self.first_child.get(id);
763        let mut index = 0;
764        while index < field {
765            if child == 0 {
766                break;
767            }
768            child = self.next_sibling.get(child);
769            index += 1;
770        }
771        if child != 0 {
772            return child;
773        }
774        let mut count = self.child_count(id);
775        while count <= field {
776            child = self.allocate();
777            self.data_types.set(child, EnumToken::ListTokenType);
778            self.append_child_list(id, &[child]);
779            count += 1;
780        }
781        child
782    }
783
784    /// true if the field exists and is not empty
785    pub fn has_field(&self, id: u32, field: u32) -> bool {
786        self.get_child_at(id, field).is_some_and(|list| self.first_token.get(list) != 0)
787    }
788
789    /// first token of a structured token field
790    pub fn field(&self, id: u32, field: u32) -> u32 {
791        self.get_child_at(id, field).map_or(0, |list| self.first_token.get(list))
792    }
793
794    /// tokens of a structured token field
795    pub fn field_tokens(&self, id: u32, field: u32) -> Vec<u32> {
796        self.get_child_at(id, field).map_or_else(Vec::new, |list| self.tokens(list))
797    }
798
799    /// set the tokens of a structured token field
800    pub fn set_field(&self, id: u32, field: u32, tokens: &[u32]) {
801        self.set_token_list(self.field_list(id, field), tokens);
802    }
803
804    /// append tokens to a structured token field
805    pub fn append_field(&self, id: u32, field: u32, tokens: &[u32]) {
806        self.append_token_list(self.field_list(id, field), tokens);
807    }
808
809    pub fn set_left(&self, id: u32, children: &[u32]) {
810        self.set_token_list(self.field_list(id, TokenField::L), children);
811    }
812
813    pub fn get_left(&self, id: u32) -> Option<Vec<u32>> {
814        self.get_child_at(id, TokenField::L).map(|_| self.field_tokens(id, TokenField::L))
815    }
816
817    pub fn set_right(&self, id: u32, right: &[u32]) {
818        self.set_token_list(self.field_list(id, TokenField::R), right);
819    }
820
821    pub fn get_right(&self, id: u32) -> Option<Vec<u32>> {
822        self.get_child_at(id, TokenField::R).map(|_| self.field_tokens(id, TokenField::R))
823    }
824
825    pub fn set_op(&self, id: u32, op: u32) {
826        self.set_token_list(self.field_list(id, TokenField::Op), &[op]);
827    }
828
829    pub fn get_op(&self, id: u32) -> u32 {
830        self.field(id, TokenField::Op)
831    }
832
833    pub fn set_op2(&self, id: u32, op2: u32) {
834        self.set_token_list(self.field_list(id, TokenField::Op2), &[op2]);
835    }
836
837    pub fn get_op2(&self, id: u32) -> u32 {
838        self.field(id, TokenField::Op2)
839    }
840
841    // ---- spans ---------------------------------------------------------------------
842
843    #[inline]
844    pub fn set_span(&self, id: u32, source_id: u32, start: u32, end: u32) {
845        self.spans.set(
846            id,
847            ((source_id as u64 & 0xff) << 56) | ((start as u64 & 0xfffffff) << 28) | (end as u64 & 0xfffffff),
848        );
849    }
850
851    /// copy the packed location of a node
852    #[inline]
853    pub fn copy_span(&self, target: u32, source: u32) {
854        self.spans.set(target, self.spans.get(source));
855    }
856
857    #[inline]
858    pub fn get_source_id(&self, id: u32) -> u32 {
859        ((self.spans.get(id) >> 56) & 0xff) as u32
860    }
861
862    #[inline]
863    pub fn get_span_start(&self, id: u32) -> u32 {
864        ((self.spans.get(id) >> 28) & 0xfffffff) as u32
865    }
866
867    /// (sic: the typescript name is `setSpandStart`)
868    pub fn set_span_start(&self, id: u32, start: u32) {
869        self.set_span(id, self.get_source_id(id), start, self.get_span_end(id));
870    }
871
872    #[inline]
873    pub fn get_span_end(&self, id: u32) -> u32 {
874        (self.spans.get(id) & 0xfffffff) as u32
875    }
876
877    pub fn set_span_end(&self, id: u32, end: u32) {
878        self.set_span(id, self.get_source_id(id), self.get_span_start(id), end);
879    }
880
881    #[inline]
882    pub fn get_parent(&self, id: u32) -> u32 {
883        self.parents.get(id)
884    }
885
886    /// detach a node from its parent
887    pub fn detach(&self, id: u32) {
888        if id == 0 || self.parents.get(id) == 0 {
889            return;
890        }
891        let parent = self.parents.get(id);
892        let next = self.next_sibling.get(id);
893        let previous = self.previous_sibling.get(id);
894        if previous != 0 {
895            self.next_sibling.set(previous, next);
896        } else if self.first_child.get(parent) == id {
897            self.first_child.set(parent, next);
898        } else if self.first_token.get(parent) == id {
899            self.first_token.set(parent, next);
900        }
901        if next != 0 {
902            self.previous_sibling.set(next, previous);
903        } else if self.last_child.get(parent) == id {
904            self.last_child.set(parent, previous);
905        } else if self.last_token.get(parent) == id {
906            self.last_token.set(parent, previous);
907        }
908        self.next_sibling.set(id, 0);
909        self.previous_sibling.set(id, 0);
910        self.parents.set(id, 0);
911    }
912
913    // ---- walkers ---------------------------------------------------------------------
914
915    /// walk the ast nodes: the node and its descendants, in document order
916    pub fn walk<'f>(&self, node: u32, filter: Option<WalkerFilter<'f>>, reverse: bool) -> NodeWalker<'f> {
917        NodeWalker::new(node, filter, reverse)
918    }
919
920    /// walk the ast nodes with options
921    pub fn walk_with<'f>(&self, node: u32, options: WalkerOptions<'f>) -> NodeWalker<'f> {
922        NodeWalker::with_options(node, options)
923    }
924
925    /// walk the value tokens of a node / token and their descendants
926    pub fn walk_values<'f>(&self, node: u32, options: WalkerValueOptions<'f>, reverse: bool) -> ValueWalker<'f> {
927        ValueWalker::of_node(self, node, options, reverse)
928    }
929
930    /// walk tokens and their descendants
931    pub fn walk_token_values<'f>(&self, tokens: &[u32], options: WalkerValueOptions<'f>, reverse: bool) -> ValueWalker<'f> {
932        ValueWalker::of_tokens(tokens, options, reverse)
933    }
934
935    /// node ids of a subtree in document order (collected)
936    pub fn walk_ids(&self, node: u32) -> Vec<u32> {
937        let mut walker = NodeWalker::new(node, None, false);
938        walker.iter(self).collect()
939    }
940
941    /// call the visitor for the tokens and their children, in the order of [`Arena::walk_values`] (the children of a
942    /// token are read after the visitor returns)
943    pub fn visit_values(&self, tokens: &[u32], mut visitor: impl FnMut(&Self, u32)) {
944        // a pooled stack: no allocation per traversal
945        let mut stack = crate::utils::pool::PooledVec::new();
946        stack.extend(tokens.iter().rev().copied());
947        while let Some(value) = stack.pop() {
948            visitor(self, value);
949            let first = stack.len();
950            let mut token = self.first_token.get(value);
951            while token != 0 {
952                stack.push(token);
953                token = self.next_sibling.get(token);
954            }
955            if self.flags.get(value) & EnumAstNodeStatus::HasChildren == 0 {
956                let mut child = self.first_child.get(value);
957                while child != 0 {
958                    if self.data_types.get(child) == EnumToken::ListTokenType {
959                        token = self.first_token.get(child);
960                        while token != 0 {
961                            stack.push(token);
962                            token = self.next_sibling.get(token);
963                        }
964                    } else {
965                        stack.push(child);
966                    }
967                    child = self.next_sibling.get(child);
968                }
969            }
970            stack[first..].reverse();
971        }
972    }
973
974    /// parent of a value token: the node / token that owns the token list, or the structured token that owns the
975    /// field (the field list token is skipped). 0 when the token is detached
976    pub fn get_value_parent(&self, id: u32) -> u32 {
977        let parent = self.parents.get(id);
978        if parent != 0 && self.data_types.get(parent) == EnumToken::ListTokenType {
979            self.parents.get(parent)
980        } else {
981            parent
982        }
983    }
984
985    /// node that owns a value token: the declaration, the rule or the at-rule. 0 when the token is detached
986    pub fn get_value_owner(&self, id: u32) -> u32 {
987        let mut parent = self.parents.get(id);
988        while parent != 0 && self.flags.get(parent) & (EnumAstNodeStatus::HasChildren | EnumAstNodeStatus::HasValues) == 0 {
989            parent = self.parents.get(parent);
990        }
991        parent
992    }
993
994    /// first match of a subtree, in document order
995    pub fn find(&self, node: u32, mut matcher: impl FnMut(&Self, u32) -> bool) -> Option<u32> {
996        let mut walker = NodeWalker::new(node, None, false);
997        while let Some(id) = walker.next(self) {
998            if matcher(self, id) {
999                walker.finish();
1000                return Some(id);
1001            }
1002        }
1003        None
1004    }
1005
1006    /// all the matches of a subtree, in document order
1007    pub fn find_all(&self, node: u32, mut matcher: impl FnMut(&Self, u32) -> bool) -> Vec<u32> {
1008        let mut result = Vec::new();
1009        let mut walker = NodeWalker::new(node, None, false);
1010        while let Some(id) = walker.next(self) {
1011            if matcher(self, id) {
1012                result.push(id);
1013            }
1014        }
1015        result
1016    }
1017
1018    /// last match of a subtree in document order
1019    pub fn find_last(&self, node: u32, mut matcher: impl FnMut(&Self, u32) -> bool) -> Option<u32> {
1020        let mut walker = NodeWalker::new(node, None, true);
1021        while let Some(id) = walker.next(self) {
1022            if matcher(self, id) {
1023                walker.finish();
1024                return Some(id);
1025            }
1026        }
1027        None
1028    }
1029
1030    /// first value token match of a subtree: the node that owns the token and the token
1031    pub fn find_by_value(&self, node: u32, mut matcher: impl FnMut(&Self, u32) -> bool) -> Option<(u32, u32)> {
1032        let mut walker = NodeWalker::new(node, None, false);
1033        while let Some(current) = walker.next(self) {
1034            if self.first_token.get(current) == 0 {
1035                continue;
1036            }
1037            let tokens = self.tokens(current);
1038            let mut values = ValueWalker::of_tokens(&tokens, WalkerValueOptions::default(), false);
1039            while let Some(value) = values.next(self) {
1040                if matcher(self, value) {
1041                    walker.finish();
1042                    return Some((current, value));
1043                }
1044            }
1045        }
1046        None
1047    }
1048
1049    /// first match of a token and its descendants, or of the value tokens of a node
1050    pub fn find_value(&self, node: u32, mut matcher: impl FnMut(&Self, u32) -> bool) -> Option<u32> {
1051        if node == 0 {
1052            return None;
1053        }
1054        if self.flags.get(node) & (EnumAstNodeStatus::HasChildren | EnumAstNodeStatus::HasValues) == 0 && matcher(self, node) {
1055            return Some(node);
1056        }
1057        let mut values = ValueWalker::of_node(self, node, WalkerValueOptions::default(), false);
1058        while let Some(value) = values.next(self) {
1059            if matcher(self, value) {
1060                values.finish();
1061                return Some(value);
1062            }
1063        }
1064        None
1065    }
1066
1067    /// direct value tokens of a node or a token: the token list, then the tokens of the structured fields and the
1068    /// child tokens
1069    pub fn sub_tokens(&self, id: u32) -> Vec<u32> {
1070        let mut result = self.tokens(id);
1071        if self.flags.get(id) & EnumAstNodeStatus::HasChildren != 0 {
1072            return result;
1073        }
1074        let mut child = self.first_child.get(id);
1075        while child != 0 {
1076            if self.data_types.get(child) == EnumToken::ListTokenType {
1077                let mut token = self.first_token.get(child);
1078                while token != 0 {
1079                    result.push(token);
1080                    token = self.next_sibling.get(token);
1081                }
1082            } else {
1083                result.push(child);
1084            }
1085            child = self.next_sibling.get(child);
1086        }
1087        result
1088    }
1089
1090    pub fn find_child(&self, id: u32, mut predicate: impl FnMut(u32) -> bool) -> Option<u32> {
1091        let mut child = self.first_child.get(id);
1092        while child != 0 {
1093            if predicate(child) {
1094                return Some(child);
1095            }
1096            child = self.next_sibling.get(child);
1097        }
1098        None
1099    }
1100
1101    /// find a token in the token list
1102    pub fn find_token(&self, id: u32, mut predicate: impl FnMut(&Self, u32) -> bool) -> Option<u32> {
1103        let mut token = self.first_token.get(id);
1104        while token != 0 {
1105            if predicate(self, token) {
1106                return Some(token);
1107            }
1108            token = self.next_sibling.get(token);
1109        }
1110        None
1111    }
1112
1113    /// the children of the parent of a node, the node included
1114    pub fn siblings(&self, id: u32, mut filter: Option<&mut dyn FnMut(&Self, u32) -> bool>) -> Vec<u32> {
1115        let mut siblings = Vec::new();
1116        let mut child = self.first_child.get(self.parents.get(id));
1117        while child != 0 {
1118            if filter.as_mut().is_none_or(|f| f(self, child)) {
1119                siblings.push(child);
1120            }
1121            child = self.next_sibling.get(child);
1122        }
1123        siblings
1124    }
1125
1126    /// child node ids
1127    pub fn children(&self, id: u32) -> Vec<u32> {
1128        let mut children = Vec::new();
1129        let mut child = self.first_child.get(id);
1130        while child != 0 {
1131            children.push(child);
1132            child = self.next_sibling.get(child);
1133        }
1134        children
1135    }
1136
1137    /// child node ids accepted by a filter
1138    pub fn children_filtered(&self, id: u32, mut filter: impl FnMut(&Self, u32) -> bool) -> Vec<u32> {
1139        let mut children = Vec::new();
1140        let mut child = self.first_child.get(id);
1141        while child != 0 {
1142            if filter(self, child) {
1143                children.push(child);
1144            }
1145            child = self.next_sibling.get(child);
1146        }
1147        children
1148    }
1149
1150    /// token ids of the token list
1151    pub fn tokens(&self, id: u32) -> Vec<u32> {
1152        let mut tokens = Vec::new();
1153        let mut token = self.first_token.get(id);
1154        while token != 0 {
1155            tokens.push(token);
1156            token = self.next_sibling.get(token);
1157        }
1158        tokens
1159    }
1160
1161    /// token ids of the token list accepted by a filter
1162    pub fn tokens_filtered(&self, id: u32, mut filter: impl FnMut(&Self, u32) -> bool) -> Vec<u32> {
1163        let mut tokens = Vec::new();
1164        let mut token = self.first_token.get(id);
1165        while token != 0 {
1166            if filter(self, token) {
1167                tokens.push(token);
1168            }
1169            token = self.next_sibling.get(token);
1170        }
1171        tokens
1172    }
1173
1174    /// iterate the token list without allocation. the next token is read before the current one is returned
1175    pub fn token_iter(&self, id: u32) -> impl Iterator<Item = u32> + '_ {
1176        let mut token = self.first_token.get(id);
1177        std::iter::from_fn(move || {
1178            if token == 0 {
1179                None
1180            } else {
1181                let current = token;
1182                token = self.next_sibling.get(token);
1183                Some(current)
1184            }
1185        })
1186    }
1187
1188    /// iterate the children without allocation. the next child is read before the current one is returned
1189    pub fn child_iter(&self, id: u32) -> impl Iterator<Item = u32> + '_ {
1190        let mut child = self.first_child.get(id);
1191        std::iter::from_fn(move || {
1192            if child == 0 {
1193                None
1194            } else {
1195                let current = child;
1196                child = self.next_sibling.get(child);
1197                Some(current)
1198            }
1199        })
1200    }
1201
1202    /// number of tokens in the token list
1203    pub fn token_count(&self, id: u32) -> u32 {
1204        self.token_iter(id).count() as u32
1205    }
1206
1207    pub fn set_children(&self, id: u32, children: &[u32]) {
1208        self.set_child_list(id, children);
1209    }
1210
1211    /// replace the children
1212    pub fn set_child_list(&self, id: u32, children: &[u32]) {
1213        let mut child = self.first_child.get(id);
1214        while child != 0 {
1215            let next = self.next_sibling.get(child);
1216            self.next_sibling.set(child, 0);
1217            self.previous_sibling.set(child, 0);
1218            self.parents.set(child, 0);
1219            child = next;
1220        }
1221        self.first_child.set(id, 0);
1222        self.last_child.set(id, 0);
1223        self.append_child_list(id, children);
1224    }
1225
1226    pub fn set_tokens(&self, id: u32, tokens: &[u32]) {
1227        self.set_token_list(id, tokens);
1228    }
1229
1230    /// replace the token list
1231    pub fn set_token_list(&self, id: u32, tokens: &[u32]) {
1232        let mut token = self.first_token.get(id);
1233        while token != 0 {
1234            let next = self.next_sibling.get(token);
1235            self.next_sibling.set(token, 0);
1236            self.previous_sibling.set(token, 0);
1237            self.parents.set(token, 0);
1238            token = next;
1239        }
1240        self.first_token.set(id, 0);
1241        self.last_token.set(id, 0);
1242        self.append_token_list(id, tokens);
1243    }
1244
1245    /// move the children of a node into another node, in order
1246    pub fn move_children(&self, from: u32, to: u32, before: u32) {
1247        if from == to {
1248            return;
1249        }
1250        let mut child = self.first_child.get(from);
1251        while child != 0 {
1252            let next = self.next_sibling.get(child);
1253            self.detach(child);
1254            if before == 0 {
1255                self.append_child(to, child);
1256            } else {
1257                self.insert_before(to, before, child);
1258            }
1259            child = next;
1260        }
1261    }
1262
1263    pub fn append_children(&self, id: u32, children: &[u32]) {
1264        self.append_child_list(id, children);
1265    }
1266
1267    /// append children
1268    pub fn append_child_list(&self, id: u32, children: &[u32]) {
1269        for &child in children {
1270            if child == id || child == 0 {
1271                continue;
1272            }
1273            // the child may already be the last child: detach before reading the last child
1274            self.detach(child);
1275            let last_child = self.last_child.get(id);
1276            if last_child == 0 {
1277                self.first_child.set(id, child);
1278            } else {
1279                self.next_sibling.set(last_child, child);
1280            }
1281            self.previous_sibling.set(child, last_child);
1282            self.next_sibling.set(child, 0);
1283            self.parents.set(child, id);
1284            self.last_child.set(id, child);
1285        }
1286    }
1287
1288    pub fn append_tokens(&self, id: u32, tokens: &[u32]) {
1289        self.append_token_list(id, tokens);
1290    }
1291
1292    /// append tokens
1293    pub fn append_token_list(&self, id: u32, tokens: &[u32]) {
1294        for &token in tokens {
1295            if token == id || token == 0 {
1296                continue;
1297            }
1298            self.detach(token);
1299            let last_token = self.last_token.get(id);
1300            if last_token == 0 {
1301                self.first_token.set(id, token);
1302            } else {
1303                self.next_sibling.set(last_token, token);
1304            }
1305            self.previous_sibling.set(token, last_token);
1306            self.next_sibling.set(token, 0);
1307            self.parents.set(token, id);
1308            self.last_token.set(id, token);
1309        }
1310    }
1311
1312    /// append a single child node
1313    pub fn append_child(&self, id: u32, child: u32) {
1314        if child == id || child == 0 {
1315            return;
1316        }
1317        if self.parents.get(child) != 0 {
1318            self.detach(child);
1319        }
1320        let last_child = self.last_child.get(id);
1321        if last_child == 0 {
1322            self.first_child.set(id, child);
1323        } else {
1324            self.next_sibling.set(last_child, child);
1325        }
1326        self.previous_sibling.set(child, last_child);
1327        self.next_sibling.set(child, 0);
1328        self.parents.set(child, id);
1329        self.last_child.set(id, child);
1330    }
1331
1332    /// append a single token
1333    pub fn append_token(&self, id: u32, token: u32) {
1334        if token == id || token == 0 {
1335            return;
1336        }
1337        if self.parents.get(token) != 0 {
1338            self.detach(token);
1339        }
1340        let last_token = self.last_token.get(id);
1341        if last_token == 0 {
1342            self.first_token.set(id, token);
1343        } else {
1344            self.next_sibling.set(last_token, token);
1345        }
1346        self.previous_sibling.set(token, last_token);
1347        self.next_sibling.set(token, 0);
1348        self.parents.set(token, id);
1349        self.last_token.set(id, token);
1350    }
1351
1352    /// prepend tokens to the token list
1353    pub fn prepend_tokens(&self, id: u32, tokens: &[u32]) {
1354        let first = self.first_token.get(id);
1355        if first == 0 {
1356            self.append_token_list(id, tokens);
1357            return;
1358        }
1359        for &token in tokens {
1360            if token == id || token == 0 {
1361                continue;
1362            }
1363            self.set_previous_sibling(first, token);
1364        }
1365    }
1366
1367    /// `key` is "nam" or "val"
1368    pub fn equals_ignore_case(&self, node: u32, key: &str, string: &str) -> bool {
1369        let id = if key == "nam" { self.name.get(node) } else { self.string_value.get(node) };
1370        self.strings().equals_ignore_case(id, string)
1371    }
1372
1373    /// `key` is "nam" or "val"
1374    pub fn starts_with(&self, node: u32, key: &str, string: &str) -> bool {
1375        let id = if key == "nam" { self.name.get(node) } else { self.string_value.get(node) };
1376        self.strings().starts_with(id, string)
1377    }
1378
1379    /// grow the columns
1380    pub fn resize(&self, new_size: usize) {
1381        if new_size <= self.data_types.len() {
1382            return;
1383        }
1384        for_each_column!(self, resize, new_size, self.viewed.get());
1385        self.generation.set(self.generation.get() + 1);
1386    }
1387
1388    /// drop the interned strings that are no longer referenced by any node
1389    pub fn compact_strings(&self) {
1390        let table = self.strings();
1391        let mut used = vec![0u8; table.count as usize];
1392        let size = self.current.get() + 1;
1393        if used.is_empty() {
1394            return;
1395        }
1396        used[0] = 1;
1397        for id in 1..size {
1398            for v in [self.name.get(id), self.string_value.get(id), self.unit.get(id)] {
1399                if let Some(u) = used.get_mut(v as usize) {
1400                    *u = 1;
1401                }
1402            }
1403        }
1404        let count: u32 = used.iter().map(|&u| u as u32).sum();
1405        if count == table.count {
1406            return;
1407        }
1408        let mapping = table.compact(&used);
1409        let map = |v: u32| mapping.get(v as usize).copied().unwrap_or(0);
1410        for id in 1..size {
1411            self.name.set(id, map(self.name.get(id)));
1412            self.string_value.set(id, map(self.string_value.get(id)));
1413            self.unit.set(id, map(self.unit.get(id)));
1414        }
1415    }
1416
1417    /// drop the nodes that are not reachable from the root and renumber the remaining nodes in document order. the
1418    /// unused strings are dropped too. returns the mapping of the old ids to the new ids (0 when dropped)
1419    pub fn compact(&self, errors: Option<&mut [ErrorDescription]>) -> Vec<u32> {
1420        let size = self.current.get() as usize + 1;
1421        let mut mapping = vec![0u32; size];
1422        let mut order = vec![0u32; size];
1423        let mut stack = vec![self.root];
1424        let mut next = 1usize;
1425        while let Some(id) = stack.pop() {
1426            order[next] = id;
1427            mapping[id as usize] = next as u32;
1428            next += 1;
1429            let mut child = self.last_child.get(id);
1430            while child != 0 {
1431                stack.push(child);
1432                child = self.previous_sibling.get(child);
1433            }
1434            let mut token = self.last_token.get(id);
1435            while token != 0 {
1436                stack.push(token);
1437                token = self.previous_sibling.get(token);
1438            }
1439        }
1440        let capacity = next + 64.max(next >> 5);
1441        let m = |v: u32| mapping[v as usize];
1442        let mut t = ArenaTransferables {
1443            data_types: vec![0; capacity],
1444            parents: vec![0; capacity],
1445            next_sibling: vec![0; capacity],
1446            previous_sibling: vec![0; capacity],
1447            first_token: vec![0; capacity],
1448            last_token: vec![0; capacity],
1449            first_child: vec![0; capacity],
1450            last_child: vec![0; capacity],
1451            name: vec![0; capacity],
1452            string_value: vec![0; capacity],
1453            numeric_value: vec![0.0; capacity],
1454            unit: vec![0; capacity],
1455            flags: vec![0; capacity],
1456            color_type: vec![0; capacity],
1457            spans: vec![0; capacity],
1458        };
1459        let table = self.strings();
1460        let mut used = vec![0u8; table.count as usize];
1461        if !used.is_empty() {
1462            used[0] = 1;
1463        }
1464        for target in 1..next {
1465            let id = order[target];
1466            t.data_types[target] = self.data_types.get(id);
1467            t.parents[target] = m(self.parents.get(id));
1468            t.next_sibling[target] = m(self.next_sibling.get(id));
1469            t.previous_sibling[target] = m(self.previous_sibling.get(id));
1470            t.first_token[target] = m(self.first_token.get(id));
1471            t.last_token[target] = m(self.last_token.get(id));
1472            t.first_child[target] = m(self.first_child.get(id));
1473            t.last_child[target] = m(self.last_child.get(id));
1474            t.name[target] = self.name.get(id);
1475            t.string_value[target] = self.string_value.get(id);
1476            t.numeric_value[target] = self.numeric_value.get(id);
1477            t.unit[target] = self.unit.get(id);
1478            t.flags[target] = self.flags.get(id);
1479            t.color_type[target] = self.color_type.get(id);
1480            t.spans[target] = self.spans.get(id);
1481            for v in [t.name[target], t.string_value[target], t.unit[target]] {
1482                if let Some(u) = used.get_mut(v as usize) {
1483                    *u = 1;
1484                }
1485            }
1486        }
1487        let count: u32 = used.iter().map(|&u| u as u32).sum();
1488        if count < table.count {
1489            let string_mapping = table.compact(&used);
1490            let sm = |v: u32| string_mapping.get(v as usize).copied().unwrap_or(0);
1491            for id in 1..next {
1492                t.name[id] = sm(t.name[id]);
1493                t.string_value[id] = sm(t.string_value[id]);
1494                t.unit[id] = sm(t.unit[id]);
1495            }
1496        }
1497        let node_errors: HashMap<u32, Vec<ErrorDescription>> = self
1498            .errors
1499            .borrow_mut()
1500            .drain()
1501            .filter_map(|(id, list)| {
1502                let target = mapping.get(id as usize).copied().unwrap_or(0);
1503                (target != 0).then_some((target, list))
1504            })
1505            .collect();
1506        if let Some(errors) = errors {
1507            for error in errors.iter_mut() {
1508                if let Some(node) = error.node {
1509                    let target = mapping.get(node as usize).copied().unwrap_or(0);
1510                    error.node = if target == 0 { None } else { Some(target) };
1511                }
1512            }
1513        }
1514        self.import_columns(t);
1515        *self.errors.borrow_mut() = node_errors;
1516        self.current.set(next as u32 - 1);
1517        self.free_list.set(0);
1518        mapping
1519    }
1520
1521    /// replace the columns
1522    pub fn import_columns(&self, t: ArenaTransferables) {
1523        self.data_types.replace(t.data_types);
1524        self.parents.replace(t.parents);
1525        self.next_sibling.replace(t.next_sibling);
1526        self.previous_sibling.replace(t.previous_sibling);
1527        self.first_token.replace(t.first_token);
1528        self.last_token.replace(t.last_token);
1529        self.first_child.replace(t.first_child);
1530        self.last_child.replace(t.last_child);
1531        self.name.replace(t.name);
1532        self.string_value.replace(t.string_value);
1533        self.numeric_value.replace(t.numeric_value);
1534        self.unit.replace(t.unit);
1535        self.flags.replace(t.flags);
1536        self.color_type.replace(t.color_type);
1537        self.spans.replace(t.spans);
1538        self.generation.set(self.generation.get() + 1);
1539    }
1540
1541    /// mark nodes to be released or trimmed later
1542    pub fn mark(&self, ids: &[u32]) {
1543        for &id in ids {
1544            if id != 0 && id != self.root {
1545                self.flags.set(id, self.flags.get(id) | EnumAstNodeStatus::Marked);
1546            }
1547        }
1548    }
1549
1550    pub fn is_marked(&self, id: u32) -> bool {
1551        self.flags.get(id) & EnumAstNodeStatus::Marked != 0
1552    }
1553
1554    /// release nodes: detach them and drop their data. `None` releases the marked nodes
1555    pub fn release(&self, id: Option<u32>, deep: bool) {
1556        let Some(id) = id else {
1557            let mut node = 1;
1558            while node <= self.current.get() {
1559                if self.flags.get(node) & EnumAstNodeStatus::Marked != 0 {
1560                    self.flags.set(node, self.flags.get(node) & !EnumAstNodeStatus::Marked);
1561                    self.release(Some(node), true);
1562                }
1563                node += 1;
1564            }
1565            return;
1566        };
1567        if id == 0 || id == self.root {
1568            return;
1569        }
1570        if deep {
1571            let mut child = self.first_child.get(id);
1572            while child != 0 {
1573                let next = self.next_sibling.get(child);
1574                self.release(Some(child), true);
1575                child = next;
1576            }
1577            let mut token = self.first_token.get(id);
1578            while token != 0 {
1579                let next = self.next_sibling.get(token);
1580                self.release(Some(token), true);
1581                token = next;
1582            }
1583        }
1584        self.detach(id);
1585        self.name.set(id, 0);
1586        self.string_value.set(id, 0);
1587        self.unit.set(id, 0);
1588        self.errors.borrow_mut().remove(&id);
1589    }
1590
1591    /// reclaim the memory: release the marked nodes, then compact
1592    pub fn trim(&self, errors: Option<&mut [ErrorDescription]>) -> Vec<u32> {
1593        self.release(None, false);
1594        self.compact(errors)
1595    }
1596
1597    pub fn set_errors(&self, id: u32, errors: Option<Vec<ErrorDescription>>) {
1598        match errors {
1599            Some(errors) if !errors.is_empty() => {
1600                self.errors.borrow_mut().insert(id, errors);
1601            }
1602            _ => {
1603                self.errors.borrow_mut().remove(&id);
1604            }
1605        }
1606    }
1607
1608    pub fn get_errors(&self, id: u32) -> Option<Vec<ErrorDescription>> {
1609        self.errors.borrow().get(&id).cloned()
1610    }
1611
1612    /// number of children
1613    pub fn child_count(&self, id: u32) -> u32 {
1614        self.child_iter(id).count() as u32
1615    }
1616
1617    /// properties of the arena
1618    pub fn export_properties(&self) -> ArenaProperties {
1619        ArenaProperties {
1620            kind: "Arena".into(),
1621            current: self.current.get(),
1622            strings: self.strings().export(),
1623            errors: self.errors.borrow().iter().map(|(k, v)| (*k, v.clone())).collect(),
1624            sources: None,
1625            input_lengths: None,
1626        }
1627    }
1628
1629    /// copy of the columns
1630    pub fn export_transferables(&self) -> ArenaTransferables {
1631        ArenaTransferables {
1632            data_types: self.data_types.to_vec(),
1633            parents: self.parents.to_vec(),
1634            next_sibling: self.next_sibling.to_vec(),
1635            previous_sibling: self.previous_sibling.to_vec(),
1636            first_token: self.first_token.to_vec(),
1637            last_token: self.last_token.to_vec(),
1638            first_child: self.first_child.to_vec(),
1639            last_child: self.last_child.to_vec(),
1640            name: self.name.to_vec(),
1641            string_value: self.string_value.to_vec(),
1642            numeric_value: self.numeric_value.to_vec(),
1643            unit: self.unit.to_vec(),
1644            flags: self.flags.to_vec(),
1645            color_type: self.color_type.to_vec(),
1646            spans: self.spans.to_vec(),
1647        }
1648    }
1649
1650    /// move the columns out (transfer): the arena can no longer be used
1651    pub fn take_transferables(&self) -> ArenaTransferables {
1652        let t = ArenaTransferables {
1653            data_types: self.data_types.replace(Vec::new()),
1654            parents: self.parents.replace(Vec::new()),
1655            next_sibling: self.next_sibling.replace(Vec::new()),
1656            previous_sibling: self.previous_sibling.replace(Vec::new()),
1657            first_token: self.first_token.replace(Vec::new()),
1658            last_token: self.last_token.replace(Vec::new()),
1659            first_child: self.first_child.replace(Vec::new()),
1660            last_child: self.last_child.replace(Vec::new()),
1661            name: self.name.replace(Vec::new()),
1662            string_value: self.string_value.replace(Vec::new()),
1663            numeric_value: self.numeric_value.replace(Vec::new()),
1664            unit: self.unit.replace(Vec::new()),
1665            flags: self.flags.replace(Vec::new()),
1666            color_type: self.color_type.replace(Vec::new()),
1667            spans: self.spans.replace(Vec::new()),
1668        };
1669        self.transferred.set(true);
1670        self.generation.set(self.generation.get() + 1);
1671        t
1672    }
1673
1674    /// initialize the arena from exported properties and column buffers
1675    pub fn import_properties(&self, properties: &ArenaProperties, transferables: ArenaTransferables) {
1676        self.import_columns(transferables);
1677        self.current.set(properties.current);
1678        self.strings().import(&properties.strings);
1679        *self.errors.borrow_mut() = properties.errors.iter().cloned().collect();
1680        self.transferred.set(false);
1681    }
1682
1683    /// link a node before a reference node of the given parent
1684    fn insert_before(&self, parent: u32, reference: u32, node: u32) {
1685        let previous = self.previous_sibling.get(reference);
1686        self.previous_sibling.set(node, previous);
1687        self.next_sibling.set(node, reference);
1688        self.previous_sibling.set(reference, node);
1689        self.parents.set(node, parent);
1690        if previous != 0 {
1691            self.next_sibling.set(previous, node);
1692        } else if self.first_child.get(parent) == reference {
1693            self.first_child.set(parent, node);
1694        } else if self.first_token.get(parent) == reference {
1695            self.first_token.set(parent, node);
1696        }
1697    }
1698}
1699
1700// ---------------------------------------------------------------------------------------------------------------------
1701// AstArena
1702// ---------------------------------------------------------------------------------------------------------------------
1703
1704use crate::plain::{Plain, PlainObject};
1705use crate::types::SourceLocation;
1706
1707/// raw selector (`RawSelectorTokens`)
1708pub type RawSelectorTokens = Vec<Vec<String>>;
1709
1710/// a split selector of the minification cache (`arena.raw`) with its vendor prefixes, computed once. a mutable access
1711/// clears the prefixes
1712#[derive(Clone, Debug, Default)]
1713pub struct RawSelector {
1714    tokens: RawSelectorTokens,
1715    prefixes: std::cell::OnceCell<Rc<[String]>>,
1716}
1717
1718impl RawSelector {
1719    /// the vendor prefixes of the selector, computed once by `compute`
1720    pub fn prefixes(&self, compute: impl FnOnce(&RawSelectorTokens) -> Vec<String>) -> Rc<[String]> {
1721        self.prefixes.get_or_init(|| compute(&self.tokens).into()).clone()
1722    }
1723}
1724
1725impl From<RawSelectorTokens> for RawSelector {
1726    fn from(tokens: RawSelectorTokens) -> Self {
1727        Self { tokens, prefixes: std::cell::OnceCell::new() }
1728    }
1729}
1730
1731impl std::ops::Deref for RawSelector {
1732    type Target = RawSelectorTokens;
1733
1734    fn deref(&self) -> &RawSelectorTokens {
1735        &self.tokens
1736    }
1737}
1738
1739impl std::ops::DerefMut for RawSelector {
1740    fn deref_mut(&mut self) -> &mut RawSelectorTokens {
1741        // the tokens may change: the prefixes are computed again
1742        self.prefixes = std::cell::OnceCell::new();
1743        &mut self.tokens
1744    }
1745}
1746
1747/// optimized selector shared by reference, like the typescript objects (the minifier mutates it in place and a cloned
1748/// rule shares the object of its source)
1749pub type SharedOptimizedSelector = Rc<RefCell<OptimizedSelector>>;
1750
1751/// optimized selector (`OptimizedSelector`)
1752#[derive(Clone, Debug, PartialEq)]
1753pub struct OptimizedSelector {
1754    pub match_: bool,
1755    pub optimized: Vec<String>,
1756    pub selector: Vec<Vec<String>>,
1757    pub reducible: bool,
1758}
1759
1760/// true for the node types whose plain object is a node (`isNodeObjectType()` of `arena-node.ts`)
1761pub fn is_node_object_type(typ: u8) -> bool {
1762    matches!(
1763        typ,
1764        EnumToken::StyleSheetNodeType
1765            | EnumToken::RuleNodeType
1766            | EnumToken::KeyframesRuleNodeType
1767            | EnumToken::AtRuleNodeType
1768            | EnumToken::KeyframesAtRuleNodeType
1769            | EnumToken::CommentNodeType
1770            | EnumToken::CDOCOMMNodeType
1771            | EnumToken::DeclarationNodeType
1772            | EnumToken::CssVariableTokenType
1773            | EnumToken::CssVariableImportTokenType
1774            | EnumToken::CssVariableDeclarationMapTokenType
1775    )
1776}
1777
1778/// a string or an interned string id (`sel: string | number` arguments)
1779#[derive(Clone, Copy, Debug)]
1780pub enum StrOrId<'a> {
1781    Str(&'a str),
1782    Id(u32),
1783}
1784
1785impl<'a> From<&'a str> for StrOrId<'a> {
1786    fn from(s: &'a str) -> Self {
1787        StrOrId::Str(s)
1788    }
1789}
1790
1791impl<'a> From<&'a String> for StrOrId<'a> {
1792    fn from(s: &'a String) -> Self {
1793        StrOrId::Str(s)
1794    }
1795}
1796
1797impl From<u32> for StrOrId<'_> {
1798    fn from(id: u32) -> Self {
1799        StrOrId::Id(id)
1800    }
1801}
1802
1803/// a token value: a string or a number (`val?: string | number | null`)
1804#[derive(Clone, Copy, Debug)]
1805pub enum TokenValue<'a> {
1806    None,
1807    Str(&'a str),
1808    Num(f64),
1809}
1810
1811/// Css ast arena: ast nodes and value tokens. Derefs to [`Arena`] (typescript `extends`).
1812pub struct AstArena {
1813    base: Arena,
1814    /// raw selector (minification cache), by rule id
1815    /// split selectors by rule, shared: a read does not copy the selector
1816    pub raw: RefCell<HashMap<u32, Rc<RawSelector>>>,
1817    /// optimized selector (minification cache), by rule id
1818    pub optimized: RefCell<HashMap<u32, SharedOptimizedSelector>>,
1819    /// first part of the first selector of a selector string (minification cache), by string id: the string epoch the
1820    /// ids belong to, then the code units (`None` when the first selector is empty)
1821    pub first_parts: RefCell<(u64, HashMap<u32, Option<Rc<[u16]>>>)>,
1822    /// vendor prefixes of a selector string (minification cache), by string id, see `first_parts`
1823    pub selector_prefixes: RefCell<(u64, HashMap<u32, Rc<[String]>>)>,
1824    /// source ids. `spans` store the index in this table (8 bits)
1825    pub sources: RefCell<Vec<u32>>,
1826    /// length of the css parsed into a stylesheet, by stylesheet id
1827    pub input_lengths: RefCell<HashMap<u32, u32>>,
1828    /// the shared handle of the arena when it is created by [`AstArena::shared`]: the functions that receive a
1829    /// reference can parse into the arena (`parseDeclarations(css, arena)`)
1830    this: RefCell<std::rc::Weak<AstArena>>,
1831}
1832
1833impl std::ops::Deref for AstArena {
1834    type Target = Arena;
1835
1836    fn deref(&self) -> &Arena {
1837        &self.base
1838    }
1839}
1840
1841impl Default for AstArena {
1842    fn default() -> Self {
1843        Self::new(4096)
1844    }
1845}
1846
1847impl AstArena {
1848    /// a shared arena: [`AstArena::rc`] returns its handle
1849    pub fn shared(size: usize) -> Rc<Self> {
1850        let arena = Rc::new(Self::new(size));
1851        *arena.this.borrow_mut() = Rc::downgrade(&arena);
1852        arena
1853    }
1854
1855    /// register the shared handle of an arena (an arena created by `Rc::new`)
1856    pub fn register(arena: &Rc<Self>) {
1857        *arena.this.borrow_mut() = Rc::downgrade(arena);
1858    }
1859
1860    /// the shared handle of the arena
1861    pub fn rc(&self) -> Rc<AstArena> {
1862        self.this.borrow().upgrade().expect("the arena is not shared: create it with AstArena::shared()")
1863    }
1864
1865    pub fn new(size: usize) -> Self {
1866        let arena = Self {
1867            base: Arena::new(size),
1868            raw: RefCell::new(HashMap::default()),
1869            optimized: RefCell::new(HashMap::default()),
1870            first_parts: RefCell::new((0, HashMap::default())),
1871            selector_prefixes: RefCell::new((0, HashMap::default())),
1872            sources: RefCell::new(Vec::new()),
1873            input_lengths: RefCell::new(HashMap::default()),
1874            this: RefCell::new(std::rc::Weak::new()),
1875        };
1876        // string id 0 is the null / empty string
1877        arena.intern_string("");
1878        arena.flags.set(arena.root, EnumAstNodeStatus::HasChildren);
1879        arena
1880    }
1881
1882    /// the base arena
1883    pub fn base(&self) -> &Arena {
1884        &self.base
1885    }
1886
1887    pub fn release(&self, id: Option<u32>, deep: bool) {
1888        self.base.release(id, deep);
1889        if let Some(id) = id {
1890            self.raw.borrow_mut().remove(&id);
1891            self.optimized.borrow_mut().remove(&id);
1892            self.input_lengths.borrow_mut().remove(&id);
1893        }
1894    }
1895
1896    pub fn compact(&self, errors: Option<&mut [ErrorDescription]>) -> Vec<u32> {
1897        let mapping = self.base.compact(errors);
1898        self.raw.borrow_mut().clear();
1899        self.optimized.borrow_mut().clear();
1900        let lengths: HashMap<u32, u32> = self
1901            .input_lengths
1902            .borrow()
1903            .iter()
1904            .filter_map(|(&id, &len)| mapping.get(id as usize).filter(|&&m| m != 0).map(|&m| (m, len)))
1905            .collect();
1906        *self.input_lengths.borrow_mut() = lengths;
1907        mapping
1908    }
1909
1910    pub fn trim(&self, errors: Option<&mut [ErrorDescription]>) -> Vec<u32> {
1911        self.release(None, false);
1912        self.compact(errors)
1913    }
1914
1915    /// validation state bits
1916    pub fn get_state(&self, id: u32) -> u32 {
1917        self.flags.get(id) & EnumAstNodeStatus::StateMask
1918    }
1919
1920    /// set the validation state bits
1921    pub fn set_state(&self, id: u32, state: u32) {
1922        self.flags.set(id, (self.flags.get(id) & !EnumAstNodeStatus::StateMask) | (state & EnumAstNodeStatus::StateMask));
1923    }
1924
1925    pub fn is_invalid(&self, id: u32) -> bool {
1926        self.flags.get(id) & EnumAstNodeStatus::Invalid != 0
1927    }
1928
1929    /// index of a source id in the sources table
1930    pub fn source_index(&self, src_id: u32) -> u32 {
1931        let mut sources = self.sources.borrow_mut();
1932        match sources.iter().position(|&s| s == src_id) {
1933            Some(index) => index as u32,
1934            None => {
1935                sources.push(src_id);
1936                sources.len() as u32 - 1
1937            }
1938        }
1939    }
1940
1941    /// set the source location. `None` for both the source and the start drops the location
1942    pub fn set_location(&self, id: u32, src_id: Option<u32>, sta: Option<u32>, end: Option<u32>) {
1943        if src_id.is_none() && sta.is_none() {
1944            self.flags.set(id, self.flags.get(id) & !EnumAstNodeStatus::HasLocation);
1945            self.spans.set(id, 0);
1946            return;
1947        }
1948        self.flags.set(id, self.flags.get(id) | EnumAstNodeStatus::HasLocation);
1949        self.set_span(id, self.source_index(src_id.unwrap_or(0)), sta.unwrap_or(0), end.unwrap_or(0));
1950    }
1951
1952    /// set the location of a token from the tokenizer values
1953    #[inline]
1954    pub fn set_token_location(&self, id: u32, source_index: u32, sta: u32, end: u32) {
1955        self.flags.set(id, self.flags.get(id) | EnumAstNodeStatus::HasLocation);
1956        self.set_span(id, source_index, sta, end);
1957    }
1958
1959    /// copy the source location of another node
1960    pub fn copy_location(&self, id: u32, source: u32) {
1961        self.copy_span(id, source);
1962        self.flags.set(
1963            id,
1964            (self.flags.get(id) & !EnumAstNodeStatus::HasLocation) | (self.flags.get(source) & EnumAstNodeStatus::HasLocation),
1965        );
1966    }
1967
1968    /// set the location from the start of a node to the end of another one
1969    pub fn span_location(&self, id: u32, start: u32, end: u32) {
1970        if self.flags.get(start) & EnumAstNodeStatus::HasLocation == 0 {
1971            self.copy_location(id, end);
1972            return;
1973        }
1974        self.flags.set(id, self.flags.get(id) | EnumAstNodeStatus::HasLocation);
1975        self.set_span(
1976            id,
1977            self.get_source_id(start),
1978            self.get_span_start(start),
1979            if self.flags.get(end) & EnumAstNodeStatus::HasLocation != 0 { self.get_span_end(end) } else { self.get_span_end(start) },
1980        );
1981    }
1982
1983    pub fn has_location(&self, id: u32) -> bool {
1984        self.flags.get(id) & EnumAstNodeStatus::HasLocation != 0
1985    }
1986
1987    /// source location
1988    pub fn get_location(&self, id: u32) -> Option<SourceLocation> {
1989        if self.flags.get(id) & EnumAstNodeStatus::HasLocation == 0 {
1990            return None;
1991        }
1992        Some(SourceLocation { sta: self.get_span_start(id), end: self.get_span_end(id), src_id: self.get_source(id) })
1993    }
1994
1995    /// source id of the node location
1996    pub fn get_source(&self, id: u32) -> u32 {
1997        self.sources.borrow().get(self.get_source_id(id) as usize).copied().unwrap_or(0)
1998    }
1999
2000    fn intern_str_or_id(&self, value: StrOrId) -> u32 {
2001        match value {
2002            StrOrId::Str(s) => self.intern_string(s),
2003            StrOrId::Id(id) => id,
2004        }
2005    }
2006
2007    // ---- ast nodes -------------------------------------------------------------------
2008
2009    pub fn create_style_sheet(&self) -> u32 {
2010        let id = self.allocate();
2011        self.data_types.set(id, EnumToken::StyleSheetNodeType);
2012        self.flags.set(id, EnumAstNodeStatus::HasChildren);
2013        id
2014    }
2015
2016    pub fn create_rule(&self, typ: u8, sel: StrOrId, tokens: Option<&[u32]>, state: u32, errors: Option<Vec<ErrorDescription>>) -> u32 {
2017        let id = self.allocate();
2018        self.data_types.set(id, typ);
2019        self.name.set(id, self.intern_str_or_id(sel));
2020        self.flags.set(id, EnumAstNodeStatus::HasChildren | (state & EnumAstNodeStatus::StateMask));
2021        if let Some(tokens) = tokens {
2022            self.append_token_list(id, tokens);
2023        }
2024        if let Some(errors) = errors.filter(|e| !e.is_empty()) {
2025            self.errors.borrow_mut().insert(id, errors);
2026        }
2027        id
2028    }
2029
2030    pub fn create_at_rule(
2031        &self,
2032        typ: u8,
2033        nam: StrOrId,
2034        val: StrOrId,
2035        block: bool,
2036        tokens: Option<&[u32]>,
2037        state: u32,
2038        errors: Option<Vec<ErrorDescription>>,
2039    ) -> u32 {
2040        let id = self.allocate();
2041        self.data_types.set(id, typ);
2042        self.name.set(id, self.intern_str_or_id(nam));
2043        self.string_value.set(id, self.intern_str_or_id(val));
2044        self.flags.set(id, (if block { EnumAstNodeStatus::HasChildren } else { 0 }) | (state & EnumAstNodeStatus::StateMask));
2045        if let Some(tokens) = tokens {
2046            self.append_token_list(id, tokens);
2047        }
2048        if let Some(errors) = errors.filter(|e| !e.is_empty()) {
2049            self.errors.borrow_mut().insert(id, errors);
2050        }
2051        id
2052    }
2053
2054    pub fn create_declaration(&self, typ: u8, nam: StrOrId, val: Option<&[u32]>, state: u32, errors: Option<Vec<ErrorDescription>>) -> u32 {
2055        let id = self.allocate();
2056        self.data_types.set(id, typ);
2057        self.name.set(id, self.intern_str_or_id(nam));
2058        self.flags.set(id, EnumAstNodeStatus::HasValues | (state & EnumAstNodeStatus::StateMask));
2059        if let Some(val) = val {
2060            self.append_token_list(id, val);
2061        }
2062        if let Some(errors) = errors.filter(|e| !e.is_empty()) {
2063            self.errors.borrow_mut().insert(id, errors);
2064        }
2065        id
2066    }
2067
2068    pub fn create_comment(&self, typ: u8, val: StrOrId) -> u32 {
2069        let id = self.allocate();
2070        self.data_types.set(id, typ);
2071        self.string_value.set(id, self.intern_str_or_id(val));
2072        self.flags.set(id, 0);
2073        id
2074    }
2075
2076    // ---- tokens ----------------------------------------------------------------------
2077
2078    /// allocate a token. string values are interned, numeric values are stored in the `numeric_value` column
2079    pub fn create_token(&self, typ: u8, val: TokenValue, unit: Option<&str>) -> u32 {
2080        let id = self.allocate();
2081        self.data_types.set(id, typ);
2082        match val {
2083            TokenValue::Str(s) => self.string_value.set(id, self.intern_string(s)),
2084            TokenValue::Num(n) => self.numeric_value.set(id, n),
2085            TokenValue::None => {}
2086        }
2087        if let Some(unit) = unit {
2088            self.unit.set(id, self.intern_string(unit));
2089        }
2090        id
2091    }
2092
2093    /// allocate a token with a string value
2094    pub fn create_str_token(&self, typ: u8, val: &str) -> u32 {
2095        self.create_token(typ, TokenValue::Str(val), None)
2096    }
2097
2098    /// allocate a token with a numeric value
2099    pub fn create_num_token(&self, typ: u8, val: f64, unit: Option<&str>) -> u32 {
2100        self.create_token(typ, TokenValue::Num(val), unit)
2101    }
2102
2103    /// allocate a color token
2104    pub fn create_color(&self, val: &str, kin: u8, tokens: Option<&[u32]>) -> u32 {
2105        let id = self.allocate();
2106        self.data_types.set(id, EnumToken::ColorTokenType);
2107        self.string_value.set(id, self.intern_string(val));
2108        self.color_type.set(id, kin);
2109        if let Some(tokens) = tokens {
2110            self.append_token_list(id, tokens);
2111        }
2112        id
2113    }
2114
2115    /// allocate a function token
2116    pub fn create_function(&self, typ: u8, name: &str, tokens: Option<&[u32]>) -> u32 {
2117        let id = self.allocate();
2118        self.data_types.set(id, typ);
2119        self.string_value.set(id, self.intern_string(name));
2120        if let Some(tokens) = tokens {
2121            self.append_token_list(id, tokens);
2122        }
2123        id
2124    }
2125
2126    /// allocate a list token (parens, attribute, wrapped values, ...)
2127    pub fn create_list(&self, typ: u8, tokens: Option<&[u32]>) -> u32 {
2128        let id = self.allocate();
2129        self.data_types.set(id, typ);
2130        if let Some(tokens) = tokens {
2131            self.append_token_list(id, tokens);
2132        }
2133        id
2134    }
2135
2136    /// allocate a binary expression token. the operator is stored in the `numeric_value` column
2137    pub fn create_binary_expression(&self, op: u8, l: u32, r: u32) -> u32 {
2138        let id = self.allocate();
2139        self.data_types.set(id, EnumToken::BinaryExpressionTokenType);
2140        self.numeric_value.set(id, op as f64);
2141        self.set_token_list(self.field_list(id, TokenField::L), &[l]);
2142        self.set_token_list(self.field_list(id, TokenField::R), &[r]);
2143        id
2144    }
2145
2146    /// allocate a fraction token
2147    pub fn create_fraction(&self, l: u32, r: u32) -> u32 {
2148        let id = self.allocate();
2149        self.data_types.set(id, EnumToken::FractionTokenType);
2150        self.append_child_list(id, &[l, r]);
2151        id
2152    }
2153
2154    /// true if the numeric token value is a fraction
2155    pub fn has_fraction(&self, id: u32) -> bool {
2156        let child = self.first_child.get(id);
2157        child != 0 && self.data_types.get(child) == EnumToken::FractionTokenType
2158    }
2159
2160    /// fraction token of a numeric token
2161    pub fn get_fraction(&self, id: u32) -> u32 {
2162        let child = self.first_child.get(id);
2163        if child != 0 && self.data_types.get(child) == EnumToken::FractionTokenType {
2164            child
2165        } else {
2166            0
2167        }
2168    }
2169
2170    /// set the fraction value of a numeric token. the numeric value is set to the fraction value
2171    pub fn set_fraction(&self, id: u32, fraction: Option<u32>) {
2172        let child = self.get_fraction(id);
2173        if child != 0 {
2174            self.detach(child);
2175        }
2176        if let Some(fraction) = fraction.filter(|&f| f != 0) {
2177            self.append_child_list(id, &[fraction]);
2178            self.numeric_value.set(
2179                id,
2180                self.numeric_value.get(self.first_child.get(fraction)) / self.numeric_value.get(self.last_child.get(fraction)),
2181            );
2182        }
2183    }
2184
2185    pub fn numerator(&self, id: u32) -> u32 {
2186        self.first_child.get(id)
2187    }
2188
2189    pub fn denominator(&self, id: u32) -> u32 {
2190        self.last_child.get(id)
2191    }
2192
2193    /// string value of a token (`val`)
2194    pub fn str(&self, id: u32) -> SharedStr {
2195        self.resolve_string(self.string_value.get(id))
2196    }
2197
2198    /// set the string value of a token (`val`)
2199    pub fn set_str(&self, id: u32, value: &str) {
2200        self.string_value.set(id, self.intern_string(value));
2201    }
2202
2203    /// set the unit of a token
2204    pub fn set_unit_string(&self, id: u32, unit: Option<&str>) {
2205        self.unit.set(id, unit.map_or(0, |u| self.intern_string(u)));
2206    }
2207
2208    /// true if the token is a numeric token
2209    pub fn is_numeric(&self, id: u32) -> bool {
2210        is_numeric_token_type(self.data_types.get(id))
2211    }
2212
2213    /// replace a token by other tokens in its parent token list
2214    pub fn replace_token(&self, id: u32, tokens: &[u32]) {
2215        self.replace_child(id, tokens);
2216    }
2217
2218    /// a token that can be attached to a new parent: the token itself when it is detached, a deep clone otherwise
2219    pub fn take(&self, token: u32) -> u32 {
2220        if self.parents.get(token) == 0 {
2221            token
2222        } else {
2223            self.clone_node_deep(token, true, None)
2224        }
2225    }
2226
2227    /// copy the data columns of a token
2228    pub fn copy_token(&self, target: u32, source: u32) {
2229        self.data_types.set(target, self.data_types.get(source));
2230        self.name.set(target, self.name.get(source));
2231        self.string_value.set(target, self.string_value.get(source));
2232        self.numeric_value.set(target, self.numeric_value.get(source));
2233        self.unit.set(target, self.unit.get(source));
2234        self.color_type.set(target, self.color_type.get(source));
2235        self.copy_span(target, source);
2236        self.flags.set(target, self.flags.get(source) & !(EnumAstNodeStatus::HasChildren | EnumAstNodeStatus::HasValues));
2237    }
2238
2239    /// reset a token to a new type. the values, the token list and the fields are dropped
2240    pub fn reset_token(&self, id: u32, typ: u8, val: TokenValue, unit: Option<&str>) {
2241        self.data_types.set(id, typ);
2242        self.string_value.set(id, 0);
2243        self.numeric_value.set(id, 0.0);
2244        self.unit.set(id, 0);
2245        self.color_type.set(id, 0);
2246        self.name.set(id, 0);
2247        match val {
2248            TokenValue::Str(s) => self.string_value.set(id, self.intern_string(s)),
2249            TokenValue::Num(n) => self.numeric_value.set(id, n),
2250            TokenValue::None => {}
2251        }
2252        if let Some(unit) = unit {
2253            self.unit.set(id, self.intern_string(unit));
2254        }
2255        self.set_token_list(id, &[]);
2256        self.set_child_list(id, &[]);
2257    }
2258
2259    // ---- plain objects -----------------------------------------------------------------
2260
2261    /// import a plain object (`PlainAstNode` / `PlainToken`). numbers in `chi`, `val`, `l`, ... are node ids
2262    pub fn from_object(&self, node: &Plain) -> u32 {
2263        if let Some(id) = node.as_f64() {
2264            return id as u32;
2265        }
2266        let typ = node.get("typ").as_f64().unwrap_or(0.0) as u8;
2267        if is_node_object_type(typ) {
2268            self.node_from_object(node)
2269        } else {
2270            self.token_from_object(node)
2271        }
2272    }
2273
2274    fn location_to_plain(loc: SourceLocation) -> Plain {
2275        let mut o = PlainObject::new();
2276        o.set("sta", loc.sta);
2277        o.set("end", loc.end);
2278        o.set("srcId", loc.src_id);
2279        Plain::Object(o)
2280    }
2281
2282    /// export a node or a token as a plain object (deep copy)
2283    pub fn to_plain_object(&self, id: u32) -> Plain {
2284        let typ = self.data_types.get(id);
2285        let flags = self.flags.get(id);
2286        if !is_node_object_type(typ) {
2287            return self.token_to_object(id);
2288        }
2289        let mut node = PlainObject::new();
2290        node.set("typ", typ);
2291        match typ {
2292            EnumToken::StyleSheetNodeType => {}
2293            EnumToken::RuleNodeType | EnumToken::KeyframesRuleNodeType => {
2294                node.set("sel", self.resolve_string(self.name.get(id)));
2295            }
2296            EnumToken::AtRuleNodeType | EnumToken::KeyframesAtRuleNodeType => {
2297                node.set("nam", self.resolve_string(self.name.get(id)));
2298                node.set("val", self.resolve_string(self.string_value.get(id)));
2299            }
2300            EnumToken::CommentNodeType | EnumToken::CDOCOMMNodeType => {
2301                node.set("val", self.resolve_string(self.string_value.get(id)));
2302            }
2303            _ => {
2304                node.set("nam", self.resolve_string(self.name.get(id)));
2305                node.set("val", Plain::Array(self.tokens(id).into_iter().map(|t| self.token_to_object(t)).collect()));
2306            }
2307        }
2308        if flags & EnumAstNodeStatus::HasChildren != 0 {
2309            node.set("chi", Plain::Array(self.children(id).into_iter().map(|c| self.to_plain_object(c)).collect()));
2310        }
2311        if flags & EnumAstNodeStatus::HasLocation != 0 {
2312            node.set("loc", self.get_location(id).map_or(Plain::Null, Self::location_to_plain));
2313        }
2314        if flags & EnumAstNodeStatus::StateMask != 0 {
2315            node.set("state", flags & EnumAstNodeStatus::StateMask);
2316        }
2317        if flags & EnumAstNodeStatus::HasValues == 0 && self.first_token.get(id) != 0 {
2318            node.set("tokens", Plain::Array(self.tokens(id).into_iter().map(|t| self.token_to_object(t)).collect()));
2319        }
2320        if let Some(errors) = self.errors.borrow().get(&id) {
2321            node.set("errors", Plain::Array(errors.iter().map(|e| e.to_plain()).collect()));
2322        }
2323        if let Some(raw) = self.raw.borrow().get(&id) {
2324            node.set("raw", raw_to_plain(raw));
2325        }
2326        if let Some(optimized) = self.optimized.borrow().get(&id) {
2327            let optimized = optimized.borrow();
2328            let mut o = PlainObject::new();
2329            o.set("match", optimized.match_);
2330            o.set("optimized", Plain::Array(optimized.optimized.iter().map(|s| Plain::from(s.as_str())).collect()));
2331            o.set("selector", raw_to_plain(&optimized.selector));
2332            o.set("reducible", optimized.reducible);
2333            node.set("optimized", o);
2334        }
2335        Plain::Object(node)
2336    }
2337
2338    /// export a token as a plain object (deep copy)
2339    pub fn token_to_object(&self, id: u32) -> Plain {
2340        let typ = self.data_types.get(id);
2341        let mut token = PlainObject::new();
2342        token.set("typ", typ);
2343        if self.name.get(id) != 0 {
2344            token.set("nam", self.resolve_string(self.name.get(id)));
2345        }
2346        if typ == EnumToken::BinaryExpressionTokenType {
2347            token.set("op", self.numeric_value.get(id));
2348        } else if typ == EnumToken::UnaryExpressionTokenType {
2349            token.set("sign", self.numeric_value.get(id));
2350            let child = self.first_child.get(id);
2351            token.set("val", if child == 0 { Plain::Null } else { self.token_to_object(child) });
2352        } else if typ == EnumToken::FractionTokenType {
2353            token.set("l", self.token_to_object(self.first_child.get(id)));
2354            token.set("r", self.token_to_object(self.last_child.get(id)));
2355        } else if is_numeric_token_type(typ) {
2356            let fraction = self.get_fraction(id);
2357            token.set("val", if fraction == 0 { Plain::Number(self.numeric_value.get(id)) } else { self.token_to_object(fraction) });
2358        } else if self.string_value.get(id) != 0 || typ == EnumToken::IdenTokenType || typ == EnumToken::StringTokenType {
2359            token.set("val", self.resolve_string(self.string_value.get(id)));
2360        }
2361        if self.unit.get(id) != 0 {
2362            let unit = self.resolve_string(self.unit.get(id));
2363            if typ == EnumToken::ColorTokenType {
2364                token.set("cal", unit);
2365            } else if typ == EnumToken::MatchExpressionTokenType {
2366                token.set("attr", unit);
2367            } else {
2368                token.set("unit", unit);
2369            }
2370        }
2371        if typ == EnumToken::ColorTokenType && self.color_type.get(id) != crate::ast::types::ColorType::NONE {
2372            token.set("kin", self.color_type.get(id));
2373        }
2374        if self.first_token.get(id) != 0 {
2375            let tokens = Plain::Array(self.tokens(id).into_iter().map(|t| self.token_to_object(t)).collect());
2376            if matches!(typ, EnumToken::DeclarationNodeType | EnumToken::CssVariableTokenType | EnumToken::CssVariableImportTokenType) {
2377                token.set("val", tokens);
2378            } else {
2379                token.set("chi", tokens);
2380            }
2381        }
2382        if is_structured_token_type(typ) {
2383            for (key, field, single) in structured_fields(typ) {
2384                let Some(list) = self.get_child_at(id, field) else {
2385                    continue;
2386                };
2387                let mut values: Vec<Plain> = self.tokens(list).into_iter().map(|t| self.token_to_object(t)).collect();
2388                token.set(key, if single { if values.is_empty() { Plain::Null } else { values.swap_remove(0) } } else { Plain::Array(values) });
2389            }
2390        }
2391        if self.flags.get(id) & EnumAstNodeStatus::HasLocation != 0 {
2392            token.set("loc", self.get_location(id).map_or(Plain::Null, Self::location_to_plain));
2393        }
2394        Plain::Object(token)
2395    }
2396
2397    /// copy the data of a node (type, strings, values, flags, location, errors)
2398    pub fn clone_node(&self, id: u32) -> u32 {
2399        let target = self.allocate();
2400        self.data_types.set(target, self.data_types.get(id));
2401        self.name.set(target, self.name.get(id));
2402        self.string_value.set(target, self.string_value.get(id));
2403        self.numeric_value.set(target, self.numeric_value.get(id));
2404        self.unit.set(target, self.unit.get(id));
2405        self.color_type.set(target, self.color_type.get(id));
2406        self.flags.set(target, self.flags.get(id));
2407        self.copy_span(target, id);
2408        let errors = self.errors.borrow().get(&id).cloned();
2409        if let Some(errors) = errors {
2410            self.errors.borrow_mut().insert(target, errors);
2411        }
2412        target
2413    }
2414
2415    /// copy a node or a token (`clone(id, deep, cloneMap)`). the tokens of a node are copied, its children are copied
2416    /// with `deep`. the values of a declaration are copied with `deep`
2417    pub fn clone_node_deep(&self, id: u32, deep: bool, mut clone_map: Option<&mut HashMap<u32, u32>>) -> u32 {
2418        let target = self.allocate();
2419        let flags = self.flags.get(id);
2420        if let Some(map) = clone_map.as_deref_mut() {
2421            map.insert(id, target);
2422        }
2423        self.data_types.set(target, self.data_types.get(id));
2424        self.name.set(target, self.name.get(id));
2425        self.string_value.set(target, self.string_value.get(id));
2426        self.numeric_value.set(target, self.numeric_value.get(id));
2427        self.unit.set(target, self.unit.get(id));
2428        self.color_type.set(target, self.color_type.get(id));
2429        self.flags.set(target, flags);
2430        self.copy_span(target, id);
2431        let raw = self.raw.borrow().get(&id).cloned();
2432        if let Some(raw) = raw {
2433            self.raw.borrow_mut().insert(target, raw);
2434        }
2435        let optimized = self.optimized.borrow().get(&id).cloned();
2436        if let Some(optimized) = optimized {
2437            self.optimized.borrow_mut().insert(target, optimized);
2438        }
2439        let errors = self.errors.borrow().get(&id).cloned();
2440        if let Some(errors) = errors {
2441            self.errors.borrow_mut().insert(target, errors);
2442        }
2443        let is_node = flags & (EnumAstNodeStatus::HasChildren | EnumAstNodeStatus::HasValues) != 0;
2444        if !is_node || deep || flags & EnumAstNodeStatus::HasValues == 0 {
2445            let mut token = self.first_token.get(id);
2446            while token != 0 {
2447                let copy = self.clone_node_deep(token, true, clone_map.as_deref_mut());
2448                self.append_token(target, copy);
2449                token = self.next_sibling.get(token);
2450            }
2451        }
2452        if !is_node || deep {
2453            let mut child = self.first_child.get(id);
2454            while child != 0 {
2455                let copy = self.clone_node_deep(child, true, clone_map.as_deref_mut());
2456                self.append_child(target, copy);
2457                child = self.next_sibling.get(child);
2458            }
2459        }
2460        target
2461    }
2462
2463    /// `clone(id)` with the default arguments
2464    pub fn clone(&self, id: u32) -> u32 {
2465        self.clone_node_deep(id, false, None)
2466    }
2467
2468    /// copy a node or a token of another arena into this arena
2469    pub fn import(&self, source: &AstArena, id: u32, deep: bool) -> u32 {
2470        if std::ptr::eq(source, self) {
2471            return id;
2472        }
2473        let target = self.allocate();
2474        let flags = source.flags.get(id);
2475        self.data_types.set(target, source.data_types.get(id));
2476        self.name.set(target, self.intern_shared(&source.resolve_string(source.name.get(id))));
2477        self.string_value.set(target, self.intern_shared(&source.resolve_string(source.string_value.get(id))));
2478        self.numeric_value.set(target, source.numeric_value.get(id));
2479        self.unit.set(target, self.intern_shared(&source.resolve_string(source.unit.get(id))));
2480        self.color_type.set(target, source.color_type.get(id));
2481        self.flags.set(target, flags & !EnumAstNodeStatus::HasLocation);
2482        if let Some(raw) = source.raw.borrow().get(&id) {
2483            self.raw.borrow_mut().insert(target, raw.clone());
2484        }
2485        if let Some(optimized) = source.optimized.borrow().get(&id) {
2486            self.optimized.borrow_mut().insert(target, optimized.clone());
2487        }
2488        if flags & EnumAstNodeStatus::HasLocation != 0 {
2489            self.set_location(target, Some(source.get_source(id)), Some(source.get_span_start(id)), Some(source.get_span_end(id)));
2490        }
2491        if let Some(errors) = source.errors.borrow().get(&id) {
2492            self.errors.borrow_mut().insert(target, errors.clone());
2493        }
2494        let mut token = source.first_token.get(id);
2495        while token != 0 {
2496            let copy = self.import(source, token, true);
2497            self.append_token(target, copy);
2498            token = source.next_sibling.get(token);
2499        }
2500        if deep || flags & EnumAstNodeStatus::HasChildren == 0 {
2501            let mut child = source.first_child.get(id);
2502            while child != 0 {
2503                let copy = self.import(source, child, true);
2504                self.append_child(target, copy);
2505                child = source.next_sibling.get(child);
2506            }
2507        }
2508        target
2509    }
2510
2511    /// index of a child in its parent's children (or tokens) list
2512    pub fn index_of(&self, id: u32) -> i32 {
2513        if self.parents.get(id) == 0 {
2514            return -1;
2515        }
2516        let mut index = 0;
2517        let mut child = self.previous_sibling.get(id);
2518        while child != 0 {
2519            index += 1;
2520            child = self.previous_sibling.get(child);
2521        }
2522        index
2523    }
2524
2525    /// insert nodes before a child
2526    pub fn insert_before(&self, reference: u32, nodes: &[u32]) {
2527        for &node in nodes {
2528            if node == reference || node == 0 {
2529                continue;
2530            }
2531            self.set_previous_sibling(reference, node);
2532        }
2533    }
2534
2535    /// insert nodes after a child
2536    pub fn insert_after(&self, mut reference: u32, nodes: &[u32]) {
2537        for &node in nodes {
2538            if node == reference || node == 0 {
2539                continue;
2540            }
2541            self.set_next_sibling(reference, node);
2542            reference = node;
2543        }
2544    }
2545
2546    /// prepend children
2547    pub fn prepend_children(&self, id: u32, nodes: &[u32]) {
2548        let first = self.first_child.get(id);
2549        if first == 0 {
2550            self.append_child_list(id, nodes);
2551        } else {
2552            self.insert_before(first, nodes);
2553        }
2554    }
2555
2556    /// replace a child with other nodes. the node itself may be part of the replacement
2557    pub fn replace_child(&self, id: u32, nodes: &[u32]) {
2558        if self.parents.get(id) == 0 {
2559            return;
2560        }
2561        match nodes.iter().position(|&n| n == id) {
2562            None => {
2563                self.insert_before(id, nodes);
2564                self.detach(id);
2565            }
2566            Some(index) => {
2567                self.insert_before(id, &nodes[..index]);
2568                self.insert_after(id, &nodes[index + 1..]);
2569            }
2570        }
2571    }
2572
2573    pub fn has_children(&self, id: u32) -> bool {
2574        self.flags.get(id) & EnumAstNodeStatus::HasChildren != 0
2575    }
2576
2577    /// rule selector
2578    pub fn get_selector(&self, id: u32) -> SharedStr {
2579        self.resolve_string(self.name.get(id))
2580    }
2581
2582    pub fn set_selector(&self, id: u32, sel: &str) {
2583        self.name.set(id, self.intern_string(sel));
2584    }
2585
2586    pub fn set_name_string(&self, id: u32, nam: &str) {
2587        self.name.set(id, self.intern_string(nam));
2588    }
2589
2590    pub fn set_value_string(&self, id: u32, val: &str) {
2591        self.string_value.set(id, self.intern_string(val));
2592    }
2593
2594    // ---- nesting rules expansion ---------------------------------------------------------------
2595
2596    /// expand the css nesting rules of a stylesheet, a rule or an at-rule, in place
2597    pub fn expand(&self, ast: u32) -> u32 {
2598        if self.flags.get(ast) & SKIP_STATES != 0 {
2599            return ast;
2600        }
2601        let mut node = self.first_child.get(ast);
2602        while node != 0 {
2603            let next = self.next_sibling.get(node);
2604            let typ = self.data_types.get(node);
2605            if typ == EnumToken::RuleNodeType {
2606                self.expand_rule(node, ast, next);
2607            } else if typ == EnumToken::AtRuleNodeType
2608                && self.flags.get(node) & EnumAstNodeStatus::HasChildren != 0
2609                && !self.string_equals(self.name.get(node), "mixin")
2610            {
2611                let mut j = self.last_child.get(node);
2612                while j != 0 {
2613                    if matches!(self.data_types.get(j), EnumToken::RuleNodeType | EnumToken::AtRuleNodeType) {
2614                        self.expand(node);
2615                        break;
2616                    }
2617                    j = self.previous_sibling.get(j);
2618                }
2619            }
2620            node = next;
2621        }
2622        ast
2623    }
2624
2625    /// replace the nesting selector '&' of a selector
2626    pub fn replace_compound(&self, input: &str, replace: &str) -> String {
2627        let tokens = crate::parser::parse::parse_string(self, input);
2628        let mut walker = ValueWalker::of_tokens(&tokens, WalkerValueOptions::default(), false);
2629        while let Some(t) = walker.next(self) {
2630            if self.data_types.get(t) == EnumToken::NestingSelectorTokenType {
2631                if tokens.len() == 2 {
2632                    let literal = self.replace_compound_literal(&self.resolve_string(self.string_value.get(t)), replace);
2633                    self.reset_token(t, EnumToken::LiteralTokenType, TokenValue::Str(&literal), None);
2634                    continue;
2635                }
2636                let rule = crate::ast::minify::split_rule(replace);
2637                let value = if rule.len() > 1 { format!(":is({})", replace) } else { replace.to_string() };
2638                self.reset_token(t, EnumToken::LiteralTokenType, TokenValue::Str(&value), None);
2639            }
2640        }
2641        tokens.iter().map(|&t| crate::printer::render::render_value_default(self, t)).collect()
2642    }
2643
2644    /// properties of the arena
2645    pub fn export_properties(&self) -> ArenaProperties {
2646        let mut properties = self.base.export_properties();
2647        properties.kind = "AstArena".into();
2648        properties.sources = Some(self.sources.borrow().clone());
2649        let lengths = self.input_lengths.borrow();
2650        let max = lengths.keys().max().map_or(0, |&m| m as usize + 1);
2651        properties.input_lengths = Some((0..max).map(|i| lengths.get(&(i as u32)).copied()).collect());
2652        properties
2653    }
2654
2655    /// initialize the arena from exported properties and column buffers
2656    pub fn import_properties(&self, properties: &ArenaProperties, transferables: ArenaTransferables) {
2657        self.base.import_properties(properties, transferables);
2658        *self.sources.borrow_mut() = properties.sources.clone().unwrap_or_default();
2659        self.raw.borrow_mut().clear();
2660        self.optimized.borrow_mut().clear();
2661        *self.input_lengths.borrow_mut() = properties
2662            .input_lengths
2663            .as_ref()
2664            .map(|l| l.iter().enumerate().filter_map(|(i, v)| v.map(|v| (i as u32, v))).collect())
2665            .unwrap_or_default();
2666    }
2667
2668    /// create an ast node from a plain object
2669    fn node_from_object(&self, node: &Plain) -> u32 {
2670        let id = self.allocate();
2671        let typ = node.get("typ").as_f64().unwrap_or(0.0) as u8;
2672        self.data_types.set(id, typ);
2673        let str_of = |v: &Plain| v.as_str().map(|s| s.to_string());
2674        match typ {
2675            EnumToken::StyleSheetNodeType => self.flags.set(id, EnumAstNodeStatus::HasChildren),
2676            EnumToken::RuleNodeType | EnumToken::KeyframesRuleNodeType => {
2677                let sel = str_of(node.get("sel")).or_else(|| str_of(node.get("nam"))).unwrap_or_default();
2678                self.name.set(id, self.intern_string(&sel));
2679                self.flags.set(id, EnumAstNodeStatus::HasChildren);
2680                if let Some(raw) = plain_to_raw(node.get("raw")) {
2681                    self.raw.borrow_mut().insert(id, Rc::new(RawSelector::from(raw)));
2682                }
2683                if let Some(o) = node.get("optimized").as_object() {
2684                    self.optimized.borrow_mut().insert(
2685                        id,
2686                        Rc::new(RefCell::new(OptimizedSelector {
2687                            match_: o.get("match").is_some_and(|m| m.truthy()),
2688                            optimized: o
2689                                .get("optimized")
2690                                .and_then(|v| v.as_array())
2691                                .map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect())
2692                                .unwrap_or_default(),
2693                            selector: o.get("selector").and_then(plain_to_raw).unwrap_or_default(),
2694                            reducible: o.get("reducible").is_some_and(|m| m.truthy()),
2695                        })),
2696                    );
2697                }
2698                if let Some(val) = node.get("val").as_str() {
2699                    self.string_value.set(id, self.intern_string(val));
2700                }
2701            }
2702            EnumToken::AtRuleNodeType | EnumToken::KeyframesAtRuleNodeType => {
2703                self.name.set(id, self.intern_string(node.get("nam").as_str().unwrap_or("")));
2704                self.string_value.set(id, self.intern_string(node.get("val").as_str().unwrap_or("")));
2705                self.flags.set(id, if node.get("chi").is_nullish() { 0 } else { EnumAstNodeStatus::HasChildren });
2706            }
2707            EnumToken::CommentNodeType | EnumToken::CDOCOMMNodeType => {
2708                self.string_value.set(id, self.intern_string(node.get("val").as_str().unwrap_or("")));
2709                self.flags.set(id, 0);
2710            }
2711            _ => {
2712                self.name.set(id, self.intern_string(node.get("nam").as_str().unwrap_or("")));
2713                self.flags.set(id, EnumAstNodeStatus::HasValues);
2714                if let Some(values) = node.get("val").as_array() {
2715                    for token in values {
2716                        let t = self.from_object(token);
2717                        self.append_token(id, t);
2718                    }
2719                }
2720            }
2721        }
2722        if let Some(tokens) = node.get("tokens").as_array() {
2723            for token in tokens {
2724                let t = self.from_object(token);
2725                self.append_token(id, t);
2726            }
2727        }
2728        self.set_state(id, node.get("state").as_f64().unwrap_or(0.0) as u32);
2729        if let Some(loc) = node.get("loc").as_object() {
2730            self.set_location(id, plain_u32(loc.get("srcId")), plain_u32(loc.get("sta")), plain_u32(loc.get("end")));
2731        }
2732        if let Some(errors) = node.get("errors").as_array().filter(|e| !e.is_empty()) {
2733            self.errors.borrow_mut().insert(id, errors.iter().map(ErrorDescription::from_plain).collect());
2734        }
2735        if let Some(children) = node.get("chi").as_array() {
2736            if self.flags.get(id) & EnumAstNodeStatus::HasChildren != 0 {
2737                for child in children {
2738                    let c = self.from_object(child);
2739                    self.append_child_list(id, &[c]);
2740                }
2741            }
2742        }
2743        id
2744    }
2745
2746    /// create a token from a plain object
2747    fn token_from_object(&self, plain: &Plain) -> u32 {
2748        let id = self.allocate();
2749        let typ = plain.get("typ").as_f64().unwrap_or(0.0) as u8;
2750        self.data_types.set(id, typ);
2751        if let Some(nam) = plain.get("nam").as_str() {
2752            self.name.set(id, self.intern_string(nam));
2753        }
2754        if let Some(unit) = plain.get("unit").as_str() {
2755            self.unit.set(id, self.intern_string(unit));
2756        }
2757        if let Some(kin) = plain.get("kin").as_f64() {
2758            self.color_type.set(id, kin as u8);
2759        }
2760        if let Some(cal) = plain.get("cal").as_str() {
2761            self.unit.set(id, self.intern_string(cal));
2762        }
2763        if let Some(attr) = plain.get("attr").as_str() {
2764            self.unit.set(id, self.intern_string(attr));
2765        }
2766        let val = plain.get("val");
2767        if typ == EnumToken::BinaryExpressionTokenType {
2768            self.numeric_value.set(id, plain.get("op").as_f64().unwrap_or(f64::NAN));
2769        } else if typ == EnumToken::UnaryExpressionTokenType {
2770            self.numeric_value.set(id, plain.get("sign").as_f64().unwrap_or(f64::NAN));
2771            let v = self.from_object(val);
2772            self.append_child_list(id, &[v]);
2773        } else if typ == EnumToken::FractionTokenType {
2774            let l = self.from_object(plain.get("l"));
2775            let r = self.from_object(plain.get("r"));
2776            self.append_child_list(id, &[l, r]);
2777        } else if let Some(s) = val.as_str() {
2778            if is_numeric_token_type(typ) {
2779                self.numeric_value.set(id, crate::utils::number::js_parse_number(s));
2780            } else {
2781                self.string_value.set(id, self.intern_string(s));
2782            }
2783        } else if let Some(n) = val.as_f64() {
2784            self.numeric_value.set(id, n);
2785        } else if val.as_object().is_some() {
2786            let fraction = self.from_object(val);
2787            self.set_fraction(id, Some(fraction));
2788        } else if let Some(values) = val.as_array().filter(|_| typ != EnumToken::MediaRangeQueryTokenType) {
2789            for child in values {
2790                let c = self.from_object(child);
2791                self.append_token(id, c);
2792            }
2793        }
2794        if let Some(children) = plain.get("chi").as_array() {
2795            for child in children {
2796                let c = self.from_object(child);
2797                self.append_token(id, c);
2798            }
2799        }
2800        if is_structured_token_type(typ) {
2801            for (key, field) in [("l", TokenField::L), ("r", TokenField::R), ("op", TokenField::Op), ("op1", TokenField::Op), ("op2", TokenField::Op2), ("val", TokenField::Val)] {
2802                let value = plain.get(key);
2803                if value.is_nullish() {
2804                    continue;
2805                }
2806                let field_tokens: Vec<u32> = match value.as_array() {
2807                    Some(values) => values.iter().map(|v| self.from_object(v)).collect(),
2808                    None => vec![self.from_object(value)],
2809                };
2810                self.set_token_list(self.field_list(id, field), &field_tokens);
2811            }
2812        }
2813        if let Some(loc) = plain.get("loc").as_object() {
2814            self.set_location(id, plain_u32(loc.get("srcId")), plain_u32(loc.get("sta")), plain_u32(loc.get("end")));
2815        }
2816        id
2817    }
2818
2819    /// expand a rule: the nested rules and at-rules are moved out of the rule, into `parent` before `before`. the rule
2820    /// is detached when it has no children left
2821    pub fn expand_rule(&self, node: u32, parent: u32, before: u32) {
2822        if self.flags.get(node) & SKIP_STATES != 0 {
2823            return;
2824        }
2825        let ast = node;
2826        let sel = self.resolve_string(self.name.get(ast));
2827        let place = |child: u32| {
2828            if before == 0 {
2829                self.append_child(parent, child);
2830            } else {
2831                self.insert_before(before, &[child]);
2832            }
2833        };
2834        let is_pseudo_element = |t: &String| t == ":before" || t == ":after" || t.starts_with("::");
2835        if self.data_types.get(ast) == EnumToken::RuleNodeType {
2836            let mut child = self.first_child.get(ast);
2837            while child != 0 {
2838                let next = self.next_sibling.get(child);
2839                let typ = self.data_types.get(child);
2840                if typ == EnumToken::RuleNodeType {
2841                    let rule = child;
2842                    let rule_sel = self.resolve_string(self.name.get(rule));
2843                    if !rule_sel.contains('&') {
2844                        let mut sel_rule = crate::ast::minify::split_rule(&rule_sel);
2845                        let ar_self = crate::ast::minify::split_rule(&sel)
2846                            .into_iter()
2847                            .filter(|r| r.iter().all(|t| !is_pseudo_element(t)))
2848                            .map(|r| r.concat())
2849                            .collect::<Vec<_>>()
2850                            .join(",");
2851                        if ar_self.is_empty() {
2852                            self.detach(rule);
2853                            child = next;
2854                            continue;
2855                        }
2856                        for arr in sel_rule.iter_mut() {
2857                            let first = arr.first().and_then(|s| s.chars().next()).map(String::from).unwrap_or_default();
2858                            if crate::syntax::constants::COMBINATORS.contains(&first.as_str()) {
2859                                arr.insert(0, ar_self.clone());
2860                            } else {
2861                                arr.insert(0, " ".into());
2862                                arr.insert(0, ar_self.clone());
2863                            }
2864                        }
2865                        let selector = sel_rule.iter().map(|r| r.concat()).collect::<Vec<_>>().join(",");
2866                        self.name.set(rule, self.intern_string(&selector));
2867                    } else {
2868                        let mut child_selector_compound: Vec<String> = Vec::new();
2869                        let mut with_compound: Vec<String> = Vec::new();
2870                        let mut without_compound: Vec<String> = Vec::new();
2871                        let rules: Vec<Vec<String>> = crate::ast::minify::split_rule(&sel)
2872                            .into_iter()
2873                            .filter(|r| r.iter().all(|t| !is_pseudo_element(t)))
2874                            .collect();
2875                        let parent_selector = !sel.contains('&');
2876                        if rules.is_empty() {
2877                            self.detach(rule);
2878                            child = next;
2879                            continue;
2880                        }
2881                        let raw = self.raw.borrow().get(&rule).cloned().unwrap_or_else(|| Rc::new(RawSelector::from(crate::ast::minify::split_rule(&rule_sel))));
2882                        for sel in raw.iter() {
2883                            let s: String = sel.concat();
2884                            if s.contains('&') || parent_selector {
2885                                if s.get(1..).is_none_or(|rest| !rest.contains('&')) {
2886                                    if s.starts_with('&') {
2887                                        if s.as_bytes().get(1) == Some(&b' ') {
2888                                            child_selector_compound.push(s[2..].to_string());
2889                                        } else if s == "&" || parent_selector {
2890                                            with_compound.push(s);
2891                                        }
2892                                    } else {
2893                                        without_compound.push(s);
2894                                    }
2895                                } else {
2896                                    with_compound.push(s);
2897                                }
2898                            }
2899                        }
2900                        let mut selectors: Vec<String> = Vec::new();
2901                        let selector: String = if rules.len() > 1 {
2902                            format!(":is({})", rules.iter().map(|a| a.concat()).collect::<Vec<_>>().join(","))
2903                        } else {
2904                            rules[0].concat()
2905                        };
2906                        if !child_selector_compound.is_empty() {
2907                            if child_selector_compound.len() == 1 {
2908                                selectors.push(self.replace_compound(&format!("& {}", js_trim(&child_selector_compound[0])), &selector));
2909                            } else {
2910                                let joined = child_selector_compound.iter().map(|c| js_trim(c)).collect::<Vec<_>>().join(",");
2911                                selectors.push(self.replace_compound(&format!("& :is({})", joined), &selector));
2912                            }
2913                        }
2914                        if !with_compound.is_empty() && with_compound.iter().all(|t| t.starts_with('&') && !t[1..].contains('&')) {
2915                            without_compound.extend(with_compound.iter().map(|t| t[1..].to_string()));
2916                            with_compound.clear();
2917                        }
2918                        if !without_compound.is_empty() {
2919                            if without_compound.len() == 1 {
2920                                let w = &without_compound[0];
2921                                let all_alpha = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphabetic());
2922                                let use_is = rules.len() == 1
2923                                    && selector.bytes().next().is_some_and(|b| b.is_ascii_alphabetic() || b == b'.' || b == b':')
2924                                    && selector.contains(' ')
2925                                    && all_alpha(w);
2926                                let compound = if use_is { ":is(&)" } else { "&" };
2927                                let input = if rules.len() == 1 {
2928                                    if use_is {
2929                                        format!("{}:is(&)", w)
2930                                    } else if selector.bytes().next().is_some_and(|b| b == b'.' || b == b':') && all_alpha(w) {
2931                                        format!("{}{}", w, compound)
2932                                    } else {
2933                                        format!("{}{}", compound, w)
2934                                    }
2935                                } else if !w.is_empty() && w.bytes().all(|b| b.is_ascii_alphabetic() || b == b':') {
2936                                    format!("{}{}", js_trim(w), compound)
2937                                } else if !w.is_empty() && !w.chars().any(is_js_whitespace) {
2938                                    format!("&{}", js_trim(w))
2939                                } else {
2940                                    format!("&:is({})", js_trim(w))
2941                                };
2942                                selectors.push(self.replace_compound(&input, &selector));
2943                            } else {
2944                                let joined = without_compound.iter().map(|c| js_trim(c)).collect::<Vec<_>>().join(",");
2945                                selectors.push(self.replace_compound(&format!("&:is({})", joined), &selector));
2946                            }
2947                        }
2948                        if with_compound.len() == 1 {
2949                            selectors.push(self.replace_compound(&with_compound[0], &selector));
2950                        }
2951                        let joined = selectors.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(",");
2952                        self.name.set(rule, self.intern_string(&joined));
2953                    }
2954                    place(rule);
2955                    self.expand_rule(rule, parent, before);
2956                } else if typ == EnumToken::AtRuleNodeType
2957                    && (self.flags.get(child) & EnumAstNodeStatus::HasChildren == 0 || self.string_equals(self.name.get(child), "apply"))
2958                {
2959                    // an at-rule without a block or an `@apply` rule stays in the rule
2960                } else if typ == EnumToken::AtRuleNodeType {
2961                    let ast_at_rule = child;
2962                    let at_rule_name = self.resolve_string(self.name.get(ast_at_rule));
2963                    if &*at_rule_name == "scope" {
2964                        let at_rule_value = self.resolve_string(self.string_value.get(ast_at_rule));
2965                        if at_rule_value.contains('&') {
2966                            let replaced = self.replace_compound(&at_rule_value, &sel);
2967                            self.string_value.set(ast_at_rule, self.intern_string(&replaced));
2968                        }
2969                        let has_nesting = self
2970                            .child_iter(ast_at_rule)
2971                            .any(|t| self.data_types.get(t) == EnumToken::RuleNodeType && self.resolve_string(self.name.get(t)).contains('&'));
2972                        if has_nesting {
2973                            let clone = self.clone(node);
2974                            self.move_children(ast_at_rule, clone, 0);
2975                            self.expand_rule(clone, ast_at_rule, 0);
2976                            self.move_children(clone, ast_at_rule, self.first_child.get(ast_at_rule));
2977                        }
2978                        place(ast_at_rule);
2979                    } else {
2980                        let clone = self.clone(ast);
2981                        self.move_children(ast_at_rule, clone, 0);
2982                        self.expand_rule(clone, ast_at_rule, 0);
2983                        if self.first_child.get(clone) != 0 {
2984                            if self.first_child.get(ast_at_rule) == 0 {
2985                                self.append_child(ast_at_rule, clone);
2986                            } else {
2987                                self.insert_before(self.first_child.get(ast_at_rule), &[clone]);
2988                            }
2989                        }
2990                        place(ast_at_rule);
2991                        let mut r = self.first_child.get(ast_at_rule);
2992                        while r != 0 {
2993                            let next_rule = self.next_sibling.get(r);
2994                            if self.data_types.get(r) == EnumToken::AtRuleNodeType {
2995                                if self.flags.get(r) & EnumAstNodeStatus::HasChildren != 0 {
2996                                    let val = self.resolve_string(self.string_value.get(ast_at_rule));
2997                                    let r_val = self.resolve_string(self.string_value.get(r));
2998                                    if !val.is_empty() && !r_val.is_empty() {
2999                                        let r_name = self.resolve_string(self.name.get(r));
3000                                        if &*at_rule_name == "media" && &*r_name == "media" {
3001                                            self.string_value.set(r, self.intern_string(&format!("{} and {}", val, r_val)));
3002                                        } else if &*at_rule_name == "layer" && &*r_name == "layer" {
3003                                            self.string_value.set(r, self.intern_string(&format!("{}.{}", val, r_val)));
3004                                        }
3005                                    }
3006                                    place(r);
3007                                } else {
3008                                    self.detach(r);
3009                                }
3010                            }
3011                            r = next_rule;
3012                        }
3013                    }
3014                    if self.first_child.get(ast_at_rule) == 0 {
3015                        self.detach(ast_at_rule);
3016                    }
3017                }
3018                child = next;
3019            }
3020        }
3021        if self.first_child.get(ast) == 0 {
3022            self.detach(ast);
3023        }
3024    }
3025
3026    /// (sic) port of `replaceCompoundLiteral()`: the tokens are `""` followed by `"&", ""` per `&` of the selector,
3027    /// sorted so that the `&` come last, then the `&` are replaced
3028    pub fn replace_compound_literal(&self, selector: &str, replace: &str) -> String {
3029        let count = selector.matches('&').count();
3030        // [""] + ["&", ""] * count, stable sorted with "&" last: all the "" then all the "&"
3031        replace.repeat(count)
3032    }
3033}
3034
3035/// `String.prototype.trim()`
3036pub fn js_trim(s: &str) -> &str {
3037    s.trim_matches(is_js_whitespace)
3038}
3039
3040/// javascript `\s`
3041pub fn is_js_whitespace(c: char) -> bool {
3042    c.is_whitespace() || c == '\u{feff}'
3043}
3044
3045fn plain_u32(v: Option<&Plain>) -> Option<u32> {
3046    v.and_then(|v| v.as_f64()).map(|n| n as u32)
3047}
3048
3049fn raw_to_plain(raw: &RawSelectorTokens) -> Plain {
3050    Plain::Array(raw.iter().map(|r| Plain::Array(r.iter().map(|s| Plain::from(s.as_str())).collect())).collect())
3051}
3052
3053fn plain_to_raw(v: &Plain) -> Option<RawSelectorTokens> {
3054    v.as_array().map(|a| {
3055        a.iter()
3056            .map(|r| r.as_array().map(|x| x.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default())
3057            .collect()
3058    })
3059}