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