Unverified Commit 60fb2f1c authored by Donny/강동윤's avatar Donny/강동윤 Committed by GitHub

build(turbopack): Update `swc_core` to `v27.0.1` (#80338)

### What?

ChangeLog: https://github.com/swc-project/swc/compare/swc_core%40v26.4.4...swc_core%40v27.0.1

ChangeLog for plugins: https://github.com/swc-project/plugins/pull/466

### Why?

Apply `swc_sourcemap` performance optimization.
parent 4e71be3b
This diff is collapsed.
......@@ -162,7 +162,7 @@ opt-level = "s"
[profile.release.package.zstd-sys]
opt-level = 3
[profile.release.package.sourcemap]
[profile.release.package.swc_sourcemap]
opt-level = 3
[profile.release.package.turbopack-wasm]
......@@ -292,21 +292,21 @@ turbopack-trace-utils = { path = "turbopack/crates/turbopack-trace-utils" }
turbopack-wasm = { path = "turbopack/crates/turbopack-wasm" }
# SWC crates
swc_core = { version = "26.4.4", features = [
swc_core = { version = "27.0.1", features = [
"ecma_loader_lru",
"ecma_loader_parking_lot",
"parallel_rayon",
] }
testing = { version = "12.0.0" }
testing = { version = "13.0.0" }
# Keep consistent with preset_env_base through swc_core
browserslist-rs = { version = "0.18.0" }
mdxjs = "1.0.3"
modularize_imports = { version = "0.86.0" }
styled_components = { version = "0.114.0" }
styled_jsx = { version = "0.90.3" }
swc_emotion = { version = "0.90.0" }
swc_relay = { version = "0.60.0" }
modularize_imports = { version = "0.87.0" }
styled_components = { version = "0.115.0" }
styled_jsx = { version = "0.91.1" }
swc_emotion = { version = "0.91.0" }
swc_relay = { version = "0.61.0" }
# General Deps
chromiumoxide = { version = "0.5.4", features = [
......@@ -328,6 +328,7 @@ async-compression = { version = "0.3.13", default-features = false, features = [
async-trait = "0.1.64"
bitfield = "0.18.0"
bytes = "1.1.0"
bytes-str = "0.2.6"
chrono = "0.4.23"
clap = { version = "4.5.2", features = ["derive"] }
concurrent-queue = "2.5.0"
......@@ -402,7 +403,7 @@ smallvec = { version = "1.13.1", features = [
"union",
"const_new",
] }
sourcemap = "9.2.2"
swc_sourcemap = "9.2.2"
strsim = "0.11.1"
shrink-to-fit = "0.2.10"
syn = "2.0.100"
......@@ -422,4 +423,4 @@ vergen-gitcl = { version = "1.0.8", features = ["cargo"] }
webbrowser = "0.8.7"
[patch.crates-io]
sourcemap = { git = "https://github.com/kdy1/rust-sourcemap", branch = "main" }
mdxjs = { git = "https://github.com/kdy1/mdxjs-rs.git", branch = "swc-core-27" }
......@@ -32,8 +32,8 @@ lazy_static = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
rustc-hash = { workspace = true }
react_remove_properties = "0.40.0"
remove_console = "0.41.0"
react_remove_properties = "0.41.0"
remove_console = "0.42.0"
itertools = { workspace = true }
percent-encoding = "2.3.1"
serde_path_to_error = { workspace = true }
......
......@@ -22,6 +22,7 @@ workspace = true
[dependencies]
base64 = "0.21.0"
bytes-str = { workspace = true }
chrono = "0.4"
easy-error = "1.0.0"
either = "1"
......@@ -67,8 +68,8 @@ turbopack-ecmascript-plugins = { workspace = true, optional = true }
turbo-rcstr = { workspace = true }
urlencoding = { workspace = true }
react_remove_properties = "0.40.0"
remove_console = "0.41.0"
react_remove_properties = "0.41.0"
remove_console = "0.42.0"
preset_env_base = "3.0.1"
[dev-dependencies]
......
......@@ -138,7 +138,8 @@ mod tests {
fn assert_required(code: &str, required: bool) {
run_test2(false, |cm, _| {
let fm = cm.new_source_file(FileName::Custom("test.tsx".into()).into(), code.into());
let fm =
cm.new_source_file(FileName::Custom("test.tsx".into()).into(), code.to_string());
let program = parse_file_as_program(
&fm,
......
......@@ -2,9 +2,9 @@ use std::{
env::current_dir,
iter::FromIterator,
path::{Path, PathBuf},
sync::Arc,
};
use bytes_str::BytesStr;
use next_custom_transforms::transforms::{
amp_attributes::amp_attributes,
cjs_optimizer::cjs_optimizer,
......@@ -366,8 +366,8 @@ fn next_ssg_fixture(input: PathBuf) {
next: false.into(),
runtime: None,
import_source: Some("".into()),
pragma: Some(Arc::new("__jsx".into())),
pragma_frag: Some(Arc::new("__jsxFrag".into())),
pragma: Some(BytesStr::from_str_slice("__jsx")),
pragma_frag: Some(BytesStr::from_str_slice("__jsxFrag")),
throw_if_namespace: false.into(),
development: false.into(),
refresh: Default::default(),
......@@ -802,8 +802,8 @@ fn run_stip_page_exports_test(input: &Path, output: &Path, mode: ExportFilter) {
next: false.into(),
runtime: None,
import_source: Some("".into()),
pragma: Some(Arc::new("__jsx".into())),
pragma_frag: Some(Arc::new("__jsxFrag".into())),
pragma: Some(BytesStr::from_str_slice("__jsx")),
pragma_frag: Some(BytesStr::from_str_slice("__jsxFrag")),
throw_if_namespace: false.into(),
development: false.into(),
..Default::default()
......
......@@ -40,7 +40,7 @@ pub fn minify_sync(s: JsString, opts: JsValue) -> Result<JsValue, JsValue> {
},
|handler| {
GLOBALS.set(&Default::default(), || {
let fm = c.cm.new_source_file(FileName::Anon.into(), s.into());
let fm = c.cm.new_source_file(FileName::Anon.into(), String::from(s));
let program = c
.minify(fm, handler, &opts, Default::default())
.context("failed to minify file")?;
......@@ -89,7 +89,7 @@ pub fn transform_sync(s: JsValue, opts: JsValue) -> Result<JsValue, JsValue> {
} else {
FileName::Real(opts.swc.filename.clone().into()).into()
},
s.into(),
String::from(s),
);
let cm = c.cm.clone();
let file = fm.clone();
......@@ -154,7 +154,7 @@ pub fn parse_sync(s: JsString, opts: JsValue) -> Result<JsValue, JsValue> {
|handler| {
c.run(|| {
GLOBALS.set(&Default::default(), || {
let fm = c.cm.new_source_file(FileName::Anon.into(), s.into());
let fm = c.cm.new_source_file(FileName::Anon.into(), String::from(s));
let cmts = c.comments().clone();
let comments = if opts.comments {
......
......@@ -16,6 +16,7 @@ serde = { workspace = true }
new_debug_unreachable = "1.0.6"
shrink-to-fit = { workspace = true }
rustc-hash = { workspace = true }
bytes-str = { workspace = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
napi = { workspace = true, optional = true }
......
......@@ -9,6 +9,7 @@ use std::{
path::{Path, PathBuf},
};
use bytes_str::BytesStr;
use debug_unreachable::debug_unreachable;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use shrink_to_fit::ShrinkToFit;
......@@ -160,6 +161,16 @@ impl Borrow<str> for RcStr {
}
}
impl From<BytesStr> for RcStr {
fn from(s: BytesStr) -> Self {
let bytes: Vec<u8> = s.into_bytes().into();
RcStr::from(unsafe {
// Safety: BytesStr are valid utf-8
String::from_utf8_unchecked(bytes)
})
}
}
impl From<Arc<String>> for RcStr {
fn from(s: Arc<String>) -> Self {
match Arc::try_unwrap(s) {
......
......@@ -34,7 +34,7 @@ serde = { workspace = true, features = ["rc"] }
serde_bytes = { workspace = true }
serde_json = { workspace = true, features = ["preserve_order"] }
smallvec = { workspace = true }
sourcemap = { workspace = true }
swc_sourcemap = { workspace = true }
swc_core = { workspace = true, features = ["ecma_preset_env", "common"] }
tracing = { workspace = true }
turbo-prehash = { workspace = true }
......@@ -44,6 +44,7 @@ turbo-tasks-env = { workspace = true }
turbo-tasks-fs = { workspace = true }
turbo-tasks-hash = { workspace = true }
urlencoding = { workspace = true }
bytes-str = { workspace = true }
[build-dependencies]
turbo-tasks-build = { workspace = true }
......
use std::{borrow::Cow, io::Write, ops::Deref, sync::Arc};
use anyhow::Result;
use bytes_str::BytesStr;
use once_cell::sync::Lazy;
use ref_cast::RefCast;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sourcemap::{DecodedMap, SourceMap as RegularMap, SourceMapBuilder, SourceMapIndex};
use swc_sourcemap::{DecodedMap, SourceMap as RegularMap, SourceMapBuilder, SourceMapIndex};
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use turbo_tasks_fs::{
......@@ -148,18 +149,20 @@ impl Token {
}
}
impl From<sourcemap::Token<'_>> for Token {
fn from(t: sourcemap::Token) -> Self {
impl From<swc_sourcemap::Token<'_>> for Token {
fn from(t: swc_sourcemap::Token) -> Self {
if t.has_source() {
Token::Original(OriginalToken {
generated_line: t.get_dst_line(),
generated_column: t.get_dst_col(),
original_file: RcStr::from(
t.get_source().expect("already checked token has source"),
t.get_source()
.expect("already checked token has source")
.clone(),
),
original_line: t.get_src_line(),
original_column: t.get_src_col(),
name: t.get_name().map(RcStr::from),
name: t.get_name().cloned().map(RcStr::from),
})
} else {
Token::Synthetic(SyntheticToken {
......@@ -171,12 +174,12 @@ impl From<sourcemap::Token<'_>> for Token {
}
}
impl TryInto<sourcemap::RawToken> for Token {
impl TryInto<swc_sourcemap::RawToken> for Token {
type Error = std::num::ParseIntError;
fn try_into(self) -> Result<sourcemap::RawToken, Self::Error> {
fn try_into(self) -> Result<swc_sourcemap::RawToken, Self::Error> {
Ok(match self {
Self::Original(t) => sourcemap::RawToken {
Self::Original(t) => swc_sourcemap::RawToken {
dst_col: t.generated_column,
dst_line: t.generated_line,
name_id: match t.name {
......@@ -188,7 +191,7 @@ impl TryInto<sourcemap::RawToken> for Token {
src_id: t.original_file.parse()?,
is_range: false,
},
Self::Synthetic(t) => sourcemap::RawToken {
Self::Synthetic(t) => swc_sourcemap::RawToken {
dst_col: t.generated_column,
dst_line: t.generated_line,
name_id: SOURCEMAP_CRATE_NONE_U32,
......@@ -273,13 +276,13 @@ impl SourceMap {
.sections
.iter()
.map(|s| {
sourcemap::SourceMapSection::new(
swc_sourcemap::SourceMapSection::new(
(s.offset.line, s.offset.column),
None,
Some(s.map.0.clone()),
)
})
.collect::<Vec<sourcemap::SourceMapSection>>();
.collect::<Vec<swc_sourcemap::SourceMapSection>>();
Arc::new(CrateMapWrapper(DecodedMap::Index(SourceMapIndex::new(
None, sections,
))))
......@@ -406,10 +409,10 @@ impl SourceMap {
pub async fn with_resolved_sources(&self, origin: Vc<FileSystemPath>) -> Result<Self> {
async fn resolve_source(
source_request: Arc<str>,
source_content: Option<Arc<str>>,
source_request: BytesStr,
source_content: Option<BytesStr>,
origin: Vc<FileSystemPath>,
) -> Result<(Arc<str>, Arc<str>)> {
) -> Result<(BytesStr, BytesStr)> {
Ok(
if let Some(path) = *origin.parent().try_join((&*source_request).into()).await? {
let path_str = path.to_string().await?;
......@@ -448,14 +451,14 @@ impl SourceMap {
origin: Vc<FileSystemPath>,
) -> Result<RegularMap> {
let map = &map.0;
let file = map.get_file().map(Arc::<str>::from);
let file = map.get_file().cloned();
let tokens = map.tokens().map(|t| t.get_raw_token()).collect();
let names = map.names().map(Arc::<str>::from).collect();
let names = map.names().cloned().collect();
let count = map.get_source_count() as usize;
let sources = map.sources().map(Arc::<str>::from).collect::<Vec<_>>();
let sources = map.sources().cloned().collect::<Vec<_>>();
let source_contents = map
.source_contents()
.map(|s| s.map(Arc::<str>::from))
.map(|s| s.cloned())
.collect::<Vec<_>>();
let mut new_sources = Vec::with_capacity(count);
let mut new_source_contents = Vec::with_capacity(count);
......@@ -482,7 +485,7 @@ impl SourceMap {
}
DecodedMap::Index(map) => {
let count = map.get_section_count() as usize;
let file = map.get_file().map(ToString::to_string);
let file = map.get_file().cloned();
let sections = map
.sections()
.filter_map(|section| {
......@@ -503,7 +506,7 @@ impl SourceMap {
.await?;
let mut new_sections = Vec::with_capacity(count);
for (offset, map) in sections {
new_sections.push(sourcemap::SourceMapSection::new(
new_sections.push(swc_sourcemap::SourceMapSection::new(
offset,
// Urls are deprecated and we don't accept them
None,
......@@ -573,7 +576,7 @@ impl SourceMap {
&& let DecodedMap::Regular(map) = &map.map.0
&& map.get_source_count() == 1
{
let source = map.sources().next().unwrap();
let source = map.sources().next().unwrap().clone();
*guessed_original_file = Some(RcStr::from(source));
}
......@@ -588,7 +591,10 @@ impl SourceMap {
let content = map.get_source_contents(src_id);
let (name, content) = name.zip(content)?;
Some(sourcemap_content_source(name.into(), content.into()))
Some(sourcemap_content_source(
name.clone().into(),
content.clone().into(),
))
});
}
......
......@@ -12,7 +12,7 @@ use turbo_tasks_fs::{
use crate::SOURCE_URL_PROTOCOL;
pub fn add_default_ignore_list(map: &mut sourcemap::SourceMap) {
pub fn add_default_ignore_list(map: &mut swc_sourcemap::SourceMap) {
let mut ignored_ids = HashSet::new();
for (source_id, source) in map.sources().enumerate() {
......
......@@ -588,11 +588,11 @@ fn generate_css_source_map(source_map: &parcel_sourcemap::SourceMap) -> Result<R
let mut builder = SourceMapBuilder::new(None);
for src in source_map.get_sources() {
builder.add_source(&format!("{SOURCE_URL_PROTOCOL}///{src}"));
builder.add_source(format!("{SOURCE_URL_PROTOCOL}///{src}").into());
}
for (idx, content) in source_map.get_sources_content().iter().enumerate() {
builder.set_source_contents(idx as _, Some(content));
builder.set_source_contents(idx as _, Some(content.clone().into()));
}
for m in source_map.get_mappings() {
......
......@@ -15,6 +15,7 @@ workspace = true
[dependencies]
anyhow = { workspace = true }
async-trait = { workspace = true }
bytes-str = { workspace = true }
data-encoding = { workspace = true }
either = { workspace = true }
indexmap = { workspace = true }
......@@ -29,7 +30,7 @@ regex = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, features = ["raw_value"] }
sourcemap = { workspace = true }
swc_sourcemap = { workspace = true }
smallvec = { workspace = true }
strsim = { workspace = true }
tokio = { workspace = true }
......
use std::{future::Future, sync::Arc};
use anyhow::{Context, Result, anyhow};
use bytes_str::BytesStr;
use rustc_hash::FxHashSet;
use swc_core::{
base::SwcComments,
......@@ -107,7 +108,7 @@ pub fn generate_js_source_map(
) -> Result<Rope> {
let original_source_map = original_source_map.map(|x| x.to_bytes());
let input_map = if let Some(original_source_map) = &original_source_map {
Some(sourcemap::lazy::decode(original_source_map)?.into_source_map()?)
Some(swc_sourcemap::lazy::decode(original_source_map)?.into_source_map()?)
} else {
None
};
......@@ -224,52 +225,58 @@ async fn parse_internal(
Ok(match &*content {
AssetContent::File(file) => match &*file.await? {
FileContent::NotFound => ParseResult::NotFound.cell(),
FileContent::Content(file) => match file.content().to_str() {
Ok(string) => {
let transforms = &*transforms.await?;
match parse_file_content(
string.into_owned(),
fs_path_vc,
fs_path,
ident,
source.ident().await?.query.clone(),
file_path_hash,
source,
ty,
transforms,
)
.await
{
Ok(result) => result,
Err(e) => {
return Err(e).context(anyhow!(
"Transforming and/or parsing of {} failed",
source.ident().to_string().await?
));
FileContent::Content(file) => {
match BytesStr::from_utf8(file.content().clone().into_bytes()) {
Ok(string) => {
let transforms = &*transforms.await?;
match parse_file_content(
string,
fs_path_vc,
fs_path,
ident,
source.ident().await?.query.clone(),
file_path_hash,
source,
ty,
transforms,
)
.await
{
Ok(result) => result,
Err(e) => {
return Err(e).context(anyhow!(
"Transforming and/or parsing of {} failed",
source.ident().to_string().await?
));
}
}
}
}
Err(error) => {
let error: RcStr = PrettyPrintError(&error).to_string().into();
ReadSourceIssue {
source,
error: error.clone(),
}
.resolved_cell()
.emit();
ParseResult::Unparseable {
messages: Some(vec![error]),
Err(error) => {
let error: RcStr = PrettyPrintError(
&anyhow::anyhow!(error).context("failed to convert rope into string"),
)
.to_string()
.into();
ReadSourceIssue {
source,
error: error.clone(),
}
.resolved_cell()
.emit();
ParseResult::Unparseable {
messages: Some(vec![error]),
}
.cell()
}
.cell()
}
},
}
},
AssetContent::Redirect { .. } => ParseResult::Unparseable { messages: None }.cell(),
})
}
async fn parse_file_content(
string: String,
string: BytesStr,
fs_path_vc: Vc<FileSystemPath>,
fs_path: &FileSystemPath,
ident: &str,
......@@ -450,7 +457,7 @@ async fn parse_file_content(
None
};
let messages =
Some(messages.unwrap_or_else(|| vec![String::clone(&fm.src).into()]));
Some(messages.unwrap_or_else(|| vec![fm.src.clone().into()]));
return Ok(ParseResult::Unparseable { messages });
}
......
......@@ -225,7 +225,7 @@ mod tests {
#[test]
fn path_visitor() {
run_test(false, |cm, _handler| {
let fm = cm.new_source_file(FileName::Anon.into(), "('foo', 'bar', ['baz']);".into());
let fm = cm.new_source_file(FileName::Anon.into(), "('foo', 'bar', ['baz']);");
let m = parse(&fm);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment