Skip to content

Commit 4058da0

Browse files
authored
allow to pass constant values to free var references (vercel#4652)
### Description This will allow to do constant replacements of free vars aka webpack DefinePlugin
1 parent 9c6221b commit 4058da0

File tree

3 files changed

+107
-3
lines changed

3 files changed

+107
-3
lines changed

crates/turbopack-core/src/compile_time_info.rs

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
use std::collections::HashMap;
22

33
use anyhow::Result;
4-
use serde::{Deserialize, Serialize};
5-
use turbo_tasks::trace::TraceRawVcs;
64
use turbo_tasks_fs::FileSystemPathVc;
75

86
use crate::environment::EnvironmentVc;
97

108
// TODO stringify split map collect could be optimized with a marco
119
#[macro_export]
1210
macro_rules! definable_name_map_internal {
11+
($map:ident, .. $value:expr) => {
12+
for (key, value) in $value {
13+
$map.insert(
14+
key.into(),
15+
value.into()
16+
);
17+
}
18+
};
1319
($map:ident, $($name:ident).+ = $value:expr) => {
1420
$map.insert(
1521
$crate::definable_name_map_internal!($($name).+).into(),
@@ -26,6 +32,10 @@ macro_rules! definable_name_map_internal {
2632
$crate::definable_name_map_internal!($map, $($name).+ = $value);
2733
$crate::definable_name_map_internal!($map, $($more)+);
2834
};
35+
($map:ident, .. $value:expr, $($more:tt)+) => {
36+
$crate::definable_name_map_internal!($map, .. $value);
37+
$crate::definable_name_map_internal!($map, $($more)+);
38+
};
2939
($name:ident) => {
3040
[stringify!($name).to_string()]
3141
};
@@ -62,7 +72,8 @@ macro_rules! free_var_references {
6272
};
6373
}
6474

65-
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TraceRawVcs)]
75+
#[turbo_tasks::value(serialization = "auto_for_input")]
76+
#[derive(Debug, Clone, Hash, PartialOrd, Ord)]
6677
pub enum CompileTimeDefineValue {
6778
Bool(bool),
6879
String(String),
@@ -89,6 +100,15 @@ impl From<&str> for CompileTimeDefineValue {
89100
#[turbo_tasks::value(transparent)]
90101
pub struct CompileTimeDefines(pub HashMap<Vec<String>, CompileTimeDefineValue>);
91102

103+
impl IntoIterator for CompileTimeDefines {
104+
type Item = (Vec<String>, CompileTimeDefineValue);
105+
type IntoIter = std::collections::hash_map::IntoIter<Vec<String>, CompileTimeDefineValue>;
106+
107+
fn into_iter(self) -> Self::IntoIter {
108+
self.0.into_iter()
109+
}
110+
}
111+
92112
#[turbo_tasks::value_impl]
93113
impl CompileTimeDefinesVc {
94114
#[turbo_tasks::function]
@@ -104,6 +124,31 @@ pub enum FreeVarReference {
104124
context: Option<FileSystemPathVc>,
105125
export: Option<String>,
106126
},
127+
Value(CompileTimeDefineValue),
128+
}
129+
130+
impl From<bool> for FreeVarReference {
131+
fn from(value: bool) -> Self {
132+
Self::Value(value.into())
133+
}
134+
}
135+
136+
impl From<String> for FreeVarReference {
137+
fn from(value: String) -> Self {
138+
Self::Value(value.into())
139+
}
140+
}
141+
142+
impl From<&str> for FreeVarReference {
143+
fn from(value: &str) -> Self {
144+
Self::Value(value.into())
145+
}
146+
}
147+
148+
impl From<CompileTimeDefineValue> for FreeVarReference {
149+
fn from(value: CompileTimeDefineValue) -> Self {
150+
Self::Value(value)
151+
}
107152
}
108153

109154
#[turbo_tasks::value(transparent)]
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
use anyhow::Result;
2+
use swc_core::quote;
3+
use turbo_tasks::Value;
4+
use turbopack_core::compile_time_info::CompileTimeDefineValue;
5+
6+
use super::AstPathVc;
7+
use crate::{
8+
chunk::EcmascriptChunkingContextVc,
9+
code_gen::{CodeGenerateable, CodeGenerateableVc, CodeGeneration, CodeGenerationVc},
10+
create_visitor,
11+
};
12+
13+
#[turbo_tasks::value]
14+
pub struct ConstantValue {
15+
value: CompileTimeDefineValue,
16+
path: AstPathVc,
17+
}
18+
19+
#[turbo_tasks::value_impl]
20+
impl ConstantValueVc {
21+
#[turbo_tasks::function]
22+
pub fn new(value: Value<CompileTimeDefineValue>, path: AstPathVc) -> Self {
23+
Self::cell(ConstantValue {
24+
value: value.into_value(),
25+
path,
26+
})
27+
}
28+
}
29+
30+
#[turbo_tasks::value_impl]
31+
impl CodeGenerateable for ConstantValue {
32+
#[turbo_tasks::function]
33+
async fn code_generation(
34+
&self,
35+
_context: EcmascriptChunkingContextVc,
36+
) -> Result<CodeGenerationVc> {
37+
let value = self.value.clone();
38+
let visitors = [
39+
create_visitor!(exact &self.path.await?, visit_mut_expr(expr: &mut Expr) {
40+
*expr = match value {
41+
CompileTimeDefineValue::Bool(true) => quote!("(\"TURBOPACK compile-time value\", true)" as Expr),
42+
CompileTimeDefineValue::Bool(false) => quote!("(\"TURBOPACK compile-time value\", false)" as Expr),
43+
CompileTimeDefineValue::String(ref s) => quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = s.to_string().into()),
44+
};
45+
}),
46+
]
47+
.into();
48+
49+
Ok(CodeGeneration { visitors }.cell())
50+
}
51+
}

crates/turbopack-ecmascript/src/references/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
pub mod amd;
22
pub mod cjs;
33
pub mod constant_condition;
4+
pub mod constant_value;
45
pub mod esm;
56
pub mod node;
67
pub mod pattern_mapping;
@@ -20,6 +21,7 @@ use std::{
2021

2122
use anyhow::Result;
2223
use constant_condition::{ConstantConditionValue, ConstantConditionVc};
24+
use constant_value::ConstantValueVc;
2325
use indexmap::IndexSet;
2426
use lazy_static::lazy_static;
2527
use parking_lot::Mutex;
@@ -1275,6 +1277,12 @@ pub(crate) async fn analyze_ecmascript_module(
12751277
.eq(name.iter().map(Cow::Borrowed).rev())
12761278
{
12771279
match value {
1280+
FreeVarReference::Value(value) => {
1281+
analysis.add_code_gen(ConstantValueVc::new(
1282+
Value::new(value.clone()),
1283+
AstPathVc::cell(ast_path.to_vec()),
1284+
));
1285+
}
12781286
FreeVarReference::EcmaScriptModule {
12791287
request,
12801288
context,

0 commit comments

Comments
 (0)