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

perf: Make `next-page-static-info` use `Atom` instead of `String` (#75587)

### What?

Use `swc_atoms::Atom` instead of `String` in `next-swc`. 

### Why?

`Atom` does not allocate if another instance has the same value, meaning that `clone()` is a single atomic operation. But `String` allocates regardless of any other occurrence. 
parent 90090ba4
...@@ -4,7 +4,7 @@ use next_custom_transforms::transforms::page_static_info::{ ...@@ -4,7 +4,7 @@ use next_custom_transforms::transforms::page_static_info::{
collect_exports, extract_exported_const_values, Const, collect_exports, extract_exported_const_values, Const,
}; };
use serde_json::Value; use serde_json::Value;
use swc_core::ecma::ast::Program; use swc_core::{atoms::atom, ecma::ast::Program};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::{ModuleRule, ModuleRuleEffect}; use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
...@@ -51,7 +51,7 @@ impl CustomTransformer for NextPageStaticInfo { ...@@ -51,7 +51,7 @@ impl CustomTransformer for NextPageStaticInfo {
async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> { async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
if let Some(collected_exports) = collect_exports(program)? { if let Some(collected_exports) = collect_exports(program)? {
let mut properties_to_extract = collected_exports.extra_properties.clone(); let mut properties_to_extract = collected_exports.extra_properties.clone();
properties_to_extract.insert("config".to_string()); properties_to_extract.insert(atom!("config"));
let extracted = extract_exported_const_values(program, properties_to_extract); let extracted = extract_exported_const_values(program, properties_to_extract);
...@@ -82,7 +82,8 @@ impl CustomTransformer for NextPageStaticInfo { ...@@ -82,7 +82,8 @@ impl CustomTransformer for NextPageStaticInfo {
} }
if is_app_page { if is_app_page {
if let Some(Some(Const::Value(Value::Object(config_obj)))) = extracted.get("config") if let Some(Some(Const::Value(Value::Object(config_obj)))) =
extracted.get(&atom!("config"))
{ {
let mut messages = vec![format!( let mut messages = vec![format!(
"Page config in {} is deprecated. Replace `export const config=…` with \ "Page config in {} is deprecated. Replace `export const config=…` with \
...@@ -110,7 +111,7 @@ impl CustomTransformer for NextPageStaticInfo { ...@@ -110,7 +111,7 @@ impl CustomTransformer for NextPageStaticInfo {
} }
} }
if collected_exports.directives.contains("client") if collected_exports.directives.contains(&atom!("client"))
&& collected_exports.generate_static_params && collected_exports.generate_static_params
&& is_app_page && is_app_page
{ {
......
use std::collections::{HashMap, HashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use serde_json::{Map, Number, Value}; use serde_json::{Map, Number, Value};
use swc_core::{ use swc_core::{
atoms::Atom,
common::{Mark, SyntaxContext}, common::{Mark, SyntaxContext},
ecma::{ ecma::{
ast::{ ast::{
...@@ -22,12 +22,12 @@ pub enum Const { ...@@ -22,12 +22,12 @@ pub enum Const {
} }
pub(crate) struct CollectExportedConstVisitor { pub(crate) struct CollectExportedConstVisitor {
pub properties: HashMap<String, Option<Const>>, pub properties: FxHashMap<Atom, Option<Const>>,
expr_ctx: ExprCtx, expr_ctx: ExprCtx,
} }
impl CollectExportedConstVisitor { impl CollectExportedConstVisitor {
pub fn new(properties_to_extract: HashSet<String>) -> Self { pub fn new(properties_to_extract: FxHashSet<Atom>) -> Self {
Self { Self {
properties: properties_to_extract properties: properties_to_extract
.into_iter() .into_iter()
...@@ -60,7 +60,7 @@ impl Visit for CollectExportedConstVisitor { ...@@ -60,7 +60,7 @@ impl Visit for CollectExportedConstVisitor {
.. ..
} = decl } = decl
{ {
let id = id.sym.as_ref(); let id = &id.sym;
if let Some(prop) = self.properties.get_mut(id) { if let Some(prop) = self.properties.get_mut(id) {
*prop = extract_value(self.expr_ctx, init, id.to_string()); *prop = extract_value(self.expr_ctx, init, id.to_string());
}; };
......
use std::collections::HashSet; use std::collections::HashSet;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use swc_core::ecma::{ use swc_core::{
ast::{ atoms::atom,
Decl, ExportDecl, ExportNamedSpecifier, ExportSpecifier, Expr, ExprOrSpread, ExprStmt, Lit, ecma::{
ModuleExportName, ModuleItem, NamedExport, Pat, Stmt, Str, VarDeclarator, ast::{
Decl, ExportDecl, ExportNamedSpecifier, ExportSpecifier, Expr, ExprOrSpread, ExprStmt,
Lit, ModuleExportName, ModuleItem, NamedExport, Pat, Stmt, Str, VarDeclarator,
},
visit::{Visit, VisitWith},
}, },
visit::{Visit, VisitWith},
}; };
use super::{ExportInfo, ExportInfoWarning}; use super::{ExportInfo, ExportInfoWarning};
...@@ -46,11 +49,11 @@ impl Visit for CollectExportsVisitor { ...@@ -46,11 +49,11 @@ impl Visit for CollectExportsVisitor {
if is_directive { if is_directive {
if value == "use server" { if value == "use server" {
let export_info = self.export_info.get_or_insert(Default::default()); let export_info = self.export_info.get_or_insert(Default::default());
export_info.directives.insert("server".to_string()); export_info.directives.insert(atom!("server"));
} }
if value == "use client" { if value == "use client" {
let export_info = self.export_info.get_or_insert(Default::default()); let export_info = self.export_info.get_or_insert(Default::default());
export_info.directives.insert("client".to_string()); export_info.directives.insert(atom!("client"));
} }
} }
} else { } else {
...@@ -86,7 +89,7 @@ impl Visit for CollectExportsVisitor { ...@@ -86,7 +89,7 @@ impl Visit for CollectExportsVisitor {
let export_info = self.export_info.get_or_insert(Default::default()); let export_info = self.export_info.get_or_insert(Default::default());
export_info.runtime = decl.init.as_ref().and_then(|init| { export_info.runtime = decl.init.as_ref().and_then(|init| {
if let Expr::Lit(Lit::Str(Str { value, .. })) = &**init { if let Expr::Lit(Lit::Str(Str { value, .. })) = &**init {
Some(value.to_string()) Some(value.clone())
} else { } else {
None None
} }
...@@ -102,18 +105,18 @@ impl Visit for CollectExportsVisitor { ...@@ -102,18 +105,18 @@ impl Visit for CollectExportsVisitor {
{ {
let export_info = let export_info =
self.export_info.get_or_insert(Default::default()); self.export_info.get_or_insert(Default::default());
export_info.preferred_region.push(value.to_string()); export_info.preferred_region.push(value.clone());
} }
} }
} else if let Expr::Lit(Lit::Str(Str { value, .. })) = &**init { } else if let Expr::Lit(Lit::Str(Str { value, .. })) = &**init {
let export_info = let export_info =
self.export_info.get_or_insert(Default::default()); self.export_info.get_or_insert(Default::default());
export_info.preferred_region.push(value.to_string()); export_info.preferred_region.push(value.clone());
} }
} }
} else { } else {
let export_info = self.export_info.get_or_insert(Default::default()); let export_info = self.export_info.get_or_insert(Default::default());
export_info.extra_properties.insert(id.sym.to_string()); export_info.extra_properties.insert(id.sym.clone());
} }
} }
} }
...@@ -169,16 +172,15 @@ impl Visit for CollectExportsVisitor { ...@@ -169,16 +172,15 @@ impl Visit for CollectExportsVisitor {
if export_info.runtime.is_none() && value.sym == "runtime" { if export_info.runtime.is_none() && value.sym == "runtime" {
export_info.warnings.push(ExportInfoWarning::new( export_info.warnings.push(ExportInfoWarning::new(
value.sym.to_string(), value.sym.clone(),
"it was not assigned to a string literal".to_string(), "it was not assigned to a string literal",
)); ));
} }
if export_info.preferred_region.is_empty() && value.sym == "preferredRegion" { if export_info.preferred_region.is_empty() && value.sym == "preferredRegion" {
export_info.warnings.push(ExportInfoWarning::new( export_info.warnings.push(ExportInfoWarning::new(
value.sym.to_string(), value.sym.clone(),
"it was not assigned to a string literal or an array of string literals" "it was not assigned to a string literal or an array of string literals",
.to_string(),
)); ));
} }
} }
......
use std::collections::{HashMap, HashSet};
use anyhow::Result; use anyhow::Result;
pub use collect_exported_const_visitor::Const; pub use collect_exported_const_visitor::Const;
use collect_exports_visitor::CollectExportsVisitor; use collect_exports_visitor::CollectExportsVisitor;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::{ use swc_core::{
atoms::Atom,
base::SwcComments, base::SwcComments,
common::GLOBALS, common::GLOBALS,
ecma::{ast::Program, visit::VisitWith}, ecma::{ast::Program, visit::VisitWith},
...@@ -38,33 +38,33 @@ pub struct PageStaticInfo { ...@@ -38,33 +38,33 @@ pub struct PageStaticInfo {
pub amp: Option<Amp>, pub amp: Option<Amp>,
} }
#[derive(Debug, Default, Serialize, Deserialize)] #[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ExportInfoWarning { pub struct ExportInfoWarning {
pub key: String, pub key: Atom,
pub message: String, pub message: &'static str,
} }
impl ExportInfoWarning { impl ExportInfoWarning {
pub fn new(key: String, message: String) -> Self { pub fn new(key: Atom, message: &'static str) -> Self {
Self { key, message } Self { key, message }
} }
} }
#[derive(Debug, Default, Serialize, Deserialize)] #[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ExportInfo { pub struct ExportInfo {
pub ssr: bool, pub ssr: bool,
pub ssg: bool, pub ssg: bool,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub runtime: Option<String>, pub runtime: Option<Atom>,
#[serde(skip_serializing_if = "Vec::is_empty")] #[serde(skip_serializing_if = "Vec::is_empty")]
pub preferred_region: Vec<String>, pub preferred_region: Vec<Atom>,
pub generate_image_metadata: Option<bool>, pub generate_image_metadata: Option<bool>,
pub generate_sitemaps: Option<bool>, pub generate_sitemaps: Option<bool>,
pub generate_static_params: bool, pub generate_static_params: bool,
pub extra_properties: HashSet<String>, pub extra_properties: FxHashSet<Atom>,
pub directives: HashSet<String>, pub directives: FxHashSet<Atom>,
/// extra properties to bubble up warning messages from visitor, /// extra properties to bubble up warning messages from visitor,
/// since this isn't a failure to abort the process. /// since this isn't a failure to abort the process.
pub warnings: Vec<ExportInfoWarning>, pub warnings: Vec<ExportInfoWarning>,
...@@ -209,8 +209,8 @@ pub fn collect_rsc_module_info( ...@@ -209,8 +209,8 @@ pub fn collect_rsc_module_info(
/// error. /// error.
pub fn extract_exported_const_values( pub fn extract_exported_const_values(
source_ast: &Program, source_ast: &Program,
properties_to_extract: HashSet<String>, properties_to_extract: FxHashSet<Atom>,
) -> HashMap<String, Option<Const>> { ) -> FxHashMap<Atom, Option<Const>> {
GLOBALS.set(&Default::default(), || { GLOBALS.set(&Default::default(), || {
let mut visitor = let mut visitor =
collect_exported_const_visitor::CollectExportedConstVisitor::new(properties_to_extract); collect_exported_const_visitor::CollectExportedConstVisitor::new(properties_to_extract);
......
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