Skip to content

perf(turbopack): Use owned instance of Code for minify() #79991

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

Merged
merged 5 commits into from
Jun 2, 2025
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
42 changes: 37 additions & 5 deletions turbopack/crates/turbo-tasks-fs/src/rope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ use serde_bytes::ByteBuf;
use tokio::io::{AsyncRead, ReadBuf};
use triomphe::Arc;
use turbo_tasks_hash::{DeterministicHash, DeterministicHasher};
use unsize::{CoerceUnsize, Coercion};

static EMPTY_BUF: &[u8] = &[];

Expand All @@ -42,7 +41,7 @@ pub struct Rope {
/// An Arc container for ropes. This indirection allows for easily sharing the
/// contents between Ropes (and also RopeBuilders/RopeReaders).
#[derive(Clone, Debug)]
struct InnerRope(Arc<[RopeElem]>);
struct InnerRope(Arc<Vec<RopeElem>>);

/// Differentiates the types of stored bytes in a rope.
#[derive(Clone, Debug)]
Expand Down Expand Up @@ -117,6 +116,10 @@ impl Rope {
pub fn to_bytes(&self) -> Cow<'_, [u8]> {
self.data.to_bytes(self.length)
}

pub fn into_bytes(self) -> Bytes {
self.data.into_bytes(self.length)
}
}

impl From<Vec<u8>> for Rope {
Expand All @@ -142,7 +145,7 @@ impl<T: Into<Bytes>> From<T> for Rope {
} else {
Rope {
length: bytes.len(),
data: InnerRope(Arc::from([Local(bytes)]).unsize(Coercion::to_slice())),
data: InnerRope(Arc::from(vec![Local(bytes)])),
}
}
}
Expand Down Expand Up @@ -536,11 +539,33 @@ impl InnerRope {
}
}
}

fn into_bytes(mut self, len: usize) -> Bytes {
if self.0.is_empty() {
return Bytes::default();
} else if self.0.len() == 1 {
let data = Arc::try_unwrap(self.0);
match data {
Ok(data) => {
return data.into_iter().next().unwrap().into_bytes(len);
}
Err(data) => {
self.0 = data;
}
}
}

let mut read = RopeReader::new(&self, 0);
let mut buf = Vec::with_capacity(len);
read.read_to_end(&mut buf)
.expect("read of rope cannot fail");
buf.into()
}
}

impl Default for InnerRope {
fn default() -> Self {
InnerRope(Arc::new([]).unsize(Coercion::to_slice()))
InnerRope(Arc::new(vec![]))
}
}

Expand Down Expand Up @@ -579,7 +604,7 @@ impl From<Vec<RopeElem>> for InnerRope {
}

impl Deref for InnerRope {
type Target = Arc<[RopeElem]>;
type Target = Arc<Vec<RopeElem>>;

fn deref(&self) -> &Self::Target {
&self.0
Expand Down Expand Up @@ -610,6 +635,13 @@ impl RopeElem {
_ => None,
}
}

fn into_bytes(self, len: usize) -> Bytes {
match self {
Local(bytes) => bytes,
Shared(inner) => inner.into_bytes(len),
}
}
}

impl DeterministicHash for RopeElem {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ impl EcmascriptBrowserChunkContent {
let mut code = code.build();

if let MinifyType::Minify { mangle } = this.chunking_context.await?.minify_type() {
code = minify(&code, source_maps, mangle)?;
code = minify(code, source_maps, mangle)?;
}

Ok(code.cell())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ impl EcmascriptBrowserEvaluateChunk {
let mut code = code.build();

if let MinifyType::Minify { mangle } = this.chunking_context.await?.minify_type() {
code = minify(&code, source_maps, mangle)?;
code = minify(code, source_maps, mangle)?;
}

Ok(code.cell())
Expand Down
5 changes: 5 additions & 0 deletions turbopack/crates/turbopack-core/src/code_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ impl Code {
pub fn has_source_map(&self) -> bool {
!self.mappings.is_empty()
}

/// Take the source code out of the Code.
pub fn into_source_code(self) -> Rope {
self.code
}
}

/// CodeBuilder provides a mutable container to append source code.
Expand Down
15 changes: 6 additions & 9 deletions turbopack/crates/turbopack-ecmascript/src/minify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,17 @@ use turbopack_core::{
use crate::parse::generate_js_source_map;

#[instrument(level = Level::INFO, skip_all)]
pub fn minify(code: &Code, source_maps: bool, mangle: Option<MangleType>) -> Result<Code> {
pub fn minify(code: Code, source_maps: bool, mangle: Option<MangleType>) -> Result<Code> {
let source_maps = source_maps
.then(|| code.generate_source_map_ref())
.transpose()?;

let source_code = code.into_source_code().into_bytes().into();
let source_code = String::from_utf8(source_code)?;

let cm = Arc::new(SwcSourceMap::new(FilePathMapping::empty()));
let (src, mut src_map_buf) = {
let fm = cm.new_source_file(
FileName::Anon.into(),
code.source_code().to_str()?.into_owned(),
);
let fm = cm.new_source_file(FileName::Anon.into(), source_code);

let lexer = Lexer::new(
Syntax::default(),
Expand All @@ -57,10 +57,7 @@ pub fn minify(code: &Code, source_maps: bool, mangle: Option<MangleType>) -> Res
Ok(program) => program,
Err(err) => {
err.into_diagnostic(handler).emit();
bail!(
"failed to parse source code\n{}",
code.source_code().to_str()?
)
bail!("failed to parse source code\n{}", fm.src)
}
};
let comments = SingleThreadedComments::default();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl EcmascriptBuildNodeChunkContent {
let mut code = code.build();

if let MinifyType::Minify { mangle } = this.chunking_context.await?.minify_type() {
code = minify(&code, source_maps, mangle)?;
code = minify(code, source_maps, mangle)?;
}

Ok(code.cell())
Expand Down
Loading