1use std::borrow::Cow;
4use std::ops::Range;
5
6use crate::context::{DeclarationContext, PropertyHandlerContext};
7use crate::error::{ParserError, PrinterError, PrinterErrorKind};
8use crate::parser::ParserOptions;
9use crate::properties::box_shadow::BoxShadowHandler;
10use crate::properties::custom::{CustomProperty, CustomPropertyName};
11use crate::properties::masking::MaskHandler;
12use crate::properties::text::{Direction, UnicodeBidi};
13use crate::properties::{
14 align::AlignHandler,
15 animation::AnimationHandler,
16 background::BackgroundHandler,
17 border::BorderHandler,
18 contain::ContainerHandler,
19 display::DisplayHandler,
20 flex::FlexHandler,
21 font::FontHandler,
22 grid::GridHandler,
23 list::ListStyleHandler,
24 margin_padding::*,
25 outline::OutlineHandler,
26 overflow::OverflowHandler,
27 position::PositionHandler,
28 prefix_handler::{FallbackHandler, PrefixHandler},
29 size::SizeHandler,
30 text::TextDecorationHandler,
31 transform::TransformHandler,
32 transition::TransitionHandler,
33 ui::ColorSchemeHandler,
34};
35use crate::properties::{Property, PropertyId};
36use crate::selector::SelectorList;
37use crate::traits::{PropertyHandler, ToCss};
38use crate::values::ident::DashedIdent;
39use crate::values::string::CowArcStr;
40#[cfg(feature = "visitor")]
41use crate::visitor::Visit;
42use cssparser::*;
43use indexmap::IndexMap;
44use smallvec::SmallVec;
45
46#[derive(Debug, PartialEq, Clone, Default)]
52#[cfg_attr(feature = "visitor", derive(Visit), visit(visit_declaration_block, PROPERTIES))]
53#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
54#[cfg_attr(
55 feature = "serde",
56 derive(serde::Serialize, serde::Deserialize),
57 serde(rename_all = "camelCase")
58)]
59#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
60pub struct DeclarationBlock<'i> {
61 #[cfg_attr(feature = "serde", serde(borrow, default))]
63 pub important_declarations: Vec<Property<'i>>,
64 #[cfg_attr(feature = "serde", serde(default))]
66 pub declarations: Vec<Property<'i>>,
67}
68
69impl<'i> DeclarationBlock<'i> {
70 pub fn parse<'a, 't>(
72 input: &mut Parser<'i, 't>,
73 options: &'a ParserOptions<'i>,
74 ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
75 let mut important_declarations = DeclarationList::new();
76 let mut declarations = DeclarationList::new();
77 let mut decl_parser = PropertyDeclarationParser {
78 important_declarations: &mut important_declarations,
79 declarations: &mut declarations,
80 options,
81 };
82 let mut parser = RuleBodyParser::new(input, &mut decl_parser);
83 while let Some(res) = parser.next() {
84 if let Err((err, _)) = res {
85 if options.error_recovery {
86 options.warn(err);
87 continue;
88 }
89 return Err(err);
90 }
91 }
92
93 Ok(DeclarationBlock {
94 important_declarations,
95 declarations,
96 })
97 }
98
99 pub fn parse_string<'o>(
101 input: &'i str,
102 options: ParserOptions<'i>,
103 ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
104 let mut input = ParserInput::new(input);
105 let mut parser = Parser::new(&mut input);
106 let result = Self::parse(&mut parser, &options)?;
107 parser.expect_exhausted()?;
108 Ok(result)
109 }
110
111 pub fn new() -> Self {
113 Self {
114 declarations: vec![],
115 important_declarations: vec![],
116 }
117 }
118
119 pub fn len(&self) -> usize {
121 self.declarations.len() + self.important_declarations.len()
122 }
123}
124
125impl<'i> ToCss for DeclarationBlock<'i> {
126 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
127 let len = self.declarations.len() + self.important_declarations.len();
128 let mut i = 0;
129
130 macro_rules! write {
131 ($decls: expr, $important: literal) => {
132 for decl in &$decls {
133 decl.to_css(dest, $important)?;
134 if i != len - 1 {
135 dest.write_char(';')?;
136 dest.whitespace()?;
137 }
138 i += 1;
139 }
140 };
141 }
142
143 write!(self.declarations, false);
144 write!(self.important_declarations, true);
145 Ok(())
146 }
147}
148
149impl<'i> DeclarationBlock<'i> {
150 pub fn to_css_block<PrinterT: crate::printer::PrinterTrait>(
152 &self,
153 dest: &mut PrinterT,
154 ) -> Result<(), PrinterError> {
155 dest.whitespace()?;
156 dest.write_char('{')?;
157 dest.indent();
158 dest.newline()?;
159
160 self.to_css_declarations(
161 dest,
162 false,
163 &rspack_lightningcss_selectors::SelectorList(SmallVec::new()),
164 0,
165 )?;
166
167 dest.dedent();
168 dest.newline()?;
169 dest.write_char('}')?;
170 Ok(())
171 }
172
173 pub(crate) fn has_printable_declarations(&self) -> bool {
174 if self.len() > 1 {
175 return true;
176 }
177
178 if self.declarations.len() == 1 {
179 !matches!(self.declarations[0], crate::properties::Property::Composes(_))
180 } else if self.important_declarations.len() == 1 {
181 !matches!(self.important_declarations[0], crate::properties::Property::Composes(_))
182 } else {
183 false
184 }
185 }
186
187 pub fn to_css_declarations<PrinterT: crate::printer::PrinterTrait>(
189 &self,
190 dest: &mut PrinterT,
191 has_nested_rules: bool,
192 selectors: &SelectorList,
193 source_index: u32,
194 ) -> Result<(), PrinterError> {
195 let mut i = 0;
196 let len = self.len();
197
198 macro_rules! write {
199 ($decls: expr, $important: literal) => {
200 for decl in &$decls {
201 if let crate::properties::Property::Composes(composes) = &decl {
204 if dest.is_nested() && dest.css_module_config().is_some() {
205 return Err(dest.error(PrinterErrorKind::InvalidComposesNesting, composes.loc));
206 }
207
208 if let Some(result) = dest
209 .with_css_module_mut(|css_module| css_module.handle_composes(&selectors, &composes, source_index))
210 {
211 result.map_err(|e| dest.error(e, composes.loc))?;
212 continue;
213 }
214 }
215
216 if i > 0 {
217 dest.newline()?;
218 }
219
220 decl.to_css(dest, $important)?;
221 if i != len - 1 || !dest.options().minify || has_nested_rules {
222 dest.write_char(';')?;
223 }
224
225 i += 1;
226 }
227 };
228 }
229
230 write!(self.declarations, false);
231 write!(self.important_declarations, true);
232 Ok(())
233 }
234}
235
236impl<'i> DeclarationBlock<'i> {
237 pub(crate) fn minify(
238 &mut self,
239 handler: &mut DeclarationHandler<'i>,
240 important_handler: &mut DeclarationHandler<'i>,
241 context: &mut PropertyHandlerContext<'i, '_>,
242 ) {
243 macro_rules! handle {
244 ($decls: expr, $handler: expr, $important: literal) => {
245 for decl in $decls.iter() {
246 context.is_important = $important;
247 let handled = $handler.handle_property(decl, context);
248
249 if !handled {
250 $handler.decls.push(decl.clone());
251 }
252 }
253 };
254 }
255
256 handle!(self.important_declarations, important_handler, true);
257 handle!(self.declarations, handler, false);
258
259 handler.finalize(context);
260 important_handler.finalize(context);
261 self.important_declarations = std::mem::take(&mut important_handler.decls);
262 self.declarations = std::mem::take(&mut handler.decls);
263 }
264
265 pub fn is_empty(&self) -> bool {
267 return self.declarations.is_empty() && self.important_declarations.is_empty();
268 }
269
270 pub(crate) fn property_location<'t>(
271 &self,
272 input: &mut Parser<'i, 't>,
273 index: usize,
274 ) -> Result<(Range<SourceLocation>, Range<SourceLocation>), ParseError<'i, ParserError<'i>>> {
275 for _ in 0..index {
277 input.expect_ident()?;
278 input.expect_colon()?;
279 input.parse_until_after(Delimiter::Semicolon, |parser| {
280 while parser.next().is_ok() {}
281 Ok(())
282 })?;
283 }
284
285 input.skip_whitespace();
287 let key_start = input.current_source_location();
288 input.expect_ident()?;
289 let key_end = input.current_source_location();
290 let key_range = key_start..key_end;
291
292 input.expect_colon()?;
293 input.skip_whitespace();
294
295 let val_start = input.current_source_location();
297 input.parse_until_before(Delimiter::Semicolon, |parser| {
298 while parser.next().is_ok() {}
299 Ok(())
300 })?;
301 let val_end = input.current_source_location();
302 let val_range = val_start..val_end;
303
304 Ok((key_range, val_range))
305 }
306}
307
308impl<'i> DeclarationBlock<'i> {
309 pub fn iter(&self) -> impl std::iter::DoubleEndedIterator<Item = (&Property<'i>, bool)> {
311 self
312 .declarations
313 .iter()
314 .map(|property| (property, false))
315 .chain(self.important_declarations.iter().map(|property| (property, true)))
316 }
317
318 pub fn iter_mut(&mut self) -> impl std::iter::DoubleEndedIterator<Item = &mut Property<'i>> {
320 self.declarations.iter_mut().chain(self.important_declarations.iter_mut())
321 }
322
323 pub fn get<'a>(&'a self, property_id: &PropertyId) -> Option<(Cow<'a, Property<'i>>, bool)> {
329 if property_id.is_shorthand() {
330 if let Some((shorthand, important)) = property_id.shorthand_value(&self) {
331 return Some((Cow::Owned(shorthand), important));
332 }
333 } else {
334 for (property, important) in self.iter().rev() {
335 if property.property_id() == *property_id {
336 return Some((Cow::Borrowed(property), important));
337 }
338
339 if let Some(val) = property.longhand(&property_id) {
340 return Some((Cow::Owned(val), important));
341 }
342 }
343 }
344
345 None
346 }
347
348 pub fn set(&mut self, property: Property<'i>, important: bool) {
354 let property_id = property.property_id();
355 let declarations = if important {
356 self.declarations.retain(|decl| decl.property_id() != property_id);
358 &mut self.important_declarations
359 } else {
360 self.important_declarations.retain(|decl| decl.property_id() != property_id);
362 &mut self.declarations
363 };
364
365 let longhands = property_id.longhands().unwrap_or_else(|| vec![property.property_id()]);
366
367 for decl in declarations.iter_mut().rev() {
368 {
369 let id = decl.property_id();
373 let id_longhands = id.longhands().unwrap_or_else(|| vec![id]);
374 if longhands.iter().any(|longhand| {
375 let logical_group = longhand.logical_group();
376 let category = longhand.category();
377
378 logical_group.is_some()
379 && id_longhands.iter().any(|id_longhand| {
380 logical_group == id_longhand.logical_group() && category != id_longhand.category()
381 })
382 }) {
383 break;
384 }
385 }
386
387 if decl.property_id() == property_id {
388 *decl = property;
389 return;
390 }
391
392 if decl.set_longhand(&property).is_ok() {
394 return;
395 }
396 }
397
398 declarations.push(property)
399 }
400
401 pub fn remove(&mut self, property_id: &PropertyId) {
407 fn remove<'i, 'a>(declarations: &mut Vec<Property<'i>>, property_id: &PropertyId<'a>) {
408 let longhands = property_id.longhands().unwrap_or(vec![]);
409 let mut i = 0;
410 while i < declarations.len() {
411 let replacement = {
412 let property = &declarations[i];
413 let id = property.property_id();
414 if id == *property_id || longhands.contains(&id) {
415 None
418 } else if longhands.is_empty() && id.longhands().unwrap_or(vec![]).contains(&property_id) {
419 Some(
422 id.longhands()
423 .unwrap()
424 .iter()
425 .filter_map(|longhand| {
426 if *longhand == *property_id {
427 None
428 } else {
429 property.longhand(longhand)
430 }
431 })
432 .collect::<Vec<Property>>(),
433 )
434 } else {
435 i += 1;
436 continue;
437 }
438 };
439
440 match replacement {
441 Some(properties) => {
442 let count = properties.len();
443 declarations.splice(i..i + 1, properties);
444 i += count;
445 }
446 None => {
447 declarations.remove(i);
448 }
449 }
450 }
451 }
452
453 remove(&mut self.declarations, property_id);
454 remove(&mut self.important_declarations, property_id);
455 }
456}
457
458struct PropertyDeclarationParser<'a, 'i> {
459 important_declarations: &'a mut Vec<Property<'i>>,
460 declarations: &'a mut Vec<Property<'i>>,
461 options: &'a ParserOptions<'i>,
462}
463
464impl<'a, 'i> cssparser::DeclarationParser<'i> for PropertyDeclarationParser<'a, 'i> {
466 type Declaration = ();
467 type Error = ParserError<'i>;
468
469 fn parse_value<'t>(
470 &mut self,
471 name: CowRcStr<'i>,
472 input: &mut cssparser::Parser<'i, 't>,
473 _declaration_start: &ParserState,
474 ) -> Result<Self::Declaration, cssparser::ParseError<'i, Self::Error>> {
475 parse_declaration(
476 name,
477 input,
478 &mut self.declarations,
479 &mut self.important_declarations,
480 &self.options,
481 )
482 }
483}
484
485impl<'a, 'i> AtRuleParser<'i> for PropertyDeclarationParser<'a, 'i> {
487 type Prelude = ();
488 type AtRule = ();
489 type Error = ParserError<'i>;
490}
491
492impl<'a, 'i> QualifiedRuleParser<'i> for PropertyDeclarationParser<'a, 'i> {
493 type Prelude = ();
494 type QualifiedRule = ();
495 type Error = ParserError<'i>;
496}
497
498impl<'a, 'i> RuleBodyItemParser<'i, (), ParserError<'i>> for PropertyDeclarationParser<'a, 'i> {
499 fn parse_qualified(&self) -> bool {
500 false
501 }
502
503 fn parse_declarations(&self) -> bool {
504 true
505 }
506}
507
508pub(crate) fn parse_declaration<'i, 't>(
509 name: CowRcStr<'i>,
510 input: &mut cssparser::Parser<'i, 't>,
511 declarations: &mut DeclarationList<'i>,
512 important_declarations: &mut DeclarationList<'i>,
513 options: &ParserOptions<'i>,
514) -> Result<(), cssparser::ParseError<'i, ParserError<'i>>> {
515 let property_id = PropertyId::from(CowArcStr::from(name));
519 let mut delimiters = Delimiter::Bang;
520 if !matches!(property_id, PropertyId::Custom(CustomPropertyName::Custom(..))) {
521 delimiters = delimiters | Delimiter::CurlyBracketBlock;
522 }
523 let property = input.parse_until_before(delimiters, |input| Property::parse(property_id, input, options))?;
524 let important = input
525 .try_parse(|input| {
526 input.expect_delim('!')?;
527 input.expect_ident_matching("important")
528 })
529 .is_ok();
530 input.expect_exhausted()?;
531 if important {
532 important_declarations.push(property);
533 } else {
534 declarations.push(property);
535 }
536 Ok(())
537}
538
539pub(crate) type DeclarationList<'i> = Vec<Property<'i>>;
540
541#[derive(Default)]
542pub(crate) struct DeclarationHandler<'i> {
543 background: BackgroundHandler<'i>,
544 border: BorderHandler<'i>,
545 outline: OutlineHandler,
546 flex: FlexHandler,
547 grid: GridHandler<'i>,
548 align: AlignHandler,
549 size: SizeHandler,
550 margin: MarginHandler<'i>,
551 padding: PaddingHandler<'i>,
552 scroll_margin: ScrollMarginHandler<'i>,
553 scroll_padding: ScrollPaddingHandler<'i>,
554 font: FontHandler<'i>,
555 text: TextDecorationHandler<'i>,
556 list: ListStyleHandler<'i>,
557 transition: TransitionHandler<'i>,
558 animation: AnimationHandler<'i>,
559 display: DisplayHandler<'i>,
560 position: PositionHandler,
561 inset: InsetHandler<'i>,
562 overflow: OverflowHandler,
563 transform: TransformHandler,
564 box_shadow: BoxShadowHandler,
565 mask: MaskHandler<'i>,
566 container: ContainerHandler<'i>,
567 color_scheme: ColorSchemeHandler,
568 fallback: FallbackHandler,
569 prefix: PrefixHandler,
570 direction: Option<Direction>,
571 unicode_bidi: Option<UnicodeBidi>,
572 custom_properties: IndexMap<DashedIdent<'i>, usize>,
573 decls: DeclarationList<'i>,
574}
575
576impl<'i> DeclarationHandler<'i> {
577 pub fn handle_property(
578 &mut self,
579 property: &Property<'i>,
580 context: &mut PropertyHandlerContext<'i, '_>,
581 ) -> bool {
582 self.background.handle_property(property, &mut self.decls, context)
583 || self.border.handle_property(property, &mut self.decls, context)
584 || self.outline.handle_property(property, &mut self.decls, context)
585 || self.flex.handle_property(property, &mut self.decls, context)
586 || self.grid.handle_property(property, &mut self.decls, context)
587 || self.align.handle_property(property, &mut self.decls, context)
588 || self.size.handle_property(property, &mut self.decls, context)
589 || self.margin.handle_property(property, &mut self.decls, context)
590 || self.padding.handle_property(property, &mut self.decls, context)
591 || self.scroll_margin.handle_property(property, &mut self.decls, context)
592 || self.scroll_padding.handle_property(property, &mut self.decls, context)
593 || self.font.handle_property(property, &mut self.decls, context)
594 || self.text.handle_property(property, &mut self.decls, context)
595 || self.list.handle_property(property, &mut self.decls, context)
596 || self.transition.handle_property(property, &mut self.decls, context)
597 || self.animation.handle_property(property, &mut self.decls, context)
598 || self.display.handle_property(property, &mut self.decls, context)
599 || self.position.handle_property(property, &mut self.decls, context)
600 || self.inset.handle_property(property, &mut self.decls, context)
601 || self.overflow.handle_property(property, &mut self.decls, context)
602 || self.transform.handle_property(property, &mut self.decls, context)
603 || self.box_shadow.handle_property(property, &mut self.decls, context)
604 || self.mask.handle_property(property, &mut self.decls, context)
605 || self.container.handle_property(property, &mut self.decls, context)
606 || self.color_scheme.handle_property(property, &mut self.decls, context)
607 || self.fallback.handle_property(property, &mut self.decls, context)
608 || self.prefix.handle_property(property, &mut self.decls, context)
609 || self.handle_all(property)
610 || self.handle_custom_property(property, context)
611 }
612
613 fn handle_custom_property(
614 &mut self,
615 property: &Property<'i>,
616 context: &mut PropertyHandlerContext<'i, '_>,
617 ) -> bool {
618 if let Property::Custom(custom) = property {
619 if context.unused_symbols.contains(custom.name.as_ref()) {
620 return true;
621 }
622
623 if let CustomPropertyName::Custom(name) = &custom.name {
624 if let Some(index) = self.custom_properties.get(name) {
625 if self.decls[*index] == *property {
626 return true;
627 }
628 let mut custom = custom.clone();
629 self.add_conditional_fallbacks(&mut custom, context);
630 self.decls[*index] = Property::Custom(custom);
631 } else {
632 self.custom_properties.insert(name.clone(), self.decls.len());
633 let mut custom = custom.clone();
634 self.add_conditional_fallbacks(&mut custom, context);
635 self.decls.push(Property::Custom(custom));
636 }
637
638 return true;
639 }
640 }
641
642 false
643 }
644
645 fn handle_all(&mut self, property: &Property<'i>) -> bool {
646 match property {
649 Property::UnicodeBidi(bidi) => {
650 self.unicode_bidi = Some(*bidi);
651 true
652 }
653 Property::Direction(direction) => {
654 self.direction = Some(*direction);
655 true
656 }
657 Property::All(keyword) => {
658 let mut handler = DeclarationHandler {
659 unicode_bidi: self.unicode_bidi.clone(),
660 direction: self.direction.clone(),
661 ..Default::default()
662 };
663 for (key, index) in self.custom_properties.drain(..) {
664 handler.custom_properties.insert(key, handler.decls.len());
665 handler.decls.push(self.decls[index].clone());
666 }
667 handler.decls.push(Property::All(keyword.clone()));
668 *self = handler;
669 true
670 }
671 _ => false,
672 }
673 }
674
675 fn add_conditional_fallbacks(
676 &self,
677 custom: &mut CustomProperty<'i>,
678 context: &mut PropertyHandlerContext<'i, '_>,
679 ) {
680 if context.context != DeclarationContext::Keyframes {
681 let fallbacks = custom.value.get_fallbacks(context.targets);
682 for (condition, fallback) in fallbacks {
683 context.add_conditional_property(
684 condition,
685 Property::Custom(CustomProperty {
686 name: custom.name.clone(),
687 value: fallback,
688 }),
689 );
690 }
691 }
692 }
693
694 pub fn finalize(&mut self, context: &mut PropertyHandlerContext<'i, '_>) {
695 if let Some(direction) = std::mem::take(&mut self.direction) {
696 self.decls.push(Property::Direction(direction));
697 }
698 if let Some(unicode_bidi) = std::mem::take(&mut self.unicode_bidi) {
699 self.decls.push(Property::UnicodeBidi(unicode_bidi));
700 }
701
702 self.background.finalize(&mut self.decls, context);
703 self.border.finalize(&mut self.decls, context);
704 self.outline.finalize(&mut self.decls, context);
705 self.flex.finalize(&mut self.decls, context);
706 self.grid.finalize(&mut self.decls, context);
707 self.align.finalize(&mut self.decls, context);
708 self.size.finalize(&mut self.decls, context);
709 self.margin.finalize(&mut self.decls, context);
710 self.padding.finalize(&mut self.decls, context);
711 self.scroll_margin.finalize(&mut self.decls, context);
712 self.scroll_padding.finalize(&mut self.decls, context);
713 self.font.finalize(&mut self.decls, context);
714 self.text.finalize(&mut self.decls, context);
715 self.list.finalize(&mut self.decls, context);
716 self.transition.finalize(&mut self.decls, context);
717 self.animation.finalize(&mut self.decls, context);
718 self.display.finalize(&mut self.decls, context);
719 self.position.finalize(&mut self.decls, context);
720 self.inset.finalize(&mut self.decls, context);
721 self.overflow.finalize(&mut self.decls, context);
722 self.transform.finalize(&mut self.decls, context);
723 self.box_shadow.finalize(&mut self.decls, context);
724 self.mask.finalize(&mut self.decls, context);
725 self.container.finalize(&mut self.decls, context);
726 self.color_scheme.finalize(&mut self.decls, context);
727 self.fallback.finalize(&mut self.decls, context);
728 self.prefix.finalize(&mut self.decls, context);
729 self.custom_properties.clear();
730 }
731}