Unverified Commit 2d1d5268 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Upgrade to swc 70 (#94814)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Signed commits

- This repository requires verified commit signatures on protected
branches.
- If this pull request is blocked for unsigned commits, re-sign the
commits and force-push the branch.
- A `Signed-off-by` line in the commit message is not enough.


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------
Co-authored-by: 's avatarWill Binns-Smith <wbinnssmith@gmail.com>
parent b783793e
This diff is collapsed.
......@@ -209,30 +209,30 @@ turbopack-trace-server = { path = "turbopack/crates/turbopack-trace-server" }
turbopack-trace-utils = { path = "turbopack/crates/turbopack-trace-utils" }
turbopack-wasm = { path = "turbopack/crates/turbopack-wasm" }
react_compiler_swc = { version = "0.1.5", package = "nextjs_react_compiler_swc" }
react_compiler = { version = "0.1.5", package = "nextjs_react_compiler" }
swc_ecma_react_compiler = "19.1.2"
react_compiler = { version = "0.1.5", package = "forked_react_compiler" }
# SWC crates
swc_core = { version = "65.0.3", default-features = false, features = [
swc_core = { version = "69.0.0", default-features = false, features = [
"ecma_loader_lru",
"ecma_loader_parking_lot",
"parallel_rayon",
] }
swc_plugin_backend_wasmtime = "9.0.0"
testing = "22.0.0"
swc_plugin_backend_wasmtime = "11.0.0"
testing = "24.0.0"
# Keep consistent with preset_env_base through swc_core
browserslist-rs = "0.19.0"
mdxjs = "1.0.3"
modularize_imports = "4.0.0"
styled_components = "4.0.0"
styled_jsx = "4.0.0"
swc_emotion = "4.0.0"
swc_relay = "4.0.0"
react_remove_properties = "4.0.0"
remove_console = "4.0.0"
preset_env_base = "7.0.0"
modularize_imports = "9.0.0"
styled_components = "9.0.0"
styled_jsx = "9.0.0"
swc_emotion = "9.0.0"
swc_relay = "9.0.0"
react_remove_properties = "9.0.0"
remove_console = "9.0.0"
preset_env_base = "8.0.0"
# General Deps
......
......@@ -187,7 +187,7 @@ where
if let Some(config) = &opts.styled_components {
program.mutate(styled_components::styled_components(
Some(&file_path_str),
file.src_hash,
file.src_hash(),
config,
NoopComments,
))
......@@ -209,7 +209,7 @@ where
program.mutate(swc_emotion::emotion(
config,
path,
file.src_hash as u32,
file.src_hash() as u32,
cm.clone(),
comments.clone(),
));
......
......@@ -102,12 +102,11 @@ impl SwcEcmaTransformPluginsTransformer {
impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
#[tracing::instrument(level = tracing::Level::TRACE, name = "swc_ecma_transform_plugin", skip_all)]
async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
use std::{cell::RefCell, rc::Rc, sync::Arc};
use std::sync::Arc;
use anyhow::Context;
use swc_core::{
common::{
comments::SingleThreadedComments,
plugin::{
metadata::TransformPluginMetadataContext, serialized::PluginSerializedBytes,
},
......@@ -141,22 +140,8 @@ impl CustomTransformer for SwcEcmaTransformPluginsTransformer {
// depends on the src's comments availability. For now, check naively if leading
// / trailing comments are empty.
let comments = if should_enable_comments_proxy {
// Plugin only able to accept singlethreaded comments, interop from
// multithreaded comments.
let mut leading = swc_core::common::comments::SingleThreadedCommentsMapInner::default();
ctx.comments.leading.as_ref().into_iter().for_each(|c| {
leading.insert(*c.key(), c.value().clone());
});
let mut trailing =
swc_core::common::comments::SingleThreadedCommentsMapInner::default();
ctx.comments.trailing.as_ref().into_iter().for_each(|c| {
trailing.insert(*c.key(), c.value().clone());
});
Some(SingleThreadedComments::from_leading_and_trailing(
Rc::new(RefCell::new(leading)),
Rc::new(RefCell::new(trailing)),
Some(turbopack_ecmascript::swc_comments_to_single_threaded(
ctx.comments,
))
} else {
None
......
......@@ -43,7 +43,7 @@ regex = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, features = ["raw_value"] }
react_compiler_swc = { workspace = true }
swc_ecma_react_compiler = { workspace = true }
react_compiler = { workspace = true }
next-custom-transforms = { workspace = true, default-features = false }
swc_sourcemap = { workspace = true }
......
......@@ -125,6 +125,7 @@ use crate::{
pub use crate::{
references::{AnalyzeEcmascriptModuleResult, TURBOPACK_HELPER},
static_code::StaticEcmascriptCode,
swc_comments::swc_comments_to_single_threaded,
transform::{
CustomTransformer, EcmascriptInputTransform, EcmascriptInputTransforms, TransformContext,
TransformPlugin,
......
use std::{borrow::Cow, cell::RefCell, mem::take};
use std::{borrow::Cow, cell::RefCell, mem::take, rc::Rc};
use rustc_hash::FxHashMap;
use swc_core::{
base::SwcComments,
common::{
BytePos,
comments::{Comment, CommentKind, Comments},
comments::{Comment, CommentKind, Comments, SingleThreadedComments},
},
};
use crate::source_map::extract_source_mapping_url;
/// Converts multi-threaded [`SwcComments`] into [`SingleThreadedComments`] by
/// copying all entries. Required when APIs (e.g. `swc_ecma_react_compiler`)
/// only accept the single-threaded variant.
pub fn swc_comments_to_single_threaded(comments: &SwcComments) -> SingleThreadedComments {
let mut leading = FxHashMap::default();
for entry in comments.leading.as_ref() {
leading.insert(*entry.key(), entry.value().clone());
}
let mut trailing = FxHashMap::default();
for entry in comments.trailing.as_ref() {
trailing.insert(*entry.key(), entry.value().clone());
}
SingleThreadedComments::from_leading_and_trailing(
Rc::new(RefCell::new(leading)),
Rc::new(RefCell::new(trailing)),
)
}
/// Immutable version of [SwcComments] which doesn't allow mutation. The `take`
/// variants are still implemented, but do not mutate the content. They are used
/// by the SWC Emitter.
......
......@@ -186,7 +186,7 @@ pub struct TransformContext<'a> {
pub file_path: FileSystemPath,
pub source: ResolvedVc<Box<dyn Source>>,
/// Original source text; used by transforms that need the raw text (e.g.
/// `react_compiler_swc`).
/// `swc_ecma_react_compiler`).
pub source_text: &'a str,
/// The value of `process.env.NODE_ENV` for this compilation
/// (e.g. `"development"` or `"production"`).
......@@ -454,24 +454,31 @@ async fn apply_rust_react_compiler(
compilation_mode: ReactCompilerCompilationMode,
target: ReactCompilerTarget,
) -> Result<HelperData> {
let Program::Module(module) = program else {
let Program::Module(_) = program else {
return Ok(helpers);
};
let options = react_compiler_swc_options(ctx, compilation_mode, target);
let result = react_compiler_swc::transform(module, ctx.source_text, options);
let single_threaded_comments =
crate::swc_comments::swc_comments_to_single_threaded(ctx.comments);
let result = swc_ecma_react_compiler::transform(
program,
swc_ecma_react_compiler::SourceType::from_program(program),
ctx.source_text,
Some(&single_threaded_comments),
react_compiler_options(ctx, compilation_mode, target),
);
// TODO: Emit these diagnostics with an Info level once there's a way of adjusting log levels in
// general. By default React Compiler is silent, as de-opts align closely with feedback
// rom tools like React's lint rules.
// from tools like React's lint rules.
if let Some(compiled_module) = result.module {
*program = Program::Module(compiled_module);
if let Some(compiled_program) = result.program {
*program = compiled_program;
// TODO(react-compiler-swc): The Rust React Compiler emits every identifier with
// `SyntaxContext::empty()` in `convert_ast_reverse.rs`.
//
// Remove this once `nextjs_react_compiler_swc`
// Remove this once `swc_ecma_react_compiler`
// preserves/assigns contexts on the converted AST.
program.mutate(swc_core::ecma::transforms::base::resolver(
ctx.unresolved_mark,
......@@ -483,7 +490,7 @@ async fn apply_rust_react_compiler(
Ok(helpers)
}
fn react_compiler_swc_options(
fn react_compiler_options(
ctx: &TransformContext<'_>,
compilation_mode: ReactCompilerCompilationMode,
target: ReactCompilerTarget,
......
......@@ -2,7 +2,7 @@
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/source_maps/react-compiler/input/Component.jsx"],"sourcesContent":["import { useState } from 'react'\n\nexport function Counter({ initialCount }) {\n const [count, setCount] = useState(initialCount)\n const doubled = count * 2\n return (\n <div>\n <p>{count}</p>\n <p>{doubled}</p>\n <button onClick={() => setCount(count + 1)}>increment</button>\n </div>\n )\n}\n"],"names":[],"mappings":";;;;;AAAA;AAAA;;;;AAEO"}},
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/source_maps/react-compiler/input/Component.jsx"],"sourcesContent":["import { useState } from 'react'\n\nexport function Counter({ initialCount }) {\n const [count, setCount] = useState(initialCount)\n const doubled = count * 2\n return (\n <div>\n <p>{count}</p>\n <p>{doubled}</p>\n <button onClick={() => setCount(count + 1)}>increment</button>\n </div>\n )\n}\n"],"names":[],"mappings":";;;;;;AAAA;;;;AAEO"}},
{"offset": {"line": 72, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/source_maps/react-compiler/input/index.js"],"sourcesContent":["import { Counter } from './Component.jsx'\n\nconsole.log(Counter)\n"],"names":["console","log"],"mappings":";AAAA;;AAEAA,QAAQC,GAAG,CAAC,8NAAO"}},
{"offset": {"line": 80, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/node_modules/react/jsx-dev-runtime.js"],"sourcesContent":["export function jsxDEV() {\n return 'purposefully empty stub for react/jsx-dev-runtime.js'\n}\n"],"names":["jsxDEV"],"mappings":";;;;AAAO,SAASA;IACd,OAAO;AACT","ignoreList":[0]}},
{"offset": {"line": 91, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/node_modules/react/compiler-runtime.js"],"sourcesContent":["export function c() {\n return 'purposefully empty stub for react/compiler-runtime.js'\n}\n"],"names":["c"],"mappings":";;;;AAAO,SAASA;IACd,OAAO;AACT","ignoreList":[0]}},
......
......@@ -303,8 +303,6 @@ impl ModuleOptions {
let mut ecma_preprocess = vec![];
let mut postprocess = vec![];
// Runs first so it sees the original source text (text-bridge re-parses after
// react_compiler_swc).
if let Some(compilation_mode) = enable_rust_react_compiler {
ecma_preprocess.push(EcmascriptInputTransform::ReactCompilerRust {
compilation_mode,
......
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