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

perf(es/react): Use proper string types for react configuration #9949

Merged
merged 36 commits into from
Jan 26, 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
7 changes: 7 additions & 0 deletions .changeset/shiny-maps-film.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
swc_common: patch
swc_ecma_transforms_base: patch
swc_ecma_transforms_react: major
---

perf(es/react): Use proper string types for react configuration
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/swc_bundler/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![deny(clippy::all)]
#![allow(unstable_name_collisions)]
#![allow(clippy::mutable_key_type)]
#![cfg_attr(not(test), allow(unused))]

pub use self::{
bundler::{Bundle, BundleKind, Bundler, Config, ModuleType},
Expand Down
1 change: 1 addition & 0 deletions crates/swc_common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
//! Use `ahash` instead of `rustc_hash` for `AHashMap` and `AHashSet`.
#![deny(clippy::all)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(not(test), allow(unused))]

use std::fmt::Debug;

Expand Down
1 change: 1 addition & 0 deletions crates/swc_ecma_transforms/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ concurrent = [
"swc_ecma_transforms_compat/concurrent",
"swc_ecma_transforms_optimization/concurrent",
"swc_ecma_transforms_react/concurrent",
"swc_ecma_transforms_typescript/concurrent",
]
module = ["swc_ecma_transforms_module"]
multi-module-decorator = ["swc_ecma_transforms_proposal/multi-module"]
Expand Down
1 change: 1 addition & 0 deletions crates/swc_ecma_transforms_base/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// #![cfg_attr(test, deny(warnings))]
#![allow(clippy::mutable_key_type)]
#![cfg_attr(not(test), allow(unused))]

pub use self::resolver::resolver;

Expand Down
17 changes: 9 additions & 8 deletions crates/swc_ecma_transforms_react/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,19 @@ version = "7.0.0"
bench = false

[features]
concurrent = ["rayon"]
concurrent = ["swc_common/concurrent", "rayon"]
default = ["serde-impl"]
serde-impl = ["serde"]

[dependencies]
base64 = { workspace = true }
dashmap = { workspace = true }
indexmap = { workspace = true }
once_cell = { workspace = true }
rayon = { workspace = true, optional = true }
serde = { workspace = true, features = ["derive"], optional = true }
sha1 = { workspace = true }
base64 = { workspace = true }
dashmap = { workspace = true }
indexmap = { workspace = true }
once_cell = { workspace = true }
rayon = { workspace = true, optional = true }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"], optional = true }
sha1 = { workspace = true }

string_enum = { version = "1.0.0", path = "../string_enum" }
swc_allocator = { version = "2.0.0", path = "../swc_allocator", default-features = false }
Expand Down
101 changes: 73 additions & 28 deletions crates/swc_ecma_transforms_react/src/jsx/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
#![allow(clippy::redundant_allocation)]

use std::{borrow::Cow, iter, iter::once, sync::Arc};
use std::{
borrow::Cow,
iter::{self, once},
sync::RwLock,
};

use once_cell::sync::Lazy;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use string_enum::StringEnum;
use swc_atoms::{Atom, JsWord};
use swc_atoms::{atom, Atom, JsWord};
use swc_common::{
comments::{Comment, CommentKind, Comments},
errors::HANDLER,
Expand Down Expand Up @@ -56,12 +62,12 @@ pub struct Options {

/// For automatic runtime
#[serde(default)]
pub import_source: Option<String>,
pub import_source: Option<Atom>,

#[serde(default)]
pub pragma: Option<String>,
pub pragma: Option<Lrc<String>>,
#[serde(default)]
pub pragma_frag: Option<String>,
pub pragma_frag: Option<Lrc<String>>,

#[serde(default)]
pub throw_if_namespace: Option<bool>,
Expand Down Expand Up @@ -93,16 +99,31 @@ pub struct Options {
pub refresh: Option<RefreshOptions>,
}

pub fn default_import_source() -> String {
"react".into()
#[cfg(feature = "concurrent")]
macro_rules! static_str {
($s:expr) => {{
static VAL: Lazy<Lrc<String>> = Lazy::new(|| Lrc::new($s.into()));
VAL.clone()
}};
}

#[cfg(not(feature = "concurrent"))]
macro_rules! static_str {
($s:expr) => {
Lrc::new($s.into())
};
}

pub fn default_import_source() -> Atom {
atom!("react")
}

pub fn default_pragma() -> String {
"React.createElement".into()
pub fn default_pragma() -> Lrc<String> {
static_str!("React.createElement")
}

pub fn default_pragma_frag() -> String {
"React.Fragment".into()
pub fn default_pragma_frag() -> Lrc<String> {
static_str!("React.Fragment")
}

fn default_throw_if_namespace() -> bool {
Expand All @@ -113,10 +134,10 @@ fn default_throw_if_namespace() -> bool {
pub fn parse_expr_for_jsx(
cm: &SourceMap,
name: &str,
src: String,
src: Lrc<String>,
top_level_mark: Mark,
) -> Arc<Box<Expr>> {
let fm = cm.new_source_file(
) -> Lrc<Box<Expr>> {
let fm = cm.new_source_file_from(
FileName::Internal(format!("jsx-config-{}.js", name)).into(),
src,
);
Expand All @@ -142,7 +163,7 @@ pub fn parse_expr_for_jsx(
apply_mark(&mut expr, top_level_mark);
expr
})
.map(Arc::new)
.map(Lrc::new)
.unwrap_or_else(|()| {
panic!(
"failed to parse jsx option {}: '{}' is not an expression",
Expand Down Expand Up @@ -198,10 +219,7 @@ where
top_level_mark,
unresolved_mark,
runtime: options.runtime.unwrap_or_default(),
import_source: options
.import_source
.unwrap_or_else(default_import_source)
.into(),
import_source: options.import_source.unwrap_or_else(default_import_source),
import_jsx: None,
import_jsxs: None,
import_fragment: None,
Expand Down Expand Up @@ -239,7 +257,7 @@ where

runtime: Runtime,
/// For automatic runtime.
import_source: JsWord,
import_source: Atom,
/// For automatic runtime.
import_jsx: Option<Ident>,
/// For automatic runtime.
Expand All @@ -250,9 +268,9 @@ where
import_fragment: Option<Ident>,
top_level_node: bool,

pragma: Arc<Box<Expr>>,
pragma: Lrc<Box<Expr>>,
comments: Option<C>,
pragma_frag: Arc<Box<Expr>>,
pragma_frag: Lrc<Box<Expr>>,
development: bool,
throw_if_namespace: bool,
}
Expand All @@ -262,13 +280,13 @@ pub struct JsxDirectives {
pub runtime: Option<Runtime>,

/// For automatic runtime.
pub import_source: Option<JsWord>,
pub import_source: Option<Atom>,

/// Parsed from `@jsx`
pub pragma: Option<Arc<Box<Expr>>>,
pub pragma: Option<Lrc<Box<Expr>>>,

/// Parsed from `@jsxFrag`
pub pragma_frag: Option<Arc<Box<Expr>>>,
pub pragma_frag: Option<Lrc<Box<Expr>>>,
}

fn respan(e: &mut Expr, span: Span) {
Expand Down Expand Up @@ -335,7 +353,7 @@ impl JsxDirectives {
Some("@jsxImportSource") => {
if let Some(src) = val {
res.runtime = Some(Runtime::Automatic);
res.import_source = Some(src.into());
res.import_source = Some(Atom::new(src));
}
}
Some("@jsxFrag") => {
Expand All @@ -345,7 +363,7 @@ impl JsxDirectives {
let mut e = (*parse_expr_for_jsx(
cm,
"module-jsx-pragma-frag",
src.to_string(),
cache_source(src),
top_level_mark,
))
.clone();
Expand All @@ -361,7 +379,7 @@ impl JsxDirectives {
let mut e = (*parse_expr_for_jsx(
cm,
"module-jsx-pragma",
src.to_string(),
cache_source(src),
top_level_mark,
))
.clone();
Expand All @@ -380,6 +398,33 @@ impl JsxDirectives {
}
}

#[cfg(feature = "concurrent")]
fn cache_source(src: &str) -> Lrc<String> {
static CACHE: Lazy<RwLock<FxHashMap<String, Lrc<String>>>> =
Lazy::new(|| RwLock::new(FxHashMap::default()));

{
let cache = CACHE.write().unwrap();

if let Some(cached) = cache.get(src) {
return cached.clone();
}
}

let cached = Lrc::new(src.to_string());
{
let mut cache = CACHE.write().unwrap();
cache.insert(src.to_string(), cached.clone());
}
cached
}

#[cfg(not(feature = "concurrent"))]
fn cache_source(src: &str) -> Lrc<String> {
// We cannot cache because Rc does not implement Send.
Lrc::new(src.to_string())
}

fn is_valid_for_pragma(s: &str) -> bool {
if s.is_empty() {
return false;
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_ecma_transforms_react/src/jsx/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ test!(
|t| tr(
t,
Options {
pragma: Some("dom".into()),
pragma: Some(Lrc::new("dom".into())),
..Default::default()
},
Mark::fresh(Mark::root())
Expand Down Expand Up @@ -808,7 +808,7 @@ test!(
|t| tr(
t,
Options {
pragma: Some("h".into()),
pragma: Some(Lrc::new("h".into())),
throw_if_namespace: false.into(),
..Default::default()
},
Expand Down
1 change: 1 addition & 0 deletions crates/swc_ecma_transforms_react/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![allow(clippy::mutable_key_type)]
#![allow(clippy::arc_with_non_send_sync)]
#![allow(rustc::untranslatable_diagnostic_trivial)]
#![cfg_attr(not(feature = "concurrent"), allow(unused))]

use swc_common::{comments::Comments, sync::Lrc, Mark, SourceMap};
use swc_ecma_ast::Pass;
Expand Down
13 changes: 7 additions & 6 deletions crates/swc_ecma_transforms_react/src/refresh/options.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
use serde::{Deserialize, Deserializer, Serialize};
use swc_atoms::{atom, Atom};
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
pub struct RefreshOptions {
#[serde(default = "default_refresh_reg")]
pub refresh_reg: String,
pub refresh_reg: Atom,
#[serde(default = "default_refresh_sig")]
pub refresh_sig: String,
pub refresh_sig: Atom,
#[serde(default = "default_emit_full_signatures")]
pub emit_full_signatures: bool,
}

fn default_refresh_reg() -> String {
"$RefreshReg$".to_string()
fn default_refresh_reg() -> Atom {
atom!("$RefreshReg$")
}
fn default_refresh_sig() -> String {
"$RefreshSig$".to_string()
fn default_refresh_sig() -> Atom {
atom!("$RefreshSig$")
}
fn default_emit_full_signatures() -> bool {
// Prefer to hash when we can
Expand Down
4 changes: 2 additions & 2 deletions crates/swc_ecma_transforms_react/src/refresh/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -710,8 +710,8 @@ test!(
refresh(
true,
Some(RefreshOptions {
refresh_reg: "import_meta_refreshReg".to_string(),
refresh_sig: "import_meta_refreshSig".to_string(),
refresh_reg: "import_meta_refreshReg".into(),
refresh_sig: "import_meta_refreshSig".into(),
emit_full_signatures: true,
}),
t.cm.clone(),
Expand Down
8 changes: 6 additions & 2 deletions crates/swc_ecma_transforms_typescript/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@ version = "7.0.0"
[lib]
bench = false

[features]
concurrent = ["swc_common/concurrent"]

[dependencies]
serde = { workspace = true, features = ["derive"] }
once_cell = { workspace = true }
ryu-js = { workspace = true }
serde = { workspace = true, features = ["derive"] }

ryu-js = { workspace = true }
swc_atoms = { version = "3.0.3", path = "../swc_atoms" }
swc_common = { version = "5.0.0", path = "../swc_common" }
swc_ecma_ast = { version = "5.0.3", path = "../swc_ecma_ast" }
Expand Down
5 changes: 3 additions & 2 deletions crates/swc_ecma_transforms_typescript/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use serde::{Deserialize, Serialize};
use swc_common::sync::Lrc;

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -39,11 +40,11 @@ pub struct Config {
pub struct TsxConfig {
/// Note: this pass handle jsx directives in comments
#[serde(default)]
pub pragma: Option<String>,
pub pragma: Option<Lrc<String>>,

/// Note: this pass handle jsx directives in comments
#[serde(default)]
pub pragma_frag: Option<String>,
pub pragma_frag: Option<Lrc<String>>,
}

#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
Expand Down
Loading
Loading