css_ast 0.0.28

CSS Abstract Syntax Trees with visitable nodes and style value types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
#[cfg(feature = "visitable")]
use crate::visit::NodeId;
use crate::{
	CssAtomSet,
	traits::{AppliesTo, BoxPortion, BoxSide, PropertyGroup},
};
use bitmask_enum::bitmask;
use css_lexer::{Span, ToSpan};
use css_parse::{NodeMetadata, SemanticEq, ToCursors};

/// How unitless zero (0 without a unit) resolves in a given context.
///
/// For most Style Values, a `0` can be a drop-in replacement for `0px`, but
/// certain style values will provide discrete syntax for `0px` and `0`, meaning
/// they resolve to different things. For properties that accept both `<number>`
/// and `<length>`, unitless zero may resolve to a _different value_. Using a
/// piece of metadata to describe this can be helpful for linting/minifying -
/// avoiding a reduction in semantic meaning.
///
/// Examples:
/// - `width: 0px` == `width: 0` (unitless zero resolves to length)
/// - `line-height: 0px` != `line-height: 0` (unitless zero resolves to number = 0x multiplier)
/// - `tab-size: 0px` != `tab-size: 0` (unitless zero resolves to number = 0 tab characters)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum UnitlessZeroResolves {
	/// Unitless zero resolves to a length (0 = 0px).
	#[default]
	Length,
	/// Unitless zero resolves to a number or percentage. NOT safe to reduce.
	Number,
}

#[bitmask(u32)]
#[bitmask_config(vec_debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AtRuleId {
	Charset,
	ColorProfile,
	Container,
	CounterStyle,
	FontFace,
	FontFeatureValues,
	FontPaletteValues,
	Import,
	Keyframes,
	Layer,
	Media,
	Namespace,
	Page,
	Property,
	Scope,
	StartingStyle,
	Supports,
	Document,
	WebkitKeyframes,
	MozDocument,
}

#[cfg(feature = "visitable")]
impl NodeId {
	/// Converts a NodeId to an AtRuleId if the node is an at-rule type.
	/// Returns `None` for non-at-rule nodes like StyleRule, Declaration, etc.
	pub fn to_at_rule_id(self) -> Option<AtRuleId> {
		match self {
			Self::CharsetRule => Some(AtRuleId::Charset),
			Self::ContainerRule => Some(AtRuleId::Container),
			Self::CounterStyleRule => Some(AtRuleId::CounterStyle),
			Self::DocumentRule => Some(AtRuleId::Document),
			Self::FontFaceRule => Some(AtRuleId::FontFace),
			Self::KeyframesRule => Some(AtRuleId::Keyframes),
			Self::LayerRule => Some(AtRuleId::Layer),
			Self::MediaRule => Some(AtRuleId::Media),
			Self::MozDocumentRule => Some(AtRuleId::MozDocument),
			Self::NamespaceRule => Some(AtRuleId::Namespace),
			Self::PageRule => Some(AtRuleId::Page),
			Self::PropertyRule => Some(AtRuleId::Property),
			Self::StartingStyleRule => Some(AtRuleId::StartingStyle),
			Self::SupportsRule => Some(AtRuleId::Supports),
			Self::WebkitKeyframesRule => Some(AtRuleId::WebkitKeyframes),
			_ => None,
		}
	}
}

#[bitmask(u8)]
#[bitmask_config(vec_debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum VendorPrefixes {
	Moz,
	WebKit,
	O,
	Ms,
}

impl TryFrom<CssAtomSet> for VendorPrefixes {
	type Error = ();
	fn try_from(atom: CssAtomSet) -> Result<Self, Self::Error> {
		const VENDOR_FLAG: u32 = 0b00000000_10000000_00000000_00000000;
		const VENDORS: [VendorPrefixes; 4] =
			[VendorPrefixes::WebKit, VendorPrefixes::Moz, VendorPrefixes::Ms, VendorPrefixes::O];

		let atom_bits = atom as u32;
		if atom_bits & VENDOR_FLAG == 0 {
			return Err(());
		}
		let index = (atom_bits >> 21) & 0b11;
		Ok(VENDORS[index as usize])
	}
}

#[bitmask(u8)]
#[bitmask_config(vec_debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DeclarationKind {
	/// If a declaration has !important
	Important,
	/// If a declaration used a css-wide keyword, e.g. `inherit` or `revert-layer`.
	CssWideKeywords,
	/// If a declaration is custom, e.g `--foo`
	Custom,
	/// If a declaration is computed-time, e.g. using `calc()` or `var()`
	Computed,
	/// If a declaration is shorthand
	Shorthands,
	/// If a declaration is longhand
	Longhands,
}

/// Categories of nodes present in metadata, used for selector filtering.
#[bitmask(u16)]
#[bitmask_config(vec_debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum NodeKinds {
	/// Contains unknown nodes
	Unknown,
	/// Contains style rules
	StyleRule,
	/// Contains at-rules (media, keyframes, etc.)
	AtRule,
	/// Contains Declarations
	Declaration,
	/// Contains function nodes
	Function,
	/// Node has an empty prelude
	EmptyPrelude,
	/// Node has an empty block (no declarations, no nested rules)
	EmptyBlock,
	/// Node is nested within another node
	Nested,
	/// Node is deprecated (non-conforming, obsolete)
	Deprecated,
	/// Node is experimental (not yet standardized)
	Experimental,
	/// Node is non-standard (vendor-specific, not in spec)
	NonStandard,
	/// Node is a dimension value (length, angle, time, flex, etc.)
	Dimension,
	/// Node is a custom element or custom property
	Custom,
}

/// Queryable properties a node exposes for selector matching.
/// Used by attribute selectors like `[name]` or `[name=value]`.
#[bitmask(u8)]
#[bitmask_config(vec_debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PropertyKind {
	/// Node has a queryable `name` property (declarations, named at-rules, functions)
	Name,
}

/// All PropertyKind variants for iteration.
pub const PROPERTY_KIND_VARIANTS: &[PropertyKind] = &[PropertyKind::Name];

/// OR-composable bitflag recording the set of CSS value types a substitution position accepts.
///
/// Used by [`Unresolved`](crate::Unresolved) to carry grammar-type knowledge at positions where a
/// substitution function appears but the slot cannot be fully typed at parse time.
///
/// `ANY` (all bits set) is used for `Custom` declaration bodies and substitution-function
/// internals where no type constraint applies.
#[bitmask(u32)]
#[bitmask_config(vec_debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExpectedTypes {
	Length,
	Percentage,
	Number,
	Integer,
	Angle,
	Time,
	Frequency,
	Flex,
	Color,
	Keyword,
	Image,
	Url,
	String,
}

impl ExpectedTypes {
	/// All bits set - use for untyped contexts (custom declarations, substitution internals).
	pub const ANY: ExpectedTypes = ExpectedTypes { bits: !0 };
}

/// Aggregated metadata computed from declarations within a block.
/// This allows efficient checking of what types of properties a block contains
/// without iterating through all declarations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CssMetadata {
	/// Bitwise OR of all PropertyGroup values
	pub property_groups: PropertyGroup,
	/// Bitwise OR of all AppliesTo values
	pub applies_to: AppliesTo,
	/// Bitwise OR of all BoxSide values
	pub box_sides: BoxSide,
	/// Bitwise OR of all BoxPortion values
	pub box_portions: BoxPortion,
	/// Bitwise OR of all DeclarationKind values
	pub declaration_kinds: DeclarationKind,
	/// Bitwise OR of all AtRuleIds in a Node
	pub used_at_rules: AtRuleId,
	/// Bitwise OR of all VendorPrefixes in a Node
	pub vendor_prefixes: VendorPrefixes,
	/// Bitwise OR of node categories present
	pub node_kinds: NodeKinds,
	/// Bitwise OR of queryable properties present
	pub property_kinds: PropertyKind,
	/// How unitless zero resolves in this context (Length or Number)
	pub unitless_zero_resolves: UnitlessZeroResolves,
	/// Size of vector-based nodes (e.g., number of declarations, selector list length)
	pub size: u16,
	/// True if any substitution function (var(), env(), attr(), etc.) or Unresolved node is present.
	/// Enables subtree-skip optimisations in visitors and the minifier.
	pub uses_substitution: bool,
	/// OR-union of all ExpectedTypes bits for substitution positions in this node.
	/// Accumulates upward through CssMetadata::merge for type inference.
	pub expected_types: ExpectedTypes,
}

impl Default for CssMetadata {
	fn default() -> Self {
		Self {
			property_groups: PropertyGroup::none(),
			applies_to: AppliesTo::none(),
			box_sides: BoxSide::none(),
			box_portions: BoxPortion::none(),
			declaration_kinds: DeclarationKind::none(),
			used_at_rules: AtRuleId::none(),
			vendor_prefixes: VendorPrefixes::none(),
			node_kinds: NodeKinds::none(),
			property_kinds: PropertyKind::none(),
			unitless_zero_resolves: UnitlessZeroResolves::default(),
			size: 0,
			uses_substitution: false,
			expected_types: ExpectedTypes::none(),
		}
	}
}

impl CssMetadata {
	/// Returns true if this metadata is empty (contains no properties or at-rules)
	#[inline]
	pub fn is_empty(&self) -> bool {
		self.property_groups == PropertyGroup::none()
			&& self.applies_to == AppliesTo::none()
			&& self.box_sides == BoxSide::none()
			&& self.box_portions == BoxPortion::none()
			&& self.declaration_kinds == DeclarationKind::none()
			&& self.used_at_rules == AtRuleId::none()
			&& self.vendor_prefixes == VendorPrefixes::none()
			&& self.node_kinds == NodeKinds::none()
			&& self.property_kinds == PropertyKind::none()
			&& self.unitless_zero_resolves == UnitlessZeroResolves::Length
			&& self.size == 0
			&& !self.uses_substitution
			&& self.expected_types == ExpectedTypes::none()
	}

	/// Returns true if this block modifies any positioning-related properties.
	#[inline]
	pub fn modifies_box(&self) -> bool {
		!self.box_portions.is_none()
	}

	/// Returns true if metadata contains important declarations.
	#[inline]
	pub fn has_important(&self) -> bool {
		self.declaration_kinds.contains(DeclarationKind::Important)
	}

	/// Returns true if metadata contains custom properties.
	#[inline]
	pub fn has_custom_properties(&self) -> bool {
		self.declaration_kinds.contains(DeclarationKind::Custom)
	}

	/// Returns true if metadata contains computed values.
	#[inline]
	pub fn has_computed(&self) -> bool {
		self.declaration_kinds.contains(DeclarationKind::Computed)
	}

	/// Returns true if metadata contains shorthand properties.
	#[inline]
	pub fn has_shorthands(&self) -> bool {
		self.declaration_kinds.contains(DeclarationKind::Shorthands)
	}

	/// Returns true if metadata contains longhand properties.
	#[inline]
	pub fn has_longhands(&self) -> bool {
		self.declaration_kinds.contains(DeclarationKind::Longhands)
	}

	/// Returns true if metadata contains unknown nodes.
	#[inline]
	pub fn has_unknown(&self) -> bool {
		self.node_kinds.contains(NodeKinds::Unknown)
	}

	/// Returns true if metadata contains vendor-prefixed properties.
	#[inline]
	pub fn has_vendor_prefixes(&self) -> bool {
		!self.vendor_prefixes.is_none()
	}

	/// Returns the vendor prefix if exactly one is present, None otherwise.
	#[inline]
	pub fn single_vendor_prefix(&self) -> Option<VendorPrefixes> {
		if self.vendor_prefixes.is_none() || self.vendor_prefixes.bits().count_ones() != 1 {
			None
		} else {
			Some(self.vendor_prefixes)
		}
	}

	/// Returns true if metadata contains any rule nodes.
	#[inline]
	pub fn has_rules(&self) -> bool {
		self.node_kinds.intersects(NodeKinds::StyleRule | NodeKinds::AtRule)
	}

	/// Returns true if metadata contains style rules.
	#[inline]
	pub fn has_style_rules(&self) -> bool {
		self.node_kinds.contains(NodeKinds::StyleRule)
	}

	/// Returns true if metadata contains at-rules.
	#[inline]
	pub fn has_at_rules(&self) -> bool {
		self.node_kinds.contains(NodeKinds::AtRule)
	}

	/// Returns true if metadata contains function nodes.
	#[inline]
	pub fn has_functions(&self) -> bool {
		self.node_kinds.contains(NodeKinds::Function)
	}

	/// Returns true if metadata contains deprecated nodes.
	#[inline]
	pub fn is_deprecated(&self) -> bool {
		self.node_kinds.contains(NodeKinds::Deprecated)
	}

	/// Returns true if metadata contains experimental nodes.
	#[inline]
	pub fn is_experimental(&self) -> bool {
		self.node_kinds.contains(NodeKinds::Experimental)
	}

	/// Returns true if metadata contains non-standard nodes.
	#[inline]
	pub fn is_non_standard(&self) -> bool {
		self.node_kinds.contains(NodeKinds::NonStandard)
	}

	/// Returns true if metadata contains dimension values.
	#[inline]
	pub fn is_dimension(&self) -> bool {
		self.node_kinds.contains(NodeKinds::Dimension)
	}

	/// Returns true if metadata contains nodes with the given property kind.
	#[inline]
	pub fn has_property_kind(&self, kind: PropertyKind) -> bool {
		self.property_kinds.contains(kind)
	}

	/// Returns true if any substitution function or Unresolved node is present in this subtree.
	#[inline]
	pub fn has_substitution(&self) -> bool {
		self.uses_substitution
	}

	/// Returns true if this is an empty container (no declarations, no nested rules).
	#[inline]
	pub fn is_empty_container(&self) -> bool {
		self.node_kinds.contains(NodeKinds::EmptyBlock)
	}

	/// Returns true if this node can be a container (has StyleRule or AtRule kind).
	#[inline]
	pub fn can_be_empty(&self) -> bool {
		self.node_kinds.intersects(NodeKinds::StyleRule | NodeKinds::AtRule)
	}
}

impl NodeMetadata for CssMetadata {
	#[inline]
	fn merge(mut self, other: Self) -> Self {
		self.property_groups |= other.property_groups;
		self.applies_to |= other.applies_to;
		self.box_sides |= other.box_sides;
		self.box_portions |= other.box_portions;
		self.declaration_kinds |= other.declaration_kinds;
		self.used_at_rules |= other.used_at_rules;
		self.vendor_prefixes |= other.vendor_prefixes;
		self.node_kinds |= other.node_kinds;
		self.property_kinds |= other.property_kinds;
		// For unitless_zero_resolves, we keep Number if either side has it (conservative)
		if other.unitless_zero_resolves == UnitlessZeroResolves::Number {
			self.unitless_zero_resolves = UnitlessZeroResolves::Number;
		}
		self.size = self.size.max(other.size);
		self.uses_substitution |= other.uses_substitution;
		self.expected_types |= other.expected_types;
		self
	}

	#[inline]
	fn with_size(mut self, size: u16) -> Self {
		self.size = size;
		self
	}
}

// Metadata is not serialized to tokens but providing these simplifies ToCursors/ToSpan impls
impl ToCursors for CssMetadata {
	fn to_cursors(&self, _: &mut impl css_parse::CursorSink) {}
}
impl ToSpan for CssMetadata {
	fn to_span(&self) -> Span {
		Span::DUMMY
	}
}

// ExpectedTypes is not serialized to tokens; these no-op impls let it sit as a
// non-node field on Unresolved under derive(ToCursors)/derive(ToSpan).
impl ToCursors for ExpectedTypes {
	fn to_cursors(&self, _: &mut impl css_parse::CursorSink) {}
}
impl ToSpan for ExpectedTypes {
	fn to_span(&self) -> Span {
		Span::DUMMY
	}
}
impl SemanticEq for ExpectedTypes {
	fn semantic_eq(&self, other: &Self) -> bool {
		self == other
	}
}

impl SemanticEq for CssMetadata {
	fn semantic_eq(&self, other: &Self) -> bool {
		self == other
	}
}

macro_rules! impl_token_metadata {
	($($token:tt),* $(,)?) => {
		$(
			impl css_parse::NodeWithMetadata<CssMetadata> for css_parse::T![$token] {
				fn metadata(&self) -> CssMetadata {
					CssMetadata::default()
				}
			}
		)*
	};
}

impl_token_metadata!(
	Ident,
	Number,
	Dimension,
	Hash,
	AtKeyword,
	String,
	Function,
	Url,
	Delim,
	Colon,
	Semicolon,
	Comma,
	LeftCurly,
	RightCurly,
	LeftSquare,
	RightSquare,
	LeftParen
);

// Delim subtypes (T![/] etc.) — defined by custom_delim! in css_parse, not covered by T![$token] expansion
macro_rules! impl_delim_metadata {
	($($t:ty),* $(,)?) => {
		$(
			impl css_parse::NodeWithMetadata<CssMetadata> for $t {
				fn metadata(&self) -> CssMetadata {
					CssMetadata::default()
				}
			}
		)*
	};
}
impl_delim_metadata!(
	css_parse::token_macros::delim::Slash,
	css_parse::token_macros::delim::Or,
	css_parse::token_macros::delim::Plus,
	css_parse::token_macros::delim::Tilde,
	css_parse::token_macros::delim::Star,
	css_parse::token_macros::delim::Question,
	css_parse::token_macros::delim::Underscore,
	css_parse::token_macros::delim::Eq,
	css_parse::token_macros::delim::Gt,
	css_parse::token_macros::delim::Lt,
	css_parse::token_macros::delim::Dot,
	css_parse::token_macros::delim::And,
	css_parse::token_macros::delim::At,
	css_parse::token_macros::delim::Caret,
	css_parse::token_macros::delim::Dash,
	css_parse::token_macros::delim::Dollar,
	css_parse::token_macros::delim::Bang,
	css_parse::token_macros::delim::Percent,
	css_parse::token_macros::delim::Hash,
	css_parse::token_macros::delim::Backtick,
);

impl css_parse::NodeWithMetadata<CssMetadata> for css_parse::token_macros::RightParen {
	fn metadata(&self) -> CssMetadata {
		CssMetadata::default()
	}
}

impl<'a, T: css_parse::NodeWithMetadata<CssMetadata>> css_parse::NodeWithMetadata<CssMetadata>
	for css_parse::Vec<'a, T>
{
	fn metadata(&self) -> CssMetadata {
		self.iter().fold(CssMetadata::default(), |acc, item| NodeMetadata::merge(acc, item.metadata()))
	}
}

impl<'a, T: css_parse::NodeWithMetadata<CssMetadata>, const MIN: usize> css_parse::NodeWithMetadata<CssMetadata>
	for css_parse::CommaSeparated<'a, T, MIN>
{
	fn metadata(&self) -> CssMetadata {
		self.into_iter().fold(CssMetadata::default(), |acc, (item, _comma)| NodeMetadata::merge(acc, item.metadata()))
	}
}

macro_rules! impl_optionals_metadata {
	($name:ident, $($T:ident => $v:ident),+) => {
		impl<$($T: css_parse::NodeWithMetadata<CssMetadata>),+>
			css_parse::NodeWithMetadata<CssMetadata> for css_parse::$name<$($T),+>
		{
			fn metadata(&self) -> CssMetadata {
				let css_parse::$name($($v),+) = self;
				let mut meta = CssMetadata::default();
				$(
					if let Some(val) = $v {
						meta = NodeMetadata::merge(meta, val.metadata());
					}
				)+
				meta
			}
		}
	};
}

impl_optionals_metadata!(Optionals2, A => a, B => b);
impl_optionals_metadata!(Optionals3, A => a, B => b, C => c);
impl_optionals_metadata!(Optionals4, A => a, B => b, C => c, D => d);
impl_optionals_metadata!(Optionals5, A => a, B => b, C => c, D => d, E => e);

macro_rules! impl_tuple_metadata {
	($($T:ident),+) => {
		impl<$($T: css_parse::NodeWithMetadata<CssMetadata>),+>
			css_parse::NodeWithMetadata<CssMetadata> for ($($T,)+)
		{
			#[allow(non_snake_case)]
			fn metadata(&self) -> CssMetadata {
				let ($($T,)+) = self;
				let mut meta = CssMetadata::default();
				$(
					meta = NodeMetadata::merge(meta, $T.metadata());
				)+
				meta
			}
		}
	};
}

impl_tuple_metadata!(A, B);
impl_tuple_metadata!(A, B, C);
impl_tuple_metadata!(A, B, C, D);
impl_tuple_metadata!(A, B, C, D, E);
impl_tuple_metadata!(A, B, C, D, E, F);
impl_tuple_metadata!(A, B, C, D, E, F, G);
impl_tuple_metadata!(A, B, C, D, E, F, G, H);

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{CssAtomSet, StyleSheet};
	use css_lexer::Lexer;
	use css_parse::{NodeMetadata, NodeWithMetadata, Parser};

	#[test]
	fn test_block_metadata_merge() {
		let meta1 = CssMetadata {
			property_groups: PropertyGroup::Color,
			declaration_kinds: DeclarationKind::Important,
			..Default::default()
		};

		let meta2 = CssMetadata {
			property_groups: PropertyGroup::Position,
			declaration_kinds: DeclarationKind::Custom,
			..Default::default()
		};

		let merged = meta1.merge(meta2);

		assert!(merged.property_groups.contains(PropertyGroup::Color));
		assert!(merged.property_groups.contains(PropertyGroup::Position));
		assert!(merged.declaration_kinds.contains(DeclarationKind::Important));
		assert!(merged.declaration_kinds.contains(DeclarationKind::Custom));
	}

	#[test]
	fn test_stylesheet_metadata_simple() {
		let css = "body { color: red; width: 100px; }";
		let bump = bumpalo::Bump::new();
		let lexer = Lexer::new(&CssAtomSet::ATOMS, css);
		let mut parser = Parser::new(&bump, css, lexer);
		let stylesheet = parser.parse::<StyleSheet>().unwrap();

		let metadata = stylesheet.metadata();

		assert!(metadata.property_groups.contains(PropertyGroup::Color));
		assert!(metadata.property_groups.contains(PropertyGroup::Sizing));
		assert!(metadata.modifies_box());
		assert!(metadata.has_longhands());
	}

	#[test]
	fn test_stylesheet_metadata_with_important() {
		let css = "body { color: red !important; }";
		let bump = bumpalo::Bump::new();
		let lexer = Lexer::new(&CssAtomSet::ATOMS, css);
		let mut parser = Parser::new(&bump, css, lexer);
		let stylesheet = parser.parse::<StyleSheet>().unwrap();

		let metadata = stylesheet.metadata();

		assert!(metadata.has_important());
		assert!(metadata.property_groups.contains(PropertyGroup::Color));
	}

	#[test]
	fn test_stylesheet_metadata_custom_properties() {
		let css = "body { --custom: value; }";
		let bump = bumpalo::Bump::new();
		let lexer = Lexer::new(&CssAtomSet::ATOMS, css);
		let mut parser = Parser::new(&bump, css, lexer);
		let stylesheet = parser.parse::<StyleSheet>().unwrap();

		let metadata = stylesheet.metadata();

		assert!(metadata.has_custom_properties());
	}

	#[test]
	fn test_stylesheet_metadata_nested_media() {
		let css = "@media screen { body { color: red; } }";
		let bump = bumpalo::Bump::new();
		let lexer = Lexer::new(&CssAtomSet::ATOMS, css);
		let mut parser = Parser::new(&bump, css, lexer);
		let stylesheet = parser.parse::<StyleSheet>().unwrap();

		let metadata = stylesheet.metadata();

		assert!(metadata.property_groups.contains(PropertyGroup::Color));
		assert!(metadata.used_at_rules.contains(AtRuleId::Media));
	}

	// Child leaf types carrying distinct node_kinds bits, used to verify delegation
	// propagates and merges children's metadata upward.
	#[derive(csskit_derives::NodeWithMetadata)]
	#[metadata(node_kinds = StyleRule)]
	struct ChildA;

	#[derive(csskit_derives::NodeWithMetadata)]
	#[metadata(node_kinds = AtRule)]
	struct ChildB;

	// Type-level delegate on a struct merges every field's metadata into self_metadata.
	#[derive(csskit_derives::NodeWithMetadata)]
	#[metadata(node_kinds = Function, delegate)]
	struct StructDelegate {
		a: ChildA,
		b: ChildB,
	}

	// Enum delegate over a named-field variant and a tuple variant.
	#[derive(csskit_derives::NodeWithMetadata)]
	#[metadata(delegate)]
	enum EnumDelegate {
		Named { a: ChildA, b: ChildB },
		Tuple(ChildA),
		Empty,
	}

	#[test]
	fn test_struct_type_level_delegate_merges_all_fields() {
		let node = StructDelegate { a: ChildA, b: ChildB };
		let meta = node.metadata();
		// self_metadata bit plus both children.
		assert!(meta.node_kinds.contains(NodeKinds::Function));
		assert!(meta.node_kinds.contains(NodeKinds::StyleRule));
		assert!(meta.node_kinds.contains(NodeKinds::AtRule));
	}

	#[test]
	fn test_enum_delegate_named_variant() {
		let meta = EnumDelegate::Named { a: ChildA, b: ChildB }.metadata();
		assert!(meta.node_kinds.contains(NodeKinds::StyleRule));
		assert!(meta.node_kinds.contains(NodeKinds::AtRule));
		assert!(!meta.node_kinds.contains(NodeKinds::Function));
	}

	#[test]
	fn test_enum_delegate_tuple_variant() {
		let meta = EnumDelegate::Tuple(ChildA).metadata();
		assert!(meta.node_kinds.contains(NodeKinds::StyleRule));
		assert!(!meta.node_kinds.contains(NodeKinds::AtRule));
	}

	#[test]
	fn test_enum_delegate_empty_variant() {
		let meta = EnumDelegate::Empty.metadata();
		assert!(meta.is_empty());
	}

	#[test]
	fn test_vendor_prefixes_try_from() {
		// Vendor-prefixed atoms should convert successfully
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_WebkitTransform), Ok(VendorPrefixes::WebKit));
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_WebkitAnimation), Ok(VendorPrefixes::WebKit));
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_WebkitLineClamp), Ok(VendorPrefixes::WebKit));

		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_MozAppearance), Ok(VendorPrefixes::Moz));
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_MozAny), Ok(VendorPrefixes::Moz));

		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_MsFullscreen), Ok(VendorPrefixes::Ms));
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_MsBackdrop), Ok(VendorPrefixes::Ms));

		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_OPlaceholder), Ok(VendorPrefixes::O));
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::_OScrollbar), Ok(VendorPrefixes::O));

		// Non-vendor atoms should fail
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::Px), Err(()));
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::Em), Err(()));
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::Auto), Err(()));
		assert_eq!(VendorPrefixes::try_from(CssAtomSet::Transform), Err(()));
	}

	#[test]
	fn size_baseline_css_metadata() {
		// S1 baseline: CssMetadata must stay <=48 bytes after adding uses_substitution + expected_types.
		assert!(std::mem::size_of::<CssMetadata>() <= 48, "CssMetadata size = {}", std::mem::size_of::<CssMetadata>());
	}

	#[test]
	fn test_substitution_fields_default() {
		let meta = CssMetadata::default();
		assert!(!meta.uses_substitution);
		assert_eq!(meta.expected_types, ExpectedTypes::none());
		assert!(meta.is_empty());
	}

	#[test]
	fn test_substitution_fields_merge() {
		let meta1 = CssMetadata {
			uses_substitution: true,
			expected_types: ExpectedTypes::Length | ExpectedTypes::Percentage,
			..Default::default()
		};

		let meta2 = CssMetadata { expected_types: ExpectedTypes::Color, ..Default::default() };

		let merged = NodeMetadata::merge(meta1, meta2);
		assert!(merged.uses_substitution);
		assert!(merged.expected_types.contains(ExpectedTypes::Length));
		assert!(merged.expected_types.contains(ExpectedTypes::Percentage));
		assert!(merged.expected_types.contains(ExpectedTypes::Color));
	}

	#[test]
	fn test_has_substitution() {
		let mut meta = CssMetadata::default();
		assert!(!meta.has_substitution());
		meta.uses_substitution = true;
		assert!(meta.has_substitution());
	}

	#[test]
	fn test_is_empty_with_substitution() {
		let mut meta = CssMetadata::default();
		assert!(meta.is_empty());
		meta.uses_substitution = true;
		assert!(!meta.is_empty());
		let meta2 = CssMetadata { expected_types: ExpectedTypes::Number, ..Default::default() };
		assert!(!meta2.is_empty());
	}
}