Skip to content

Commit

Permalink
fix free var replacements (compile time defines) and allow JSON values
Browse files Browse the repository at this point in the history
  • Loading branch information
ForsakenHarmony committed Sep 21, 2023
1 parent 91e9961 commit 15ab9f4
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 33 deletions.
12 changes: 11 additions & 1 deletion crates/turbopack-core/src/compile_time_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ macro_rules! free_var_references {
pub enum CompileTimeDefineValue {
Bool(bool),
String(String),
JSON(String),
}

impl From<bool> for CompileTimeDefineValue {
Expand All @@ -97,7 +98,14 @@ impl From<&str> for CompileTimeDefineValue {
}
}

impl From<serde_json::Value> for CompileTimeDefineValue {
fn from(value: serde_json::Value) -> Self {
Self::JSON(value.to_string())
}
}

#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)]
pub struct CompileTimeDefines(pub IndexMap<Vec<String>, CompileTimeDefineValue>);

impl IntoIterator for CompileTimeDefines {
Expand All @@ -118,7 +126,7 @@ impl CompileTimeDefines {
}

#[turbo_tasks::value]
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum FreeVarReference {
EcmaScriptModule {
request: String,
Expand Down Expand Up @@ -153,6 +161,7 @@ impl From<CompileTimeDefineValue> for FreeVarReference {
}

#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)]
pub struct FreeVarReferences(pub IndexMap<Vec<String>, FreeVarReference>);

#[turbo_tasks::value_impl]
Expand All @@ -164,6 +173,7 @@ impl FreeVarReferences {
}

#[turbo_tasks::value(shared)]
#[derive(Debug, Clone)]
pub struct CompileTimeInfo {
pub environment: Vc<Environment>,
pub defines: Vc<CompileTimeDefines>,
Expand Down
1 change: 1 addition & 0 deletions crates/turbopack-ecmascript/src/analyzer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,7 @@ impl From<&CompileTimeDefineValue> for JsValue {
match v {
CompileTimeDefineValue::String(s) => JsValue::Constant(s.as_str().into()),
CompileTimeDefineValue::Bool(b) => JsValue::Constant((*b).into()),
CompileTimeDefineValue::JSON(_) => JsValue::unknown_empty("compile time injected JSON"),
}
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/turbopack-ecmascript/src/path_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ impl VisitMutAstPath for ApplyVisitors<'_, '_> {
// TODO: we need a macro to apply that for all methods
method!(visit_mut_prop, Prop);
method!(visit_mut_expr, Expr);
method!(visit_mut_member_expr, MemberExpr);
method!(visit_mut_pat, Pat);
method!(visit_mut_stmt, Stmt);
method!(visit_mut_module_decl, ModuleDecl);
Expand Down
25 changes: 14 additions & 11 deletions crates/turbopack-ecmascript/src/references/constant_value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,20 @@ impl CodeGenerateable for ConstantValue {
_context: Vc<Box<dyn EcmascriptChunkingContext>>,
) -> Result<Vc<CodeGeneration>> {
let value = self.value.clone();
let visitors = [
create_visitor!(exact &self.path.await?, visit_mut_expr(expr: &mut Expr) {
*expr = match value {
CompileTimeDefineValue::Bool(true) => quote!("(\"TURBOPACK compile-time value\", true)" as Expr),
CompileTimeDefineValue::Bool(false) => quote!("(\"TURBOPACK compile-time value\", false)" as Expr),
CompileTimeDefineValue::String(ref s) => quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = s.to_string().into()),
};
}),
]
.into();
let path = &self.path.await?;

Ok(CodeGeneration { visitors }.cell())
let visitor = create_visitor!(path, visit_mut_expr(expr: &mut Expr) {
*expr = match value {
CompileTimeDefineValue::Bool(true) => quote!("(\"TURBOPACK compile-time value\", true)" as Expr),
CompileTimeDefineValue::Bool(false) => quote!("(\"TURBOPACK compile-time value\", false)" as Expr),
CompileTimeDefineValue::String(ref s) => quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = s.to_string().into()),
CompileTimeDefineValue::JSON(ref s) => quote!("(\"TURBOPACK compile-time value\", JSON.parse($e))" as Expr, e: Expr = s.to_string().into()),
};
});

Ok(CodeGeneration {
visitors: vec![visitor],
}
.cell())
}
}
23 changes: 13 additions & 10 deletions crates/turbopack-tests/tests/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::{
use anyhow::{bail, Context, Result};
use dunce::canonicalize;
use serde::Deserialize;
use serde_json::json;
use turbo_tasks::{ReadRef, TryJoinIterExt, TurboTasks, Value, ValueToString, Vc};
use turbo_tasks_env::DotenvProcessEnv;
use turbo_tasks_fs::{
Expand All @@ -34,6 +35,7 @@ use turbopack_core::{
context::AssetContext,
environment::{BrowserEnvironment, Environment, ExecutionEnvironment, NodeJsEnvironment},
file_source::FileSource,
free_var_references,
issue::{Issue, IssueDescriptionExt},
module::Module,
output::OutputAsset,
Expand Down Expand Up @@ -209,17 +211,18 @@ async fn run_test(resource: String) -> Result<Vc<FileSystemPath>> {
)
}
}));

let defines = compile_time_defines!(
process.turbopack = true,
process.env.NODE_ENV = "development",
DEFINED_VALUE = "value",
DEFINED_TRUE = true,
A.VERY.LONG.DEFINED.VALUE = json!({ "test": true }),
);

let compile_time_info = CompileTimeInfo::builder(env)
.defines(
compile_time_defines!(
process.turbopack = true,
process.env.NODE_ENV = "development",
DEFINED_VALUE = "value",
DEFINED_TRUE = true,
A.VERY.LONG.DEFINED.VALUE = "value",
)
.cell(),
)
.defines(defines.clone().cell())
.free_var_references(free_var_references!(..defines.into_iter()).cell())
.cell();

let custom_ecma_transform_plugins = Some(CustomEcmascriptTransformPlugins::cell(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ if (process.env.NODE_ENV === 'production') {

var p = process;

// TODO: replacement is not implemented yet
console.log(A.VERY.LONG.DEFINED.VALUE);
console.log(DEFINED_VALUE);
console.log(p.env.NODE_ENV);
Expand Down

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

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

0 comments on commit 15ab9f4

Please sign in to comment.