Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(css/parser): comments supporting #5504

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
100 changes: 100 additions & 0 deletions crates/swc_css_codegen/src/comments.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
use swc_common::comments::CommentKind;

use super::*;

macro_rules! write_comments {
($e:expr, $prefix_space:expr, $cmts:expr) => {{
let cmts = match $cmts {
Some(v) => v,
None => return Ok(()),
};

for cmt in cmts.iter() {
match cmt.kind {
CommentKind::Line => {
if $prefix_space {
$e.wr.write_comment(" ")?;
}

srcmap!($e, cmt, true);

$e.wr.write_comment("//")?;
$e.wr.write_comment(&cmt.text)?;

srcmap!($e, cmt, false);

$e.wr.write_newline()?;
}
CommentKind::Block => {
if $prefix_space {
$e.wr.write_comment(" ")?;
}

srcmap!($e, cmt, true);

$e.wr.write_comment("/*")?;
$e.wr.write_comment(&cmt.text)?;

{
let hi = cmt.span_hi();

if !hi.is_dummy() && hi.0 > 2 {
$e.wr.add_srcmap(hi - swc_common::BytePos(2))?;
}
}

$e.wr.write_comment("*/")?;
$e.wr.write_space()?;
}
}
}

return Ok(());
}};
}

impl<'a, W: CssWriter> CodeGenerator<'a, W> {
pub(super) fn emit_trailing_comments_of_pos(
&mut self,
pos: BytePos,
prefix_space: bool,
_is_hi: bool,
) -> Result {
if pos.is_dummy() {
return Ok(());
}

let comments = match self.comments {
Some(ref comments) => comments,
None => return Ok(()),
};

let cmts = comments.take_trailing(pos);

write_comments!(self, prefix_space, &cmts)
}

pub(super) fn emit_leading_comments(&mut self, mut pos: BytePos, is_hi: bool) -> Result {
if pos.is_dummy() {
return Ok(());
}

let comments = match self.comments {
Some(ref comments) => comments,
None => return Ok(()),
};

if is_hi {
pos = pos - BytePos(1)
}

write_comments!(self, false, comments.take_leading(pos))
}

#[inline(always)]
pub(super) fn emit_leading_comments_of_span(&mut self, span: Span, is_hi: bool) -> Result {
let pos = if is_hi { span.hi } else { span.lo };

self.emit_leading_comments(pos, is_hi)
}
}
25 changes: 12 additions & 13 deletions crates/swc_css_codegen/src/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ use std::ops::{Deref, DerefMut};

use crate::{writer::CssWriter, CodeGenerator};

impl<W> CodeGenerator<W>
where
W: CssWriter,
{
impl<'a, W: CssWriter> CodeGenerator<'a, W> {
/// Original context is restored when returned guard is dropped.
#[inline]
pub(super) fn with_ctx(&mut self, ctx: Ctx) -> WithCtx<W> {
pub(super) fn with_ctx(&mut self, ctx: Ctx) -> WithCtx<'a, '_, W> {
let orig_ctx = self.ctx;

self.ctx = ctx;

WithCtx {
orig_ctx,
inner: self,
Expand All @@ -21,25 +20,25 @@ where
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct Ctx {}

pub(super) struct WithCtx<'w, I: 'w + CssWriter> {
inner: &'w mut CodeGenerator<I>,
pub(super) struct WithCtx<'a, 'w, I: 'w + CssWriter> {
inner: &'w mut CodeGenerator<'a, I>,
orig_ctx: Ctx,
}

impl<'w, I: CssWriter> Deref for WithCtx<'w, I> {
type Target = CodeGenerator<I>;
impl<'a, 'w, I: CssWriter> Deref for WithCtx<'a, 'w, I> {
type Target = CodeGenerator<'a, I>;

fn deref(&self) -> &CodeGenerator<I> {
fn deref(&self) -> &CodeGenerator<'a, I> {
self.inner
}
}
impl<'w, I: CssWriter> DerefMut for WithCtx<'w, I> {
fn deref_mut(&mut self) -> &mut CodeGenerator<I> {
impl<'a, 'w, I: CssWriter> DerefMut for WithCtx<'a, 'w, I> {
fn deref_mut(&mut self) -> &mut CodeGenerator<'a, I> {
self.inner
}
}

impl<'w, I: CssWriter> Drop for WithCtx<'w, I> {
impl<'a, 'w, I: CssWriter> Drop for WithCtx<'a, 'w, I> {
fn drop(&mut self) {
self.inner.ctx = self.orig_ctx;
}
Expand Down
14 changes: 9 additions & 5 deletions crates/swc_css_codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub use std::fmt::Result;
use std::str::from_utf8;

use serde::{Deserialize, Serialize};
use swc_common::{BytePos, Span, Spanned, DUMMY_SP};
use swc_common::{comments::Comments, BytePos, Span, Spanned, DUMMY_SP};
use swc_css_ast::*;
use swc_css_codegen_macros::emitter;
use writer::CssWriter;
Expand All @@ -15,6 +15,7 @@ use self::{ctx::Ctx, list::ListFormat};

#[macro_use]
mod macros;
mod comments;
mod ctx;
mod emit;
mod list;
Expand All @@ -27,30 +28,32 @@ pub struct CodegenConfig {
pub minify: bool,
}

#[derive(Debug)]
pub struct CodeGenerator<W>
pub struct CodeGenerator<'a, W>
where
W: CssWriter,
{
wr: W,
comments: Option<&'a dyn Comments>,
config: CodegenConfig,
ctx: Ctx,
}

impl<W> CodeGenerator<W>
impl<'a, W> CodeGenerator<'a, W>
where
W: CssWriter,
{
pub fn new(wr: W, config: CodegenConfig) -> Self {
pub fn new(wr: W, comments: Option<&'a dyn Comments>, config: CodegenConfig) -> Self {
CodeGenerator {
wr,
config,
comments,
ctx: Default::default(),
}
}

#[emitter]
fn emit_stylesheet(&mut self, n: &Stylesheet) -> Result {
self.emit_leading_comments_of_span(n.span(), false)?;
self.emit_list(
&n.rules,
if self.config.minify {
Expand All @@ -59,6 +62,7 @@ where
ListFormat::NotDelimited | ListFormat::MultiLine
},
)?;
self.emit_trailing_comments_of_pos(n.span().hi, true, true)?;
}

#[emitter]
Expand Down
18 changes: 18 additions & 0 deletions crates/swc_css_codegen/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,21 @@ macro_rules! hi_span_offset {
}
}};
}

///
/// - `srcmap!(true)` for start (span.lo)
/// - `srcmap!(false)` for end (span.hi)
macro_rules! srcmap {
($emitter:expr, $n:expr, true) => {{
let lo = $n.span_lo();
if !lo.is_dummy() {
$emitter.wr.add_srcmap(lo)?;
}
}};
($emitter:expr, $n:expr, false) => {
let hi = $n.span_hi();
if !hi.is_dummy() {
$emitter.wr.add_srcmap(hi)?;
}
};
}
28 changes: 28 additions & 0 deletions crates/swc_css_codegen/src/writer/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,34 @@ where
Ok(())
}

fn write_comment(&mut self, s: &str) -> Result {
self.write(None, s)?;

{
let line_start_of_s = compute_line_starts(s);

if line_start_of_s.len() > 1 {
self.line = self.line + line_start_of_s.len() - 1;

let last_line_byte_index = line_start_of_s.last().cloned().unwrap_or(0);

self.col = s[last_line_byte_index..].chars().count();
}
}

Ok(())
}

fn add_srcmap(&mut self, pos: BytePos) -> Result {
if self.line_start {
self.pending_srcmap = Some(pos);
} else {
self.srcmap(pos);
}

Ok(())
}

fn increase_indent(&mut self) {
self.indent_level += 1;
}
Expand Down
6 changes: 5 additions & 1 deletion crates/swc_css_codegen/src/writer/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt::Result;

use auto_impl::auto_impl;
use swc_common::Span;
use swc_common::{BytePos, Span};

pub mod basic;

Expand All @@ -15,6 +15,10 @@ pub trait CssWriter {

fn write_str(&mut self, span: Span, s: &str) -> Result;

fn write_comment(&mut self, s: &str) -> Result;

fn add_srcmap(&mut self, pos: BytePos) -> Result;

fn increase_indent(&mut self);

fn decrease_indent(&mut self);
Expand Down