1use crate::css_modules::CssModule;
4use crate::dependencies::{Dependency, DependencyOptions};
5use crate::error::{Error, ErrorLocation, PrinterError, PrinterErrorKind};
6use crate::rules::{Location, StyleContextPtr};
7use crate::targets::{Targets, TargetsWithSupportsScope};
8use crate::vendor_prefix::VendorPrefix;
9use cssparser::{serialize_identifier, serialize_name};
10#[cfg(feature = "sourcemap")]
11use parcel_sourcemap::SourceMap as ParcelSourceMap;
12#[cfg(feature = "custom_sourcemap")]
13use rustc_hash::FxHashSet;
14#[cfg(not(feature = "custom_sourcemap"))]
15use std::marker::PhantomData;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct OriginalLocation {
20 pub original_line: u32,
22 pub original_column: u32,
24 pub source: u32,
26 pub name: Option<u32>,
28}
29
30#[cfg(feature = "custom_sourcemap")]
33pub trait SourceMap {
34 fn add_source(&mut self, source: &str) -> u32;
36
37 fn add_name(&mut self, name: &str) -> u32;
39
40 fn set_source_content(&mut self, source_index: u32, source_content: &str);
42
43 fn add_mapping(&mut self, generated_line: u32, generated_column: u32, original: Option<OriginalLocation>);
45
46 fn from_data_url(source_root: &str, data_url: &str) -> Option<Self>
48 where
49 Self: Sized;
50
51 fn find_closest_mapping(&mut self, line: u32, column: u32) -> Option<OriginalLocation>;
53
54 fn get_source(&self, source_index: u32) -> Option<&str>;
56
57 fn get_name(&self, name_index: u32) -> Option<&str>;
59
60 fn get_source_content(&self, source_index: u32) -> Option<&str>;
62}
63
64#[cfg(not(feature = "custom_sourcemap"))]
66pub trait SourceMap {}
67
68#[cfg(not(feature = "custom_sourcemap"))]
69impl SourceMap for () {}
70
71#[cfg(feature = "custom_sourcemap")]
72impl SourceMap for () {
73 fn add_source(&mut self, _source: &str) -> u32 {
74 unreachable!()
75 }
76
77 fn add_name(&mut self, _name: &str) -> u32 {
78 unreachable!()
79 }
80
81 fn set_source_content(&mut self, _source_index: u32, _source_content: &str) {
82 unreachable!()
83 }
84
85 fn add_mapping(&mut self, _generated_line: u32, _generated_column: u32, _original: Option<OriginalLocation>) {
86 unreachable!()
87 }
88
89 fn from_data_url(_source_root: &str, _data_url: &str) -> Option<Self> {
90 unreachable!()
91 }
92
93 fn find_closest_mapping(&mut self, _line: u32, _column: u32) -> Option<OriginalLocation> {
94 unreachable!()
95 }
96
97 fn get_source(&self, _source_index: u32) -> Option<&str> {
98 unreachable!()
99 }
100
101 fn get_name(&self, _name_index: u32) -> Option<&str> {
102 unreachable!()
103 }
104
105 fn get_source_content(&self, _source_index: u32) -> Option<&str> {
106 unreachable!()
107 }
108}
109
110#[cfg(feature = "custom_sourcemap")]
111impl<T: SourceMap + ?Sized> SourceMap for &mut T {
112 fn add_source(&mut self, source: &str) -> u32 {
113 (**self).add_source(source)
114 }
115
116 fn add_name(&mut self, name: &str) -> u32 {
117 (**self).add_name(name)
118 }
119
120 fn set_source_content(&mut self, source_index: u32, source_content: &str) {
121 (**self).set_source_content(source_index, source_content)
122 }
123
124 fn add_mapping(&mut self, generated_line: u32, generated_column: u32, original: Option<OriginalLocation>) {
125 (**self).add_mapping(generated_line, generated_column, original)
126 }
127
128 fn from_data_url(source_root: &str, data_url: &str) -> Option<Self>
129 where
130 Self: Sized,
131 {
132 let _ = (source_root, data_url);
133 None
134 }
135
136 fn find_closest_mapping(&mut self, line: u32, column: u32) -> Option<OriginalLocation> {
137 (**self).find_closest_mapping(line, column)
138 }
139
140 fn get_source(&self, source_index: u32) -> Option<&str> {
141 (**self).get_source(source_index)
142 }
143
144 fn get_name(&self, name_index: u32) -> Option<&str> {
145 (**self).get_name(name_index)
146 }
147
148 fn get_source_content(&self, source_index: u32) -> Option<&str> {
149 (**self).get_source_content(source_index)
150 }
151}
152
153#[cfg(feature = "sourcemap")]
154#[cfg_attr(docsrs, doc(cfg(feature = "sourcemap")))]
155impl SourceMap for ParcelSourceMap {
156 fn add_source(&mut self, source: &str) -> u32 {
157 ParcelSourceMap::add_source(self, source)
158 }
159
160 fn add_name(&mut self, name: &str) -> u32 {
161 ParcelSourceMap::add_name(self, name)
162 }
163
164 fn set_source_content(&mut self, source_index: u32, source_content: &str) {
165 let _ = ParcelSourceMap::set_source_content(self, source_index as usize, source_content);
166 }
167
168 fn add_mapping(&mut self, generated_line: u32, generated_column: u32, original: Option<OriginalLocation>) {
169 ParcelSourceMap::add_mapping(
170 self,
171 generated_line,
172 generated_column,
173 original.map(|original| parcel_sourcemap::OriginalLocation {
174 original_line: original.original_line,
175 original_column: original.original_column,
176 source: original.source,
177 name: original.name,
178 }),
179 );
180 }
181
182 fn from_data_url(source_root: &str, data_url: &str) -> Option<Self> {
183 ParcelSourceMap::from_data_url(source_root, data_url).ok()
184 }
185
186 fn find_closest_mapping(&mut self, line: u32, column: u32) -> Option<OriginalLocation> {
187 let mapping = ParcelSourceMap::find_closest_mapping(self, line, column)?;
188 mapping.original.map(|original| OriginalLocation {
189 original_line: original.original_line,
190 original_column: original.original_column,
191 source: original.source,
192 name: original.name,
193 })
194 }
195
196 fn get_source(&self, source_index: u32) -> Option<&str> {
197 ParcelSourceMap::get_source(self, source_index).ok()
198 }
199
200 fn get_name(&self, name_index: u32) -> Option<&str> {
201 ParcelSourceMap::get_name(self, name_index).ok()
202 }
203
204 fn get_source_content(&self, source_index: u32) -> Option<&str> {
205 ParcelSourceMap::get_source_content(self, source_index).ok()
206 }
207}
208
209pub struct PrinterOptions<'a> {
211 pub minify: bool,
213 pub project_root: Option<&'a str>,
215 pub targets: Targets,
217 pub analyze_dependencies: Option<DependencyOptions>,
225 pub pseudo_classes: Option<PseudoClasses<'a>>,
228}
229
230impl<'a> Default for PrinterOptions<'a> {
231 fn default() -> Self {
232 PrinterOptions {
233 minify: false,
234 project_root: None,
235 targets: Targets::default(),
236 analyze_dependencies: None,
237 pseudo_classes: None,
238 }
239 }
240}
241
242#[allow(missing_docs)]
243pub struct PrinterState<'a, 'c> {
244 pub(crate) loc: Location,
245 pub(crate) generated_line: u32,
246 pub(crate) generated_col: u32,
247 pub(crate) indent: u8,
248 pub(crate) targets: TargetsWithSupportsScope,
249 pub(crate) vendor_prefix: VendorPrefix,
250 pub(crate) in_calc: bool,
251 pub(crate) css_module: Option<CssModule<'a, 'c>>,
252 pub(crate) dependencies: Option<Vec<Dependency>>,
253 pub(crate) remove_imports: bool,
254 pub(crate) context: Option<StyleContextPtr>,
255}
256
257#[derive(Default, Debug)]
261pub struct PseudoClasses<'a> {
262 pub hover: Option<&'a str>,
264 pub active: Option<&'a str>,
266 pub focus: Option<&'a str>,
268 pub focus_visible: Option<&'a str>,
270 pub focus_within: Option<&'a str>,
272}
273
274pub struct Printer<'a, 'c, W, S: SourceMap = ()> {
284 pub(crate) sources: Option<&'c Vec<String>>,
285 dest: &'a mut W,
286 pub(crate) options: PrinterOptions<'a>,
287 pub(crate) state: PrinterState<'a, 'c>,
288 #[cfg(feature = "custom_sourcemap")]
289 pub(crate) source_map: Option<&'a mut S>,
290 #[cfg(feature = "custom_sourcemap")]
291 pub(crate) source_maps: Vec<Option<S>>,
292 #[cfg(feature = "custom_sourcemap")]
293 pub(crate) source_map_source_indices: &'c [Option<u32>],
294 #[cfg(feature = "custom_sourcemap")]
295 sources_with_content: FxHashSet<u32>,
296 #[cfg(not(feature = "custom_sourcemap"))]
297 source_map: PhantomData<fn() -> S>,
298}
299
300impl<'a, 'c, W: std::fmt::Write + Sized> Printer<'a, 'c, W, ()> {
301 pub fn new(dest: &'a mut W, options: PrinterOptions<'a>) -> Self {
303 Self::new_impl(dest, options)
304 }
305}
306
307impl<'a, 'c, W: std::fmt::Write + Sized, S: SourceMap> Printer<'a, 'c, W, S> {
308 fn new_impl(dest: &'a mut W, options: PrinterOptions<'a>) -> Self {
309 let dependencies = if options.analyze_dependencies.is_some() {
310 Some(Vec::new())
311 } else {
312 None
313 };
314 let remove_imports = matches!(&options.analyze_dependencies, Some(d) if d.remove_imports);
315 Printer {
316 sources: None,
317 dest,
318 #[cfg(feature = "custom_sourcemap")]
319 source_map: None,
320 state: PrinterState {
321 loc: Location {
322 source_index: 0,
323 line: 0,
324 column: 1,
325 },
326 generated_line: 0,
327 generated_col: 0,
328 indent: 0,
329 targets: TargetsWithSupportsScope::new(options.targets),
330 vendor_prefix: VendorPrefix::empty(),
331 in_calc: false,
332 css_module: None,
333 dependencies,
334 remove_imports,
335 context: None,
336 },
337 options,
338 #[cfg(feature = "custom_sourcemap")]
339 source_maps: Vec::new(),
340 #[cfg(feature = "custom_sourcemap")]
341 source_map_source_indices: &[],
342 #[cfg(feature = "custom_sourcemap")]
343 sources_with_content: FxHashSet::default(),
344 #[cfg(not(feature = "custom_sourcemap"))]
345 source_map: PhantomData,
346 }
347 }
348
349 #[cfg(feature = "custom_sourcemap")]
350 pub fn with_source_map<T: SourceMap>(self, source_map: Option<&'a mut T>) -> Printer<'a, 'c, W, T> {
352 Printer {
353 sources: self.sources,
354 dest: self.dest,
355 options: self.options,
356 state: self.state,
357 source_map,
358 source_maps: Vec::new(),
359 source_map_source_indices: &[],
360 sources_with_content: FxHashSet::default(),
361 }
362 }
363
364 pub fn filename(&self) -> &'c str {
366 if let Some(sources) = self.sources {
367 if let Some(f) = sources.get(self.state.loc.source_index as usize) {
368 f
369 } else {
370 "unknown.css"
371 }
372 } else {
373 "unknown.css"
374 }
375 }
376
377 pub fn write_str(&mut self, s: &str) -> Result<(), PrinterError> {
382 self.state.generated_col += s.len() as u32;
383 self.dest.write_str(s)?;
384 Ok(())
385 }
386
387 pub fn write_str_with_newlines(&mut self, s: &str) -> Result<(), PrinterError> {
389 let mut last_line_start: usize = 0;
390
391 for (idx, n) in s.char_indices() {
392 if n == '\n' {
393 self.state.generated_line += 1;
394 self.state.generated_col = 0;
395
396 last_line_start = idx + 1;
398 }
399 }
400
401 self.state.generated_col += (s.len() - last_line_start) as u32;
402 self.dest.write_str(s)?;
403 Ok(())
404 }
405
406 pub fn write_char(&mut self, c: char) -> Result<(), PrinterError> {
408 if c == '\n' {
409 self.state.generated_line += 1;
410 self.state.generated_col = 0;
411 } else {
412 self.state.generated_col += 1;
413 }
414 self.dest.write_char(c)?;
415 Ok(())
416 }
417
418 pub fn whitespace(&mut self) -> Result<(), PrinterError> {
423 if self.options.minify {
424 return Ok(());
425 }
426
427 self.write_char(' ')
428 }
429
430 pub fn delim(&mut self, delim: char, ws_before: bool) -> Result<(), PrinterError> {
433 if ws_before {
434 self.whitespace()?;
435 }
436 self.write_char(delim)?;
437 self.whitespace()
438 }
439
440 pub fn newline(&mut self) -> Result<(), PrinterError> {
443 if self.options.minify {
444 return Ok(());
445 }
446
447 self.write_char('\n')?;
448 if self.state.indent > 0 {
449 self.write_str(&" ".repeat(self.state.indent as usize))?;
450 }
451
452 Ok(())
453 }
454
455 pub fn indent(&mut self) {
457 self.state.indent += 2;
458 }
459
460 pub fn dedent(&mut self) {
462 self.state.indent -= 2;
463 }
464
465 pub fn indent_by(&mut self, amt: u8) {
467 self.state.indent += amt;
468 }
469
470 pub fn dedent_by(&mut self, amt: u8) {
472 self.state.indent -= amt;
473 }
474
475 pub fn is_nested(&self) -> bool {
477 self.state.indent > 2
478 }
479
480 pub fn write_ident(&mut self, ident: &str, handle_css_module: bool) -> Result<(), PrinterError> {
484 if handle_css_module {
485 if let Some(css_module) = &mut self.state.css_module {
486 let dest = &mut self.dest;
487 let mut first = true;
488 css_module.config.pattern.write(
489 &css_module.hashes[self.state.loc.source_index as usize],
490 &css_module.sources[self.state.loc.source_index as usize],
491 ident,
492 if let Some(content_hashes) = &css_module.content_hashes {
493 &content_hashes[self.state.loc.source_index as usize]
494 } else {
495 ""
496 },
497 |s| {
498 self.state.generated_col += s.len() as u32;
499 if first {
500 first = false;
501 serialize_identifier(s, dest)
502 } else {
503 serialize_name(s, dest)
504 }
505 },
506 )?;
507
508 css_module.add_local(&ident, &ident, self.state.loc.source_index);
509 return Ok(());
510 }
511 }
512
513 serialize_identifier(ident, self)?;
514 Ok(())
515 }
516
517 pub(crate) fn write_dashed_ident(&mut self, ident: &str, is_declaration: bool) -> Result<(), PrinterError> {
518 self.write_str("--")?;
519
520 match &mut self.state.css_module {
521 Some(css_module) if css_module.config.dashed_idents => {
522 let dest = &mut self.dest;
523 css_module.config.pattern.write(
524 &css_module.hashes[self.state.loc.source_index as usize],
525 &css_module.sources[self.state.loc.source_index as usize],
526 &ident[2..],
527 if let Some(content_hashes) = &css_module.content_hashes {
528 &content_hashes[self.state.loc.source_index as usize]
529 } else {
530 ""
531 },
532 |s| {
533 self.state.generated_col += s.len() as u32;
534 serialize_name(s, dest)
535 },
536 )?;
537
538 if is_declaration {
539 css_module.add_dashed(ident, self.state.loc.source_index);
540 }
541 }
542 _ => {
543 serialize_name(&ident[2..], self)?;
544 }
545 }
546
547 Ok(())
548 }
549
550 pub fn error(&self, kind: PrinterErrorKind, loc: crate::dependencies::Location) -> Error<PrinterErrorKind> {
552 Error {
553 kind,
554 loc: Some(ErrorLocation {
555 filename: self.filename().into(),
556 line: loc.line - 1,
557 column: loc.column,
558 }),
559 }
560 }
561
562 pub(crate) fn take_dependencies(&mut self) -> Option<Vec<Dependency>> {
563 self.state.dependencies.take()
564 }
565
566 pub fn add_mapping(&mut self, loc: Location) {
568 self.state.loc = loc;
569
570 #[cfg(feature = "custom_sourcemap")]
571 if let Some(map) = &mut self.source_map {
572 #[cfg_attr(not(feature = "sourcemap"), allow(unused_mut))]
573 let mut original = OriginalLocation {
574 original_line: loc.line,
575 original_column: loc.column - 1,
576 source: self
577 .source_map_source_indices
578 .get(loc.source_index as usize)
579 .copied()
580 .flatten()
581 .unwrap_or(loc.source_index),
582 name: None,
583 };
584
585 if let Some(Some(sm)) = self.source_maps.get_mut(loc.source_index as usize) {
587 let mut found_mapping = false;
588 if let Some(orig) = sm.find_closest_mapping(loc.line, loc.column - 1) {
589 let source_index = map.add_source(sm.get_source(orig.source).unwrap());
590 let name = orig.name.map(|name| map.add_name(sm.get_name(name).unwrap()));
591 original.original_line = orig.original_line;
592 original.original_column = orig.original_column;
593 original.source = source_index;
594 original.name = name;
595
596 if !self.sources_with_content.contains(&source_index) {
597 if let Some(content) = sm.get_source_content(orig.source) {
598 map.set_source_content(source_index, content);
599 self.sources_with_content.insert(source_index);
600 }
601 }
602
603 found_mapping = true;
604 }
605
606 if !found_mapping {
607 return;
608 }
609 }
610
611 map.add_mapping(self.state.generated_line, self.state.generated_col, Some(original))
612 }
613 }
614}
615
616impl<'a, 'c, W: std::fmt::Write + Sized, S: SourceMap> std::fmt::Write for Printer<'a, 'c, W, S> {
617 fn write_str(&mut self, s: &str) -> std::fmt::Result {
618 self.state.generated_col += s.len() as u32;
619 self.dest.write_str(s)
620 }
621
622 fn write_char(&mut self, c: char) -> std::fmt::Result {
623 Printer::write_char(self, c).map_err(|_| std::fmt::Error)
624 }
625}
626
627mod private {
628 pub trait Sealed {}
629}
630
631#[allow(missing_docs)]
633pub trait PrinterTrait: std::fmt::Write + private::Sealed {
634 fn options(&self) -> &PrinterOptions<'_>;
635 fn state(&self) -> &PrinterState<'_, '_>;
636 fn state_mut(&mut self) -> &mut PrinterState<'_, '_>;
637 fn filename(&self) -> &str;
638 fn error(&self, kind: PrinterErrorKind, loc: crate::dependencies::Location) -> Error<PrinterErrorKind> {
639 Error {
640 kind,
641 loc: Some(ErrorLocation {
642 filename: self.filename().into(),
643 line: loc.line - 1,
644 column: loc.column,
645 }),
646 }
647 }
648
649 fn whitespace(&mut self) -> Result<(), PrinterError>;
650 fn delim(&mut self, c: char, ws_before: bool) -> Result<(), PrinterError>;
651 fn newline(&mut self) -> Result<(), PrinterError>;
652 fn write_str_with_newlines(&mut self, s: &str) -> Result<(), PrinterError>;
653 fn add_mapping(&mut self, loc: Location);
654 fn indent(&mut self);
655 fn dedent(&mut self);
656 fn indent_by(&mut self, amt: u8);
657 fn dedent_by(&mut self, amt: u8);
658 fn write_ident(&mut self, ident: &str, handle_css_module: bool) -> Result<(), PrinterError>;
659 fn write_dashed_ident(&mut self, ident: &str, is_declaration: bool) -> Result<(), PrinterError>;
660
661 fn without_css_module<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T;
662}
663
664impl<'a, 'c, W: std::fmt::Write + Sized, S: SourceMap> private::Sealed for Printer<'a, 'c, W, S> {}
665
666impl<'a, 'c, W: std::fmt::Write + Sized, S: SourceMap> PrinterTrait for Printer<'a, 'c, W, S> {
667 fn options(&self) -> &PrinterOptions<'_> {
668 unsafe { std::mem::transmute::<&PrinterOptions<'a>, &PrinterOptions<'_>>(&self.options) }
669 }
670
671 fn state(&self) -> &PrinterState<'_, '_> {
672 unsafe { std::mem::transmute::<&PrinterState<'a, 'c>, &PrinterState<'_, '_>>(&self.state) }
673 }
674
675 fn state_mut(&mut self) -> &mut PrinterState<'_, '_> {
676 unsafe { std::mem::transmute::<&mut PrinterState<'a, 'c>, &mut PrinterState<'_, '_>>(&mut self.state) }
677 }
678
679 fn filename(&self) -> &str {
680 Printer::filename(self)
681 }
682
683 fn whitespace(&mut self) -> Result<(), PrinterError> {
684 Printer::whitespace(self)
685 }
686
687 fn delim(&mut self, c: char, ws_before: bool) -> Result<(), PrinterError> {
688 Printer::delim(self, c, ws_before)
689 }
690
691 fn newline(&mut self) -> Result<(), PrinterError> {
692 Printer::newline(self)
693 }
694
695 fn write_str_with_newlines(&mut self, s: &str) -> Result<(), PrinterError> {
696 Printer::write_str_with_newlines(self, s)
697 }
698
699 fn add_mapping(&mut self, loc: Location) {
700 Printer::add_mapping(self, loc)
701 }
702
703 fn indent(&mut self) {
704 Printer::indent(self)
705 }
706
707 fn dedent(&mut self) {
708 Printer::dedent(self)
709 }
710
711 fn indent_by(&mut self, amt: u8) {
712 Printer::indent_by(self, amt)
713 }
714
715 fn dedent_by(&mut self, amt: u8) {
716 Printer::dedent_by(self, amt)
717 }
718
719 fn write_ident(&mut self, ident: &str, handle_css_module: bool) -> Result<(), PrinterError> {
720 Printer::write_ident(self, ident, handle_css_module)
721 }
722
723 fn write_dashed_ident(&mut self, ident: &str, is_declaration: bool) -> Result<(), PrinterError> {
724 Printer::write_dashed_ident(self, ident, is_declaration)
725 }
726
727 fn without_css_module<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
728 let css_module = self.state.css_module.take();
729 let res = f(self);
730 self.state.css_module = css_module;
731 res
732 }
733}