Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion derive/src/to_css.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ fn derive_enum(data: &DataEnum, opts: &CssOptions) -> TokenStream2 {
Fields::Unit => {
let s = Literal::string(&variant.ident.to_string().to_case(opts.case));
quote! {
Self::#name => dest.write_str(#s)
Self::#name => {
dest.write_str(#s)?;
Ok(())
}
}
}
Fields::Named(_) => {
Expand Down
5 changes: 3 additions & 2 deletions examples/custom_at_rule.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, convert::Infallible};
use std::{collections::HashMap, convert::Infallible, fmt::Write};

use cssparser::*;
use rspack_lightningcss::{
Expand Down Expand Up @@ -295,7 +295,8 @@ impl ToCss for AtRule {
TailwindDirective::Utilities => "TAILWIND UTILITIES HERE",
TailwindDirective::Variants => "TAILWIND VARIANTS HERE",
};
dest.write_str(directive)
dest.write_str(directive)?;
Ok(())
}
AtRule::Apply(_) => Ok(()),
}
Expand Down
2 changes: 1 addition & 1 deletion napi/src/at_rule_parser.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Write};

use cssparser::*;
use rspack_lightningcss::{
Expand Down
4 changes: 3 additions & 1 deletion src/declaration.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! CSS declarations.

use std::borrow::Cow;
use std::fmt::Write;
use std::ops::Range;

use crate::context::{DeclarationContext, PropertyHandlerContext};
Expand Down Expand Up @@ -170,7 +171,8 @@ impl<'i> DeclarationBlock<'i> {

dest.dedent();
dest.newline()?;
dest.write_char('}')
dest.write_char('}')?;
Ok(())
}

pub(crate) fn has_printable_declarations(&self) -> bool {
Expand Down
3 changes: 2 additions & 1 deletion src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ macro_rules! enum_property {

impl ToCss for $name {
fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError> where W: std::fmt::Write {
dest.write_str(self.as_str())
dest.write_str(self.as_str())?;
Ok(())
}
}
};
Expand Down
14 changes: 10 additions & 4 deletions src/media_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use cssparser::*;
use rspack_lightningcss_static_self::IntoOwned;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::fmt::Write;

#[cfg(feature = "serde")]
use crate::serialization::ValueWrapper;
Expand Down Expand Up @@ -1216,7 +1217,9 @@ impl<'i, FeatureId: FeatureToCss> ToCss for QueryFeature<'i, FeatureId> {
}
}

dest.write_char(')')
dest.write_char(')')?;

Ok(())
}
}

Expand Down Expand Up @@ -1508,7 +1511,8 @@ impl FeatureToCss for MediaFeatureId {
MediaFeatureId::WebKitDevicePixelRatio => {
dest.write_str("-webkit-")?;
dest.write_str(prefix)?;
dest.write_str("device-pixel-ratio")
dest.write_str("device-pixel-ratio")?;
Ok(())
}
_ => {
dest.write_str(prefix)?;
Expand Down Expand Up @@ -1704,9 +1708,11 @@ impl<'i> ToCss for MediaFeatureValue<'i> {
MediaFeatureValue::Integer(num) => num.to_css(dest),
MediaFeatureValue::Boolean(b) => {
if *b {
dest.write_char('1')
dest.write_char('1')?;
Ok(())
} else {
dest.write_char('0')
dest.write_char('0')?;
Ok(())
}
}
MediaFeatureValue::Resolution(res) => res.to_css(dest),
Expand Down
92 changes: 48 additions & 44 deletions src/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::vendor_prefix::VendorPrefix;
use cssparser::{serialize_identifier, serialize_name};
#[cfg(feature = "sourcemap")]
use parcel_sourcemap::{OriginalLocation, SourceMap};
use std::fmt::Write;

/// Options that control how CSS is serialized to a string.
#[derive(Default)]
Expand Down Expand Up @@ -140,47 +141,6 @@ impl<'a, 'c, W: std::fmt::Write + Sized> Printer<'a, 'c, W> {
}
}

/// Writes a raw string to the underlying destination.
///
/// NOTE: Is is assumed that the string does not contain any newline characters.
/// If such a string is written, it will break source maps.
pub fn write_str(&mut self, s: &str) -> Result<(), PrinterError> {
self.col += s.len() as u32;
self.dest.write_str(s)?;
Ok(())
}

/// Writes a raw string which may contain newlines to the underlying destination.
pub fn write_str_with_newlines(&mut self, s: &str) -> Result<(), PrinterError> {
let mut last_line_start: usize = 0;

for (idx, n) in s.char_indices() {
if n == '\n' {
self.line += 1;
self.col = 0;

// Keep track of where the *next* line starts
last_line_start = idx + 1;
}
}

self.col += (s.len() - last_line_start) as u32;
self.dest.write_str(s)?;
Ok(())
}

/// Write a single character to the underlying destination.
pub fn write_char(&mut self, c: char) -> Result<(), PrinterError> {
if c == '\n' {
self.line += 1;
self.col = 0;
} else {
self.col += 1;
}
self.dest.write_char(c)?;
Ok(())
}

/// Writes a single whitespace character, unless the `minify` option is enabled.
///
/// Use `write_char` instead if you wish to force a space character to be written,
Expand All @@ -190,7 +150,8 @@ impl<'a, 'c, W: std::fmt::Write + Sized> Printer<'a, 'c, W> {
return Ok(());
}

self.write_char(' ')
self.write_char(' ')?;
Ok(())
}

/// Writes a delimiter character, followed by whitespace (depending on the `minify` option).
Expand Down Expand Up @@ -422,9 +383,52 @@ impl<'a, 'c, W: std::fmt::Write + Sized> Printer<'a, 'c, W> {
}
}

impl<'a, 'b, 'c, W: std::fmt::Write + Sized> std::fmt::Write for Printer<'a, 'c, W> {
impl<'a, 'c, W: std::fmt::Write + Sized> Write for Printer<'a, 'c, W> {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.col += s.len() as u32;
let mut last_line_start = 0;
for (idx, c) in s.char_indices() {
if c == '\n' {
self.line += 1;
last_line_start = idx + 1;
}
}

self.col = if last_line_start == 0 {
self.col + s.len() as u32
} else {
(s.len() - last_line_start) as u32
};
self.dest.write_str(s)
}

fn write_char(&mut self, c: char) -> std::fmt::Result {
if c == '\n' {
self.line += 1;
self.col = 0;
} else {
self.col += 1;
}

self.dest.write_char(c)
}
}

#[cfg(test)]
mod tests {
use super::{Printer, PrinterOptions};
use std::fmt::Write;

#[test]
fn write_tracks_multiline_positions() {
let mut output = String::new();
let mut printer = Printer::new(&mut output, PrinterOptions::default());

printer.write_str("a\nbc").unwrap();
printer.write_char('\n').unwrap();
printer.write_str("d").unwrap();

assert_eq!((printer.line, printer.col), (2, 1));
drop(printer);
assert_eq!(output, "a\nbc\nd");
}
}
64 changes: 35 additions & 29 deletions src/properties/align.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use crate::vendor_prefix::VendorPrefix;
#[cfg(feature = "visitor")]
use crate::visitor::Visit;
use cssparser::*;
use std::fmt::Write;

#[cfg(feature = "serde")]
use crate::serialization::ValueWrapper;
Expand Down Expand Up @@ -64,9 +65,10 @@ impl ToCss for BaselinePosition {
W: std::fmt::Write,
{
match self {
BaselinePosition::First => dest.write_str("baseline"),
BaselinePosition::Last => dest.write_str("last baseline"),
}
BaselinePosition::First => dest.write_str("baseline")?,
BaselinePosition::Last => dest.write_str("last baseline")?,
};
Ok(())
}
}

Expand Down Expand Up @@ -211,33 +213,34 @@ impl ToCss for JustifyContent {
W: std::fmt::Write,
{
match self {
JustifyContent::Normal => dest.write_str("normal"),
JustifyContent::ContentDistribution(value) => value.to_css(dest),
JustifyContent::Normal => dest.write_str("normal")?,
JustifyContent::ContentDistribution(value) => value.to_css(dest)?,
JustifyContent::ContentPosition { overflow, value } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

value.to_css(dest)
value.to_css(dest)?;
}
JustifyContent::Left { overflow } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

dest.write_str("left")
dest.write_str("left")?;
}
JustifyContent::Right { overflow } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

dest.write_str("right")
dest.write_str("right")?;
}
}
};
Ok(())
}
}

Expand Down Expand Up @@ -434,35 +437,36 @@ impl ToCss for JustifySelf {
W: std::fmt::Write,
{
match self {
JustifySelf::Auto => dest.write_str("auto"),
JustifySelf::Normal => dest.write_str("normal"),
JustifySelf::Stretch => dest.write_str("stretch"),
JustifySelf::BaselinePosition(val) => val.to_css(dest),
JustifySelf::Auto => dest.write_str("auto")?,
JustifySelf::Normal => dest.write_str("normal")?,
JustifySelf::Stretch => dest.write_str("stretch")?,
JustifySelf::BaselinePosition(val) => val.to_css(dest)?,
JustifySelf::SelfPosition { overflow, value } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

value.to_css(dest)
value.to_css(dest)?;
}
JustifySelf::Left { overflow } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

dest.write_str("left")
dest.write_str("left")?;
}
JustifySelf::Right { overflow } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

dest.write_str("right")
dest.write_str("right")?;
}
}
};
Ok(())
}
}

Expand Down Expand Up @@ -616,10 +620,11 @@ impl ToCss for LegacyJustify {
{
dest.write_str("legacy ")?;
match self {
LegacyJustify::Left => dest.write_str("left"),
LegacyJustify::Right => dest.write_str("right"),
LegacyJustify::Center => dest.write_str("center"),
}
LegacyJustify::Left => dest.write_str("left")?,
LegacyJustify::Right => dest.write_str("right")?,
LegacyJustify::Center => dest.write_str("center")?,
};
Ok(())
}
}

Expand Down Expand Up @@ -704,35 +709,36 @@ impl ToCss for JustifyItems {
W: std::fmt::Write,
{
match self {
JustifyItems::Normal => dest.write_str("normal"),
JustifyItems::Stretch => dest.write_str("stretch"),
JustifyItems::BaselinePosition(val) => val.to_css(dest),
JustifyItems::Legacy(val) => val.to_css(dest),
JustifyItems::Normal => dest.write_str("normal")?,
JustifyItems::Stretch => dest.write_str("stretch")?,
JustifyItems::BaselinePosition(val) => val.to_css(dest)?,
JustifyItems::Legacy(val) => val.to_css(dest)?,
JustifyItems::SelfPosition { overflow, value } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

value.to_css(dest)
value.to_css(dest)?;
}
JustifyItems::Left { overflow } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

dest.write_str("left")
dest.write_str("left")?;
}
JustifyItems::Right { overflow } => {
if let Some(overflow) = overflow {
overflow.to_css(dest)?;
dest.write_str(" ")?;
}

dest.write_str("right")
dest.write_str("right")?;
}
}
};
Ok(())
}
}

Expand Down
Loading
Loading