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