Skip to main content

rspack_lightningcss/
printer.rs

1//! CSS serialization and source map generation.
2
3use crate::css_modules::CssModule;
4use crate::dependencies::{Dependency, DependencyOptions};
5use crate::error::{Error, ErrorLocation, PrinterError, PrinterErrorKind};
6use crate::rules::{Location, StyleContext};
7use crate::selector::SelectorList;
8use crate::targets::{Targets, TargetsWithSupportsScope};
9use crate::vendor_prefix::VendorPrefix;
10use cssparser::{serialize_identifier, serialize_name};
11#[cfg(feature = "sourcemap")]
12use parcel_sourcemap::SourceMap as ParcelSourceMap;
13#[cfg(feature = "custom_sourcemap")]
14use rustc_hash::FxHashSet;
15use std::fmt::Write;
16#[cfg(not(feature = "custom_sourcemap"))]
17use std::marker::PhantomData;
18
19/// An original source location referenced by a generated source map mapping.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct OriginalLocation {
22  /// The zero-based line number in the original source.
23  pub original_line: u32,
24  /// The zero-based column number in the original source.
25  pub original_column: u32,
26  /// The source index in the source map.
27  pub source: u32,
28  /// The optional name index in the source map.
29  pub name: Option<u32>,
30}
31
32/// A source map implementation that can receive generated mappings and
33/// provide input mappings for remapping.
34#[cfg(feature = "custom_sourcemap")]
35pub trait SourceMap {
36  /// Adds a source path and returns its source index.
37  fn add_source(&mut self, source: &str) -> u32;
38
39  /// Adds a symbol name and returns its name index.
40  fn add_name(&mut self, name: &str) -> u32;
41
42  /// Sets the original content for a source index.
43  fn set_source_content(&mut self, source_index: u32, source_content: &str);
44
45  /// Adds a mapping from a generated position to an optional original location.
46  fn add_mapping(&mut self, generated_line: u32, generated_column: u32, original: Option<OriginalLocation>);
47
48  /// Reads an inline source map data URL.
49  fn from_data_url(source_root: &str, data_url: &str) -> Option<Self>
50  where
51    Self: Sized;
52
53  /// Finds the closest original location for a generated position.
54  fn find_closest_mapping(&mut self, line: u32, column: u32) -> Option<OriginalLocation>;
55
56  /// Returns the source path for a source index.
57  fn get_source(&self, source_index: u32) -> Option<&str>;
58
59  /// Returns the symbol name for a name index.
60  fn get_name(&self, name_index: u32) -> Option<&str>;
61
62  /// Returns the source content for a source index.
63  fn get_source_content(&self, source_index: u32) -> Option<&str>;
64}
65
66/// A source map placeholder used when custom source maps are disabled.
67#[cfg(not(feature = "custom_sourcemap"))]
68pub trait SourceMap {}
69
70#[cfg(not(feature = "custom_sourcemap"))]
71impl SourceMap for () {}
72
73#[cfg(feature = "custom_sourcemap")]
74impl SourceMap for () {
75  fn add_source(&mut self, _source: &str) -> u32 {
76    unreachable!()
77  }
78
79  fn add_name(&mut self, _name: &str) -> u32 {
80    unreachable!()
81  }
82
83  fn set_source_content(&mut self, _source_index: u32, _source_content: &str) {
84    unreachable!()
85  }
86
87  fn add_mapping(&mut self, _generated_line: u32, _generated_column: u32, _original: Option<OriginalLocation>) {
88    unreachable!()
89  }
90
91  fn from_data_url(_source_root: &str, _data_url: &str) -> Option<Self> {
92    unreachable!()
93  }
94
95  fn find_closest_mapping(&mut self, _line: u32, _column: u32) -> Option<OriginalLocation> {
96    unreachable!()
97  }
98
99  fn get_source(&self, _source_index: u32) -> Option<&str> {
100    unreachable!()
101  }
102
103  fn get_name(&self, _name_index: u32) -> Option<&str> {
104    unreachable!()
105  }
106
107  fn get_source_content(&self, _source_index: u32) -> Option<&str> {
108    unreachable!()
109  }
110}
111
112#[cfg(feature = "custom_sourcemap")]
113impl<T: SourceMap + ?Sized> SourceMap for &mut T {
114  fn add_source(&mut self, source: &str) -> u32 {
115    (**self).add_source(source)
116  }
117
118  fn add_name(&mut self, name: &str) -> u32 {
119    (**self).add_name(name)
120  }
121
122  fn set_source_content(&mut self, source_index: u32, source_content: &str) {
123    (**self).set_source_content(source_index, source_content)
124  }
125
126  fn add_mapping(&mut self, generated_line: u32, generated_column: u32, original: Option<OriginalLocation>) {
127    (**self).add_mapping(generated_line, generated_column, original)
128  }
129
130  fn from_data_url(source_root: &str, data_url: &str) -> Option<Self>
131  where
132    Self: Sized,
133  {
134    let _ = (source_root, data_url);
135    None
136  }
137
138  fn find_closest_mapping(&mut self, line: u32, column: u32) -> Option<OriginalLocation> {
139    (**self).find_closest_mapping(line, column)
140  }
141
142  fn get_source(&self, source_index: u32) -> Option<&str> {
143    (**self).get_source(source_index)
144  }
145
146  fn get_name(&self, name_index: u32) -> Option<&str> {
147    (**self).get_name(name_index)
148  }
149
150  fn get_source_content(&self, source_index: u32) -> Option<&str> {
151    (**self).get_source_content(source_index)
152  }
153}
154
155#[cfg(feature = "sourcemap")]
156#[cfg_attr(docsrs, doc(cfg(feature = "sourcemap")))]
157impl SourceMap for ParcelSourceMap {
158  fn add_source(&mut self, source: &str) -> u32 {
159    ParcelSourceMap::add_source(self, source)
160  }
161
162  fn add_name(&mut self, name: &str) -> u32 {
163    ParcelSourceMap::add_name(self, name)
164  }
165
166  fn set_source_content(&mut self, source_index: u32, source_content: &str) {
167    let _ = ParcelSourceMap::set_source_content(self, source_index as usize, source_content);
168  }
169
170  fn add_mapping(&mut self, generated_line: u32, generated_column: u32, original: Option<OriginalLocation>) {
171    ParcelSourceMap::add_mapping(
172      self,
173      generated_line,
174      generated_column,
175      original.map(|original| parcel_sourcemap::OriginalLocation {
176        original_line: original.original_line,
177        original_column: original.original_column,
178        source: original.source,
179        name: original.name,
180      }),
181    );
182  }
183
184  fn from_data_url(source_root: &str, data_url: &str) -> Option<Self> {
185    ParcelSourceMap::from_data_url(source_root, data_url).ok()
186  }
187
188  fn find_closest_mapping(&mut self, line: u32, column: u32) -> Option<OriginalLocation> {
189    let mapping = ParcelSourceMap::find_closest_mapping(self, line, column)?;
190    mapping.original.map(|original| OriginalLocation {
191      original_line: original.original_line,
192      original_column: original.original_column,
193      source: original.source,
194      name: original.name,
195    })
196  }
197
198  fn get_source(&self, source_index: u32) -> Option<&str> {
199    ParcelSourceMap::get_source(self, source_index).ok()
200  }
201
202  fn get_name(&self, name_index: u32) -> Option<&str> {
203    ParcelSourceMap::get_name(self, name_index).ok()
204  }
205
206  fn get_source_content(&self, source_index: u32) -> Option<&str> {
207    ParcelSourceMap::get_source_content(self, source_index).ok()
208  }
209}
210
211/// Options that control how CSS is serialized to a string.
212pub struct PrinterOptions<'a, #[cfg(feature = "custom_sourcemap")] S: SourceMap = ()> {
213  /// Whether to minify the CSS, i.e. remove white space.
214  pub minify: bool,
215  /// An optional source map to write mappings into.
216  #[cfg(feature = "custom_sourcemap")]
217  #[cfg_attr(docsrs, doc(cfg(feature = "custom_sourcemap")))]
218  pub source_map: Option<&'a mut S>,
219  /// An optional project root path, used to generate relative paths for sources used in CSS module hashes.
220  pub project_root: Option<&'a str>,
221  /// Targets to output the CSS for.
222  pub targets: Targets,
223  /// Whether to analyze dependencies (i.e. `@import` and `url()`).
224  /// If true, the dependencies are returned as part of the
225  /// [ToCssResult](super::stylesheet::ToCssResult).
226  ///
227  /// When enabled, `@import` and `url()` dependencies
228  /// are replaced with hashed placeholders that can be replaced with the final
229  /// urls later (after bundling).
230  pub analyze_dependencies: Option<DependencyOptions>,
231  /// A mapping of pseudo classes to replace with class names that can be applied
232  /// from JavaScript. Useful for polyfills, for example.
233  pub pseudo_classes: Option<PseudoClasses<'a>>,
234}
235
236impl<'a> Default for PrinterOptions<'a> {
237  fn default() -> Self {
238    PrinterOptions {
239      minify: false,
240      #[cfg(feature = "custom_sourcemap")]
241      source_map: None,
242      project_root: None,
243      targets: Targets::default(),
244      analyze_dependencies: None,
245      pseudo_classes: None,
246    }
247  }
248}
249
250#[cfg(feature = "custom_sourcemap")]
251impl<'a, S: SourceMap> PrinterOptions<'a, S> {
252  /// Set the source map writer while retaining all other printer options.
253  pub fn with_source_map<T: SourceMap>(self, source_map: impl Into<Option<&'a mut T>>) -> PrinterOptions<'a, T> {
254    PrinterOptions {
255      minify: self.minify,
256      source_map: source_map.into(),
257      project_root: self.project_root,
258      targets: self.targets,
259      analyze_dependencies: self.analyze_dependencies,
260      pseudo_classes: self.pseudo_classes,
261    }
262  }
263}
264
265pub(crate) struct PrinterState<'a, 'c> {
266  pub(crate) loc: Location,
267  pub(crate) generated_line: u32,
268  pub(crate) generated_col: u32,
269  pub(crate) indent: u8,
270  pub(crate) targets: TargetsWithSupportsScope,
271  pub(crate) vendor_prefix: VendorPrefix,
272  pub(crate) in_calc: bool,
273  pub(crate) css_module: Option<CssModule<'a, 'c>>,
274  pub(crate) dependencies: Option<Vec<Dependency>>,
275  pub(crate) remove_imports: bool,
276  pub(crate) context: Option<&'a StyleContext<'a, 'c>>,
277}
278
279/// A mapping of user action pseudo classes to replace with class names.
280///
281/// See [PrinterOptions](PrinterOptions).
282#[derive(Default, Debug)]
283pub struct PseudoClasses<'a> {
284  /// The class name to replace `:hover` with.
285  pub hover: Option<&'a str>,
286  /// The class name to replace `:active` with.
287  pub active: Option<&'a str>,
288  /// The class name to replace `:focus` with.
289  pub focus: Option<&'a str>,
290  /// The class name to replace `:focus-visible` with.
291  pub focus_visible: Option<&'a str>,
292  /// The class name to replace `:focus-within` with.
293  pub focus_within: Option<&'a str>,
294}
295
296/// A `Printer` represents a destination to output serialized CSS, as used in
297/// the [ToCss](super::traits::ToCss) trait. It can wrap any destination that
298/// implements [std::fmt::Write](std::fmt::Write), such as a [String](String).
299///
300/// A `Printer` keeps track of the current line and column position, and uses
301/// this to generate a source map if one is provided.
302///
303/// `Printer` also includes helper functions that assist with writing output
304/// that respects options such as `minify`, and `css_modules`.
305pub struct Printer<'a, 'c, W, S: SourceMap = ()> {
306  pub(crate) sources: Option<&'c Vec<String>>,
307  dest: &'a mut W,
308  pub(crate) options: PrinterOptions<'a>,
309  pub(crate) state: PrinterState<'a, 'c>,
310  #[cfg(feature = "custom_sourcemap")]
311  pub(crate) source_map: Option<&'a mut S>,
312  #[cfg(feature = "custom_sourcemap")]
313  pub(crate) source_maps: Vec<Option<S>>,
314  #[cfg(feature = "custom_sourcemap")]
315  pub(crate) source_map_source_indices: &'c [Option<u32>],
316  #[cfg(feature = "custom_sourcemap")]
317  sources_with_content: FxHashSet<u32>,
318  #[cfg(not(feature = "custom_sourcemap"))]
319  source_map: PhantomData<fn() -> S>,
320}
321
322#[cfg(not(feature = "custom_sourcemap"))]
323impl<'a, 'c, W: Write> Printer<'a, 'c, W> {
324  /// Create a new Printer wrapping the given destination.
325  pub fn new(dest: &'a mut W, options: PrinterOptions<'a>) -> Self {
326    Self::new_impl(dest, options)
327  }
328}
329
330impl<'a, 'c, W: std::fmt::Write + Sized, S: SourceMap> Printer<'a, 'c, W, S> {
331  /// Create a new Printer wrapping the given destination.
332  #[cfg(feature = "custom_sourcemap")]
333  pub fn new(dest: &'a mut W, mut options: PrinterOptions<'a, S>) -> Self {
334    let source_map = options.source_map.take();
335    Self::new_impl(dest, options.with_source_map(None), source_map)
336  }
337
338  fn new_impl(
339    dest: &'a mut W,
340    options: PrinterOptions<'a>,
341    #[cfg(feature = "custom_sourcemap")] source_map: Option<&'a mut S>,
342  ) -> Self {
343    let dependencies = if options.analyze_dependencies.is_some() {
344      Some(Vec::new())
345    } else {
346      None
347    };
348    let remove_imports = matches!(&options.analyze_dependencies, Some(d) if d.remove_imports);
349    Printer {
350      sources: None,
351      dest,
352      #[cfg(feature = "custom_sourcemap")]
353      source_map,
354      state: PrinterState {
355        loc: Location {
356          source_index: 0,
357          line: 0,
358          column: 1,
359        },
360        generated_line: 0,
361        generated_col: 0,
362        indent: 0,
363        targets: TargetsWithSupportsScope::new(options.targets),
364        vendor_prefix: VendorPrefix::empty(),
365        in_calc: false,
366        css_module: None,
367        dependencies,
368        remove_imports,
369        context: None,
370      },
371      options,
372      #[cfg(feature = "custom_sourcemap")]
373      source_maps: Vec::new(),
374      #[cfg(feature = "custom_sourcemap")]
375      source_map_source_indices: &[],
376      #[cfg(feature = "custom_sourcemap")]
377      sources_with_content: FxHashSet::default(),
378      #[cfg(not(feature = "custom_sourcemap"))]
379      source_map: PhantomData,
380    }
381  }
382
383  /// Returns the current source filename that is being printed.
384  pub fn filename(&self) -> &'c str {
385    if let Some(sources) = self.sources {
386      if let Some(f) = sources.get(self.state.loc.source_index as usize) {
387        f
388      } else {
389        "unknown.css"
390      }
391    } else {
392      "unknown.css"
393    }
394  }
395
396  /// Writes a single whitespace character, unless the `minify` option is enabled.
397  ///
398  /// Use `write_char` instead if you wish to force a space character to be written,
399  /// regardless of the `minify` option.
400  pub fn whitespace(&mut self) -> Result<(), PrinterError> {
401    if self.options.minify {
402      return Ok(());
403    }
404
405    self.write_char(' ')?;
406    Ok(())
407  }
408
409  /// Writes a delimiter character, followed by whitespace (depending on the `minify` option).
410  /// If `ws_before` is true, then whitespace is also written before the delimiter.
411  pub fn delim(&mut self, delim: char, ws_before: bool) -> Result<(), PrinterError> {
412    if ws_before {
413      self.whitespace()?;
414    }
415    self.write_char(delim)?;
416    self.whitespace()
417  }
418
419  /// Writes a newline character followed by indentation.
420  /// If the `minify` option is enabled, then nothing is printed.
421  pub fn newline(&mut self) -> Result<(), PrinterError> {
422    if self.options.minify {
423      return Ok(());
424    }
425
426    self.write_char('\n')?;
427    if self.state.indent > 0 {
428      self.write_str(&" ".repeat(self.state.indent as usize))?;
429    }
430
431    Ok(())
432  }
433
434  /// Increases the current indent level.
435  pub fn indent(&mut self) {
436    self.state.indent += 2;
437  }
438
439  /// Decreases the current indent level.
440  pub fn dedent(&mut self) {
441    self.state.indent -= 2;
442  }
443
444  /// Increases the current indent level by the given number of characters.
445  pub fn indent_by(&mut self, amt: u8) {
446    self.state.indent += amt;
447  }
448
449  /// Decreases the current indent level by the given number of characters.
450  pub fn dedent_by(&mut self, amt: u8) {
451    self.state.indent -= amt;
452  }
453
454  /// Returns whether the indent level is greater than one.
455  pub fn is_nested(&self) -> bool {
456    self.state.indent > 2
457  }
458
459  /// Writes a CSS identifier to the underlying destination, escaping it
460  /// as appropriate. If the `css_modules` option was enabled, then a hash
461  /// is added, and the mapping is added to the CSS module.
462  pub fn write_ident(&mut self, ident: &str, handle_css_module: bool) -> Result<(), PrinterError> {
463    if handle_css_module {
464      if let Some(css_module) = &mut self.state.css_module {
465        let dest = &mut self.dest;
466        let mut first = true;
467        css_module.config.pattern.write(
468          &css_module.hashes[self.state.loc.source_index as usize],
469          &css_module.sources[self.state.loc.source_index as usize],
470          ident,
471          if let Some(content_hashes) = &css_module.content_hashes {
472            &content_hashes[self.state.loc.source_index as usize]
473          } else {
474            ""
475          },
476          |s| {
477            self.state.generated_col += s.len() as u32;
478            if first {
479              first = false;
480              serialize_identifier(s, dest)
481            } else {
482              serialize_name(s, dest)
483            }
484          },
485        )?;
486
487        css_module.add_local(&ident, &ident, self.state.loc.source_index);
488        return Ok(());
489      }
490    }
491
492    serialize_identifier(ident, self)?;
493    Ok(())
494  }
495
496  pub(crate) fn write_dashed_ident(&mut self, ident: &str, is_declaration: bool) -> Result<(), PrinterError> {
497    self.write_str("--")?;
498
499    match &mut self.state.css_module {
500      Some(css_module) if css_module.config.dashed_idents => {
501        let dest = &mut self.dest;
502        css_module.config.pattern.write(
503          &css_module.hashes[self.state.loc.source_index as usize],
504          &css_module.sources[self.state.loc.source_index as usize],
505          &ident[2..],
506          if let Some(content_hashes) = &css_module.content_hashes {
507            &content_hashes[self.state.loc.source_index as usize]
508          } else {
509            ""
510          },
511          |s| {
512            self.state.generated_col += s.len() as u32;
513            serialize_name(s, dest)
514          },
515        )?;
516
517        if is_declaration {
518          css_module.add_dashed(ident, self.state.loc.source_index);
519        }
520      }
521      _ => {
522        serialize_name(&ident[2..], self)?;
523      }
524    }
525
526    Ok(())
527  }
528
529  /// Returns an error of the given kind at the provided location in the current source file.
530  pub fn error(&self, kind: PrinterErrorKind, loc: crate::dependencies::Location) -> Error<PrinterErrorKind> {
531    Error {
532      kind,
533      loc: Some(ErrorLocation {
534        filename: self.filename().into(),
535        line: loc.line - 1,
536        column: loc.column,
537      }),
538    }
539  }
540
541  pub(crate) fn take_dependencies(&mut self) -> Option<Vec<Dependency>> {
542    self.state.dependencies.take()
543  }
544
545  /// Adds a mapping to the source map, if any.
546  #[cfg(feature = "custom_sourcemap")]
547  #[cfg_attr(docsrs, doc(cfg(feature = "custom_sourcemap")))]
548  pub fn add_mapping(&mut self, loc: Location) {
549    self.state.loc = loc;
550
551    if let Some(map) = &mut self.source_map {
552      let mut original = OriginalLocation {
553        original_line: loc.line,
554        original_column: loc.column - 1,
555        source: self
556          .source_map_source_indices
557          .get(loc.source_index as usize)
558          .copied()
559          .flatten()
560          .unwrap_or(loc.source_index),
561        name: None,
562      };
563
564      // Remap using input source map if possible.
565      if let Some(Some(sm)) = self.source_maps.get_mut(loc.source_index as usize) {
566        let mut found_mapping = false;
567        if let Some(orig) = sm.find_closest_mapping(loc.line, loc.column - 1) {
568          let source_index = map.add_source(sm.get_source(orig.source).unwrap());
569          let name = orig.name.map(|name| map.add_name(sm.get_name(name).unwrap()));
570          original.original_line = orig.original_line;
571          original.original_column = orig.original_column;
572          original.source = source_index;
573          original.name = name;
574
575          if !self.sources_with_content.contains(&source_index) {
576            if let Some(content) = sm.get_source_content(orig.source) {
577              map.set_source_content(source_index, content);
578              self.sources_with_content.insert(source_index);
579            }
580          }
581
582          found_mapping = true;
583        }
584
585        if !found_mapping {
586          return;
587        }
588      }
589
590      map.add_mapping(self.state.generated_line, self.state.generated_col, Some(original))
591    }
592  }
593
594  fn with_context<T>(&mut self, selectors: &SelectorList, f: impl FnOnce(&mut Self) -> T) -> T {
595    let parent = self.state.context.take();
596    let ctx = StyleContext {
597      selectors: unsafe { std::mem::transmute(selectors) },
598      parent,
599    };
600
601    // The context is only installed for the duration of the callback.
602    self.state.context = Some(unsafe { std::mem::transmute(&ctx) });
603    let res = f(self);
604    self.state.context = parent;
605    res
606  }
607
608  fn with_cleared_context<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
609    let parent = self.state.context.take();
610    let res = f(self);
611    self.state.context = parent;
612    res
613  }
614
615  fn with_parent_context<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
616    let parent = self.state.context.take();
617    if let Some(parent) = parent {
618      self.state.context = parent.parent;
619    }
620    let res = f(self);
621    self.state.context = parent;
622    res
623  }
624}
625
626impl<'a, 'c, W: std::fmt::Write + Sized, S: SourceMap> Write for Printer<'a, 'c, W, S> {
627  fn write_str(&mut self, s: &str) -> std::fmt::Result {
628    let mut last_line_start = 0;
629    for (idx, c) in s.char_indices() {
630      if c == '\n' {
631        self.state.generated_line += 1;
632        last_line_start = idx + 1;
633      }
634    }
635
636    self.state.generated_col = if last_line_start == 0 {
637      self.state.generated_col + s.len() as u32
638    } else {
639      (s.len() - last_line_start) as u32
640    };
641    self.dest.write_str(s)
642  }
643
644  fn write_char(&mut self, c: char) -> std::fmt::Result {
645    if c == '\n' {
646      self.state.generated_line += 1;
647      self.state.generated_col = 0;
648    } else {
649      self.state.generated_col += 1;
650    }
651
652    self.dest.write_char(c)
653  }
654}
655
656// Supertrait methods can be called through a public generic bound. Require a
657// crate-local token to run a callback with an installed style context.
658pub(crate) struct ContextAccess;
659
660mod private {
661  use super::*;
662
663  pub(crate) trait Sealed {
664    fn targets(&self) -> &TargetsWithSupportsScope;
665    fn targets_mut(&mut self) -> &mut TargetsWithSupportsScope;
666    fn vendor_prefix(&self) -> VendorPrefix;
667    fn set_vendor_prefix(&mut self, prefix: VendorPrefix);
668    fn loc(&self) -> Location;
669    fn in_calc(&self) -> bool;
670    fn set_in_calc(&mut self, in_calc: bool);
671    fn css_module_config(&self) -> Option<&crate::css_modules::Config>;
672    fn with_css_module_mut<T>(&mut self, f: impl FnOnce(&mut CssModule<'_, '_>) -> T) -> Option<T>;
673    fn is_nested(&self) -> bool;
674    fn has_dependencies(&self) -> bool;
675    fn add_dependency(&mut self, dep: Dependency);
676    fn remove_imports(&self) -> bool;
677    fn has_context(&self) -> bool;
678    fn with_context<T>(
679      &mut self,
680      access: ContextAccess,
681      selectors: &SelectorList,
682      f: impl FnOnce(&mut Self) -> T,
683    ) -> T;
684    fn with_cleared_context<T>(&mut self, access: ContextAccess, f: impl FnOnce(&mut Self) -> T) -> T;
685    fn with_parent_context<T>(&mut self, access: ContextAccess, f: impl FnOnce(&mut Self) -> T) -> T;
686    fn with_current_context<T>(
687      &mut self,
688      access: ContextAccess,
689      f: impl FnOnce(&mut Self, Option<&StyleContext<'_, '_>>) -> T,
690    ) -> T;
691    fn with_pseudo_class<T>(
692      &mut self,
693      get: impl for<'p> FnOnce(&PseudoClasses<'p>) -> Option<&'p str>,
694      f: impl FnOnce(&mut Self, Option<&str>) -> T,
695    ) -> T;
696  }
697}
698
699/// A printer abstraction used by CSS serialization implementations.
700#[allow(missing_docs)]
701#[allow(private_bounds)]
702pub trait PrinterTrait: std::fmt::Write + private::Sealed {
703  fn options(&self) -> &PrinterOptions<'_>;
704  fn filename(&self) -> &str;
705  fn error(&self, kind: PrinterErrorKind, loc: crate::dependencies::Location) -> Error<PrinterErrorKind> {
706    Error {
707      kind,
708      loc: Some(ErrorLocation {
709        filename: self.filename().into(),
710        line: loc.line - 1,
711        column: loc.column,
712      }),
713    }
714  }
715
716  fn whitespace(&mut self) -> Result<(), PrinterError>;
717  fn delim(&mut self, c: char, ws_before: bool) -> Result<(), PrinterError>;
718  fn newline(&mut self) -> Result<(), PrinterError>;
719  #[cfg(feature = "custom_sourcemap")]
720  fn add_mapping(&mut self, loc: Location);
721  fn indent(&mut self);
722  fn dedent(&mut self);
723  fn indent_by(&mut self, amt: u8);
724  fn dedent_by(&mut self, amt: u8);
725  fn write_ident(&mut self, ident: &str, handle_css_module: bool) -> Result<(), PrinterError>;
726  fn write_dashed_ident(&mut self, ident: &str, is_declaration: bool) -> Result<(), PrinterError>;
727
728  fn without_css_module<T, E>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, E>) -> Result<T, E>;
729}
730
731impl<W: Write, S: SourceMap> private::Sealed for Printer<'_, '_, W, S> {
732  fn targets(&self) -> &TargetsWithSupportsScope {
733    &self.state.targets
734  }
735
736  fn targets_mut(&mut self) -> &mut TargetsWithSupportsScope {
737    &mut self.state.targets
738  }
739
740  fn vendor_prefix(&self) -> VendorPrefix {
741    self.state.vendor_prefix
742  }
743
744  fn set_vendor_prefix(&mut self, prefix: VendorPrefix) {
745    self.state.vendor_prefix = prefix;
746  }
747
748  fn loc(&self) -> Location {
749    self.state.loc
750  }
751
752  fn in_calc(&self) -> bool {
753    self.state.in_calc
754  }
755
756  fn set_in_calc(&mut self, in_calc: bool) {
757    self.state.in_calc = in_calc;
758  }
759
760  fn css_module_config(&self) -> Option<&crate::css_modules::Config> {
761    self.state.css_module.as_ref().map(|css_module| css_module.config)
762  }
763
764  fn with_css_module_mut<T>(&mut self, f: impl FnOnce(&mut CssModule<'_, '_>) -> T) -> Option<T> {
765    self.state.css_module.as_mut().map(f)
766  }
767
768  fn is_nested(&self) -> bool {
769    Printer::is_nested(self)
770  }
771
772  fn has_dependencies(&self) -> bool {
773    self.state.dependencies.is_some()
774  }
775
776  fn add_dependency(&mut self, dep: Dependency) {
777    if let Some(dependencies) = &mut self.state.dependencies {
778      dependencies.push(dep);
779    }
780  }
781
782  fn remove_imports(&self) -> bool {
783    self.state.remove_imports
784  }
785
786  fn has_context(&self) -> bool {
787    self.state.context.is_some()
788  }
789
790  fn with_context<T>(&mut self, _: ContextAccess, selectors: &SelectorList, f: impl FnOnce(&mut Self) -> T) -> T {
791    Printer::with_context(self, selectors, f)
792  }
793
794  fn with_cleared_context<T>(&mut self, _: ContextAccess, f: impl FnOnce(&mut Self) -> T) -> T {
795    Printer::with_cleared_context(self, f)
796  }
797
798  fn with_parent_context<T>(&mut self, _: ContextAccess, f: impl FnOnce(&mut Self) -> T) -> T {
799    Printer::with_parent_context(self, f)
800  }
801
802  fn with_current_context<T>(
803    &mut self,
804    _: ContextAccess,
805    f: impl FnOnce(&mut Self, Option<&StyleContext<'_, '_>>) -> T,
806  ) -> T {
807    let context = self.state.context;
808    f(self, context)
809  }
810
811  fn with_pseudo_class<T>(
812    &mut self,
813    get: impl for<'p> FnOnce(&PseudoClasses<'p>) -> Option<&'p str>,
814    f: impl FnOnce(&mut Self, Option<&str>) -> T,
815  ) -> T {
816    let class = self.options.pseudo_classes.as_ref().and_then(get);
817    f(self, class)
818  }
819}
820
821impl<'a, 'c, W: std::fmt::Write + Sized, S: SourceMap> PrinterTrait for Printer<'a, 'c, W, S> {
822  fn options(&self) -> &PrinterOptions<'_> {
823    &self.options
824  }
825
826  fn filename(&self) -> &str {
827    Printer::filename(self)
828  }
829
830  fn whitespace(&mut self) -> Result<(), PrinterError> {
831    Printer::whitespace(self)
832  }
833
834  fn delim(&mut self, c: char, ws_before: bool) -> Result<(), PrinterError> {
835    Printer::delim(self, c, ws_before)
836  }
837
838  fn newline(&mut self) -> Result<(), PrinterError> {
839    Printer::newline(self)
840  }
841
842  #[cfg(feature = "custom_sourcemap")]
843  fn add_mapping(&mut self, loc: Location) {
844    Printer::add_mapping(self, loc)
845  }
846
847  fn indent(&mut self) {
848    Printer::indent(self)
849  }
850
851  fn dedent(&mut self) {
852    Printer::dedent(self)
853  }
854
855  fn indent_by(&mut self, amt: u8) {
856    Printer::indent_by(self, amt)
857  }
858
859  fn dedent_by(&mut self, amt: u8) {
860    Printer::dedent_by(self, amt)
861  }
862
863  fn write_ident(&mut self, ident: &str, handle_css_module: bool) -> Result<(), PrinterError> {
864    Printer::write_ident(self, ident, handle_css_module)
865  }
866
867  fn write_dashed_ident(&mut self, ident: &str, is_declaration: bool) -> Result<(), PrinterError> {
868    Printer::write_dashed_ident(self, ident, is_declaration)
869  }
870
871  fn without_css_module<T, E>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, E>) -> Result<T, E> {
872    let css_module = self.state.css_module.take();
873    let res = f(self)?;
874    self.state.css_module = css_module;
875    Ok(res)
876  }
877}
878
879#[cfg(test)]
880mod tests {
881  use super::{Printer, PrinterOptions};
882  use std::fmt::Write;
883
884  #[test]
885  fn write_tracks_multiline_positions() {
886    let mut output = String::new();
887    let mut printer = Printer::new(&mut output, PrinterOptions::default());
888
889    printer.write_str("a\nbc").unwrap();
890    printer.write_char('\n').unwrap();
891    printer.write_str("d").unwrap();
892
893    assert_eq!((printer.state.generated_line, printer.state.generated_col), (2, 1));
894    drop(printer);
895    assert_eq!(output, "a\nbc\nd");
896  }
897}