1use 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#[allow(non_snake_case)]
23pub mod TokenField {
24 pub const L: u32 = 0;
26 pub const R: u32 = 1;
28 pub const Op: u32 = 2;
30 pub const Op2: u32 = 3;
32 pub const Val: u32 = 4;
34}
35
36pub 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
53pub 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
74pub type StructuredField = (&'static str, u32, bool);
76
77pub 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
112pub 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#[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#[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
162pub const SKIP_STATES: u32 = EnumAstNodeStatus::Invalid
164 | EnumAstNodeStatus::Disallowed
165 | EnumAstNodeStatus::Unknown
166 | EnumAstNodeStatus::Unparsed
167 | EnumAstNodeStatus::Malformed;
168
169pub struct Arena {
176 string_table: UnsafeCell<StringTable>,
178 pub root: u32,
180 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 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 pub spans: Column<u64>,
199 pub errors: RefCell<HashMap<u32, Vec<ErrorDescription>>>,
201 free_list: Cell<u32>,
203 generation: Cell<u32>,
205 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 #[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 #[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 pub fn generation(&self) -> u32 {
284 self.generation.get()
285 }
286
287 pub fn generation_ptr(&self) -> *const u32 {
289 self.generation.as_ptr()
290 }
291
292 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 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 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 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 pub fn intern_string(&self, str: &str) -> u32 {
359 self.strings().intern(str)
360 }
361
362 pub fn intern_rc(&self, str: &Rc<str>) -> u32 {
364 self.strings().intern_rc(str)
365 }
366
367 pub fn intern_shared(&self, str: &SharedStr) -> u32 {
369 self.strings().intern_shared(str)
370 }
371
372 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 pub fn intern_units(&self, codes: &[u16]) -> u32 {
379 self.strings().intern_units(codes)
380 }
381
382 pub fn intern_canonical(&self, start: u32, end: u32) -> u32 {
384 self.strings().intern_canonical(start, end)
385 }
386
387 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 pub fn source_text(&self, source: usize) -> Option<CodeUnits> {
398 self.strings().text(source).cloned()
399 }
400
401 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 pub fn lower_string_id(&self, id: u32) -> u32 {
432 self.strings().lower(id)
433 }
434
435 pub fn copy_string_ascii(&self, id: u32, target: &mut Vec<u8>) -> isize {
437 self.strings().copy_ascii(id, target)
438 }
439
440 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 let value = self.with_string(id, compute);
447 self.strings().set_flag(id, flag, value);
448 value
449 }
450
451 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 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 pub fn copy_string(&self, id: u32, target: &mut Vec<u16>) -> usize {
473 self.strings().copy_into(id, target)
474 }
475
476 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 pub fn intern_builder(&self, builder: &StringBuilder) -> u32 {
483 builder.intern(self.strings())
484 }
485
486 pub fn string_epoch(&self) -> u64 {
488 self.strings().epoch
489 }
490
491 pub fn with_string<R>(&self, id: u32, f: impl FnOnce(&str) -> R) -> R {
493 let table: &StringTable = self.strings();
496 table.with_str(id, f)
497 }
498
499 pub fn resolve_string(&self, id: u32) -> SharedStr {
501 self.strings().get(id)
502 }
503
504 #[inline]
507 pub fn get_type(&self, id: u32) -> u8 {
508 self.data_types.get(id)
509 }
510
511 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 #[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 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 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 pub fn walk<'f>(&self, node: u32, filter: Option<WalkerFilter<'f>>, reverse: bool) -> NodeWalker<'f> {
907 NodeWalker::new(node, filter, reverse)
908 }
909
910 pub fn walk_with<'f>(&self, node: u32, options: WalkerOptions<'f>) -> NodeWalker<'f> {
912 NodeWalker::with_options(node, options)
913 }
914
915 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 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 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 pub fn visit_values(&self, tokens: &[u32], mut visitor: impl FnMut(&Self, u32)) {
934 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn child_count(&self, id: u32) -> u32 {
1604 self.child_iter(id).count() as u32
1605 }
1606
1607 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 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 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 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 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
1690use crate::plain::{Plain, PlainObject};
1695use crate::types::SourceLocation;
1696
1697pub type RawSelectorTokens = Vec<Vec<String>>;
1699
1700#[derive(Clone, Debug, Default)]
1703pub struct RawSelector {
1704 tokens: RawSelectorTokens,
1705 prefixes: std::cell::OnceCell<Rc<[String]>>,
1706}
1707
1708impl RawSelector {
1709 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 self.prefixes = std::cell::OnceCell::new();
1733 &mut self.tokens
1734 }
1735}
1736
1737pub type SharedOptimizedSelector = Rc<RefCell<OptimizedSelector>>;
1740
1741#[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
1750pub 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#[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#[derive(Clone, Copy, Debug)]
1795pub enum TokenValue<'a> {
1796 None,
1797 Str(&'a str),
1798 Num(f64),
1799}
1800
1801pub struct AstArena {
1803 base: Arena,
1804 pub raw: RefCell<HashMap<u32, Rc<RawSelector>>>,
1807 pub optimized: RefCell<HashMap<u32, SharedOptimizedSelector>>,
1809 pub first_parts: RefCell<(u64, HashMap<u32, Option<Rc<[u16]>>>)>,
1812 pub selector_prefixes: RefCell<(u64, HashMap<u32, Rc<[String]>>)>,
1814 pub sources: RefCell<Vec<u32>>,
1816 pub input_lengths: RefCell<HashMap<u32, u32>>,
1818 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 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 pub fn register(arena: &Rc<Self>) {
1847 *arena.this.borrow_mut() = Rc::downgrade(arena);
1848 }
1849
1850 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 arena.intern_string("");
1868 arena.flags.set(arena.root, EnumAstNodeStatus::HasChildren);
1869 arena
1870 }
1871
1872 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 pub fn get_state(&self, id: u32) -> u32 {
1907 self.flags.get(id) & EnumAstNodeStatus::StateMask
1908 }
1909
1910 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 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 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 #[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 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 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 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 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 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 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 pub fn create_str_token(&self, typ: u8, val: &str) -> u32 {
2085 self.create_token(typ, TokenValue::Str(val), None)
2086 }
2087
2088 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 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 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 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 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 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 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 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 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 pub fn str(&self, id: u32) -> SharedStr {
2185 self.resolve_string(self.string_value.get(id))
2186 }
2187
2188 pub fn set_str(&self, id: u32, value: &str) {
2190 self.string_value.set(id, self.intern_string(value));
2191 }
2192
2193 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 pub fn is_numeric(&self, id: u32) -> bool {
2200 is_numeric_token_type(self.data_types.get(id))
2201 }
2202
2203 pub fn replace_token(&self, id: u32, tokens: &[u32]) {
2205 self.replace_child(id, tokens);
2206 }
2207
2208 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 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 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 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 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 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 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 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 pub fn clone(&self, id: u32) -> u32 {
2455 self.clone_node_deep(id, false, None)
2456 }
2457
2458 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 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 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 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 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 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 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 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 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 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 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 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 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 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 } 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 pub fn replace_compound_literal(&self, selector: &str, replace: &str) -> String {
3019 let count = selector.matches('&').count();
3020 replace.repeat(count)
3022 }
3023}
3024
3025pub fn js_trim(s: &str) -> &str {
3027 s.trim_matches(is_js_whitespace)
3028}
3029
3030pub 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}