Unverified Commit d7c6ff6c authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: remove GlobalTypeofs AST pass (#83479)

Port `EcmascriptInputTransform::GlobalTypeofs` from an extra AST pass to using the `CompileTimeInfo` replacement infrastructure.

Ideally, we'd get rid of the `enable_typeof_window_inlining` option entirely. But currently you cannot have different `CompileTimeInfo` per module asset context, so it's not possible to different replacements per directory (which is what we unfortunately want for `typeof window` replacements).

Basically closes PACK-5049
parent 3b8ce1a4
...@@ -8,7 +8,7 @@ use turbo_tasks_fs::FileSystemPath; ...@@ -8,7 +8,7 @@ use turbo_tasks_fs::FileSystemPath;
use turbopack::{ use turbopack::{
css::chunk::CssChunkType, css::chunk::CssChunkType,
module_options::{ module_options::{
CssOptionsContext, EcmascriptOptionsContext, JsxTransformOptions, ModuleRule, TypeofWindow, CssOptionsContext, EcmascriptOptionsContext, JsxTransformOptions, ModuleRule,
TypescriptTransformOptions, module_options_context::ModuleOptionsContext, TypescriptTransformOptions, module_options_context::ModuleOptionsContext,
}, },
resolve_options_context::ResolveOptionsContext, resolve_options_context::ResolveOptionsContext,
...@@ -28,7 +28,7 @@ use turbopack_core::{ ...@@ -28,7 +28,7 @@ use turbopack_core::{
module_graph::export_usage::OptionExportUsageInfo, module_graph::export_usage::OptionExportUsageInfo,
resolve::{parse::Request, pattern::Pattern}, resolve::{parse::Request, pattern::Pattern},
}; };
use turbopack_ecmascript::chunk::EcmascriptChunkType; use turbopack_ecmascript::{TypeofWindow, chunk::EcmascriptChunkType};
use turbopack_node::{ use turbopack_node::{
execution_context::ExecutionContext, execution_context::ExecutionContext,
transforms::postcss::{PostCssConfigLocation, PostCssTransformOptions}, transforms::postcss::{PostCssConfigLocation, PostCssTransformOptions},
......
...@@ -9,7 +9,7 @@ use turbopack::{ ...@@ -9,7 +9,7 @@ use turbopack::{
css::chunk::CssChunkType, css::chunk::CssChunkType,
module_options::{ module_options::{
CssOptionsContext, EcmascriptOptionsContext, ExternalsTracingOptions, JsxTransformOptions, CssOptionsContext, EcmascriptOptionsContext, ExternalsTracingOptions, JsxTransformOptions,
ModuleOptionsContext, ModuleRule, TypeofWindow, TypescriptTransformOptions, ModuleOptionsContext, ModuleRule, TypescriptTransformOptions,
}, },
resolve_options_context::ResolveOptionsContext, resolve_options_context::ResolveOptionsContext,
transition::Transition, transition::Transition,
...@@ -28,7 +28,9 @@ use turbopack_core::{ ...@@ -28,7 +28,9 @@ use turbopack_core::{
module_graph::export_usage::OptionExportUsageInfo, module_graph::export_usage::OptionExportUsageInfo,
target::CompileTarget, target::CompileTarget,
}; };
use turbopack_ecmascript::{chunk::EcmascriptChunkType, references::esm::UrlRewriteBehavior}; use turbopack_ecmascript::{
TypeofWindow, chunk::EcmascriptChunkType, references::esm::UrlRewriteBehavior,
};
use turbopack_ecmascript_plugins::transform::directives::{ use turbopack_ecmascript_plugins::transform::directives::{
client::ClientDirectiveTransformer, client_disallowed::ClientDisallowedDirectiveTransformer, client::ClientDirectiveTransformer, client_disallowed::ClientDisallowedDirectiveTransformer,
}; };
......
...@@ -175,8 +175,27 @@ pub enum TreeShakingMode { ...@@ -175,8 +175,27 @@ pub enum TreeShakingMode {
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct OptionTreeShaking(pub Option<TreeShakingMode>); pub struct OptionTreeShaking(pub Option<TreeShakingMode>);
/// The constant to replace `typeof window` with.
#[derive(
Copy,
Clone,
PartialEq,
Eq,
Debug,
Hash,
Serialize,
Deserialize,
TraceRawVcs,
NonLocalValue,
TaskInput,
)]
pub enum TypeofWindow {
Object,
Undefined,
}
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
#[derive(Hash, Debug, Default, Copy, Clone)] #[derive(Debug, Default, Copy, Clone)]
pub struct EcmascriptOptions { pub struct EcmascriptOptions {
/// variant of tree shaking to use /// variant of tree shaking to use
pub tree_shaking_mode: Option<TreeShakingMode>, pub tree_shaking_mode: Option<TreeShakingMode>,
...@@ -203,6 +222,11 @@ pub struct EcmascriptOptions { ...@@ -203,6 +222,11 @@ pub struct EcmascriptOptions {
/// Whether the modules in this context are never chunked/codegen-ed, but only used for /// Whether the modules in this context are never chunked/codegen-ed, but only used for
/// tracing. /// tracing.
pub is_tracing: bool, pub is_tracing: bool,
// TODO this should just be handled via CompileTimeInfo FreeVarReferences, but then it
// (currently) wouldn't be possible to have different replacement values in user code vs
// node_modules.
/// Whether to replace `typeof window` with some constant value.
pub enable_typeof_window_inlining: Option<TypeofWindow>,
} }
#[turbo_tasks::value] #[turbo_tasks::value]
......
...@@ -67,8 +67,8 @@ use turbo_tasks::{ ...@@ -67,8 +67,8 @@ use turbo_tasks::{
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
compile_time_info::{ compile_time_info::{
CompileTimeDefineValue, CompileTimeInfo, DefinableNameSegment, FreeVarReference, CompileTimeDefineValue, CompileTimeDefines, CompileTimeInfo, DefinableNameSegment,
FreeVarReferences, FreeVarReferencesIndividual, InputRelativeConstant, FreeVarReference, FreeVarReferences, FreeVarReferencesIndividual, InputRelativeConstant,
}, },
environment::Rendering, environment::Rendering,
error::PrettyPrintError, error::PrettyPrintError,
...@@ -130,7 +130,7 @@ use super::{ ...@@ -130,7 +130,7 @@ use super::{
pub use crate::references::esm::export::{FollowExportsResult, follow_reexports}; pub use crate::references::esm::export::{FollowExportsResult, follow_reexports};
use crate::{ use crate::{
EcmascriptInputTransforms, EcmascriptModuleAsset, EcmascriptParsable, SpecifiedModuleType, EcmascriptInputTransforms, EcmascriptModuleAsset, EcmascriptParsable, SpecifiedModuleType,
TreeShakingMode, TreeShakingMode, TypeofWindow,
analyzer::{ analyzer::{
ConstantNumber, ConstantString, JsValueUrlKind, RequireContextValue, ConstantNumber, ConstantString, JsValueUrlKind, RequireContextValue,
builtin::early_replace_builtin, builtin::early_replace_builtin,
...@@ -617,8 +617,11 @@ pub async fn analyse_ecmascript_module_internal( ...@@ -617,8 +617,11 @@ pub async fn analyse_ecmascript_module_internal(
analysis.set_has_side_effect_free_directive(has_side_effect_free_directive); analysis.set_has_side_effect_free_directive(has_side_effect_free_directive);
let is_esm = eval_context.is_esm(specified_type); let is_esm = eval_context.is_esm(specified_type);
let compile_time_info = let compile_time_info = compile_time_info_for_module_options(
compile_time_info_for_module_type(*raw_module.compile_time_info, is_esm) *raw_module.compile_time_info,
is_esm,
options.enable_typeof_window_inlining,
)
.to_resolved() .to_resolved()
.await?; .await?;
...@@ -1471,9 +1474,10 @@ pub async fn analyse_ecmascript_module_internal( ...@@ -1471,9 +1474,10 @@ pub async fn analyse_ecmascript_module_internal(
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn compile_time_info_for_module_type( async fn compile_time_info_for_module_options(
compile_time_info: Vc<CompileTimeInfo>, compile_time_info: Vc<CompileTimeInfo>,
is_esm: bool, is_esm: bool,
enable_typeof_window_inlining: Option<TypeofWindow>,
) -> Result<Vc<CompileTimeInfo>> { ) -> Result<Vc<CompileTimeInfo>> {
let compile_time_info = compile_time_info.await?; let compile_time_info = compile_time_info.await?;
let free_var_references = compile_time_info.free_var_references; let free_var_references = compile_time_info.free_var_references;
...@@ -1584,9 +1588,33 @@ async fn compile_time_info_for_module_type( ...@@ -1584,9 +1588,33 @@ async fn compile_time_info_for_module_type(
} else { } else {
rcstr!("object").into() rcstr!("object").into()
}); });
let mut defines = compile_time_info.defines;
if let Some(enable_typeof_window_inlining) = enable_typeof_window_inlining {
let value = match enable_typeof_window_inlining {
TypeofWindow::Object => rcstr!("object"),
TypeofWindow::Undefined => rcstr!("undefined"),
};
let window = rcstr!("window");
let mut defines_value = defines.owned().await?;
defines_value
.entry(vec![
DefinableNameSegment::Name(window.clone()),
DefinableNameSegment::TypeOf,
])
.or_insert(value.clone().into());
free_var_references
.entry(vec![
DefinableNameSegment::Name(window),
DefinableNameSegment::TypeOf,
])
.or_insert(value.into());
defines = CompileTimeDefines(defines_value).resolved_cell()
}
Ok(CompileTimeInfo { Ok(CompileTimeInfo {
environment: compile_time_info.environment, environment: compile_time_info.environment,
defines: compile_time_info.defines, defines,
free_var_references: FreeVarReferences(free_var_references).resolved_cell(), free_var_references: FreeVarReferences(free_var_references).resolved_cell(),
} }
.cell()) .cell())
......
...@@ -2,7 +2,6 @@ use std::{fmt::Debug, hash::Hash, sync::Arc}; ...@@ -2,7 +2,6 @@ use std::{fmt::Debug, hash::Hash, sync::Arc};
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use rustc_hash::FxHashMap;
use swc_core::{ use swc_core::{
atoms::{Atom, atom}, atoms::{Atom, atom},
base::SwcComments, base::SwcComments,
...@@ -15,7 +14,6 @@ use swc_core::{ ...@@ -15,7 +14,6 @@ use swc_core::{
assumptions::Assumptions, assumptions::Assumptions,
helpers::{HELPERS, HelperData, Helpers}, helpers::{HELPERS, HelperData, Helpers},
}, },
optimization::inline_globals,
react::react, react::react,
}, },
utils::IsDirective, utils::IsDirective,
...@@ -44,9 +42,6 @@ pub enum EcmascriptInputTransform { ...@@ -44,9 +42,6 @@ pub enum EcmascriptInputTransform {
// swc.jsc.transform.react.runtime, // swc.jsc.transform.react.runtime,
runtime: ResolvedVc<Option<RcStr>>, runtime: ResolvedVc<Option<RcStr>>,
}, },
GlobalTypeofs {
window_value: RcStr,
},
// These options are subset of swc_core::ecma::transforms::typescript::Config, but // These options are subset of swc_core::ecma::transforms::typescript::Config, but
// it doesn't derive `Copy` so repeating values in here // it doesn't derive `Copy` so repeating values in here
TypeScript { TypeScript {
...@@ -139,22 +134,6 @@ impl EcmascriptInputTransform { ...@@ -139,22 +134,6 @@ impl EcmascriptInputTransform {
} = ctx; } = ctx;
Ok(match self { Ok(match self {
EcmascriptInputTransform::GlobalTypeofs { window_value } => {
let mut typeofs: FxHashMap<Atom, Atom> = Default::default();
typeofs.insert(Atom::from("window"), Atom::from(&**window_value));
apply_transform(
program,
helpers,
inline_globals(
unresolved_mark,
Default::default(),
Default::default(),
Default::default(),
Arc::new(typeofs),
),
)
}
EcmascriptInputTransform::React { EcmascriptInputTransform::React {
development, development,
refresh, refresh,
......
...@@ -207,7 +207,7 @@ impl ModuleOptions { ...@@ -207,7 +207,7 @@ impl ModuleOptions {
ignore_dynamic_requests, ignore_dynamic_requests,
import_externals, import_externals,
esm_url_rewrite_behavior, esm_url_rewrite_behavior,
ref enable_typeof_window_inlining, enable_typeof_window_inlining,
source_maps: ecmascript_source_maps, source_maps: ecmascript_source_maps,
.. ..
}, },
...@@ -282,6 +282,7 @@ impl ModuleOptions { ...@@ -282,6 +282,7 @@ impl ModuleOptions {
extract_source_map: matches!(ecmascript_source_maps, SourceMapsType::Full), extract_source_map: matches!(ecmascript_source_maps, SourceMapsType::Full),
keep_last_successful_parse, keep_last_successful_parse,
is_tracing, is_tracing,
enable_typeof_window_inlining,
..Default::default() ..Default::default()
}; };
let ecmascript_options_vc = ecmascript_options.resolved_cell(); let ecmascript_options_vc = ecmascript_options.resolved_cell();
...@@ -290,15 +291,6 @@ impl ModuleOptions { ...@@ -290,15 +291,6 @@ impl ModuleOptions {
postprocess.push(EcmascriptInputTransform::PresetEnv(environment)); postprocess.push(EcmascriptInputTransform::PresetEnv(environment));
} }
if let Some(enable_typeof_window_inlining) = enable_typeof_window_inlining {
postprocess.push(EcmascriptInputTransform::GlobalTypeofs {
window_value: match enable_typeof_window_inlining {
TypeofWindow::Object => rcstr!("object"),
TypeofWindow::Undefined => rcstr!("undefined"),
},
});
}
let ts_transform = if let Some(options) = enable_typescript_transform { let ts_transform = if let Some(options) = enable_typescript_transform {
let options = options.await?; let options = options.await?;
Some(EcmascriptInputTransform::TypeScript { Some(EcmascriptInputTransform::TypeScript {
......
...@@ -9,7 +9,7 @@ use turbopack_core::{ ...@@ -9,7 +9,7 @@ use turbopack_core::{
chunk::SourceMapsType, compile_time_info::CompileTimeInfo, condition::ContextCondition, chunk::SourceMapsType, compile_time_info::CompileTimeInfo, condition::ContextCondition,
environment::Environment, resolve::options::ImportMapping, environment::Environment, resolve::options::ImportMapping,
}; };
use turbopack_ecmascript::{TreeShakingMode, references::esm::UrlRewriteBehavior}; use turbopack_ecmascript::{TreeShakingMode, TypeofWindow, references::esm::UrlRewriteBehavior};
pub use turbopack_mdx::MdxTransformOptions; pub use turbopack_mdx::MdxTransformOptions;
use turbopack_node::{ use turbopack_node::{
execution_context::ExecutionContext, execution_context::ExecutionContext,
...@@ -108,13 +108,6 @@ pub enum DecoratorsKind { ...@@ -108,13 +108,6 @@ pub enum DecoratorsKind {
Ecma, Ecma,
} }
/// The types when replacing `typeof window` with a constant.
#[derive(Copy, Clone, PartialEq, Eq, Debug, TraceRawVcs, Serialize, Deserialize, NonLocalValue)]
pub enum TypeofWindow {
Object,
Undefined,
}
/// Configuration options for the decorators transform. /// Configuration options for the decorators transform.
/// ///
/// This is not part of Typescript transform: while there are typescript /// This is not part of Typescript transform: while there are typescript
...@@ -223,6 +216,9 @@ pub struct ModuleOptionsContext { ...@@ -223,6 +216,9 @@ pub struct ModuleOptionsContext {
#[derive(Clone, Default)] #[derive(Clone, Default)]
#[serde(default)] #[serde(default)]
pub struct EcmascriptOptionsContext { pub struct EcmascriptOptionsContext {
// TODO this should just be handled via CompileTimeInfo FreeVarReferences, but then it
// (currently) wouldn't be possible to have different replacement values in user code vs
// node_modules.
pub enable_typeof_window_inlining: Option<TypeofWindow>, pub enable_typeof_window_inlining: Option<TypeofWindow>,
pub enable_jsx: Option<ResolvedVc<JsxTransformOptions>>, pub enable_jsx: Option<ResolvedVc<JsxTransformOptions>>,
/// Follow type references and resolve declaration files in additional to /// Follow type references and resolve declaration files in additional to
......
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