Unverified Commit 1122b1f2 authored by xusd320's avatar xusd320 Committed by GitHub

feat(turbopack): improve compile-time define value to support more data types…

feat(turbopack): improve compile-time define value to support more data types and expr evaluation (#81042)
Co-authored-by: 's avatargraphite-app[bot] <96075541+graphite-app[bot]@users.noreply.github.com>
parent d5dc166f
use std::{future::Future, sync::LazyLock}; use std::{str::FromStr, sync::LazyLock};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use regex::Regex; use regex::Regex;
...@@ -61,13 +61,10 @@ pub fn defines(define_env: &FxIndexMap<RcStr, Option<RcStr>>) -> CompileTimeDefi ...@@ -61,13 +61,10 @@ pub fn defines(define_env: &FxIndexMap<RcStr, Option<RcStr>>) -> CompileTimeDefi
) )
.or_insert_with(|| { .or_insert_with(|| {
if let Some(v) = v { if let Some(v) = v {
let val = serde_json::from_str(v); let val = serde_json::Value::from_str(v);
match val { match val {
Ok(serde_json::Value::Bool(v)) => CompileTimeDefineValue::Bool(v), Ok(v) => v.into(),
Ok(serde_json::Value::String(v)) => { _ => CompileTimeDefineValue::Evaluate(v.clone()),
CompileTimeDefineValue::String(v.into())
}
_ => CompileTimeDefineValue::JSON(v.clone()),
} }
} else { } else {
CompileTimeDefineValue::Undefined CompileTimeDefineValue::Undefined
......
...@@ -233,6 +233,12 @@ impl AsRef<[u8]> for RcStr { ...@@ -233,6 +233,12 @@ impl AsRef<[u8]> for RcStr {
} }
} }
impl From<RcStr> for BytesStr {
fn from(value: RcStr) -> Self {
Self::from_str_slice(value.as_str())
}
}
impl PartialEq<str> for RcStr { impl PartialEq<str> for RcStr {
fn eq(&self, other: &str) -> bool { fn eq(&self, other: &str) -> bool {
self.as_str() == other self.as_str() == other
......
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{FxIndexMap, NonLocalValue, ResolvedVc, TaskInput, Vc, trace::TraceRawVcs}; use turbo_tasks::{FxIndexMap, NonLocalValue, ResolvedVc, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use crate::environment::Environment; use crate::environment::Environment;
...@@ -102,12 +102,16 @@ macro_rules! free_var_references { ...@@ -102,12 +102,16 @@ macro_rules! free_var_references {
// TODO: replace with just a `serde_json::Value` // TODO: replace with just a `serde_json::Value`
// https://linear.app/vercel/issue/WEB-1641/compiletimedefinevalue-should-just-use-serde-jsonvalue // https://linear.app/vercel/issue/WEB-1641/compiletimedefinevalue-should-just-use-serde-jsonvalue
#[turbo_tasks::value] #[turbo_tasks::value]
#[derive(Debug, Clone, Hash, TaskInput)] #[derive(Debug, Clone, Hash)]
pub enum CompileTimeDefineValue { pub enum CompileTimeDefineValue {
Null,
Bool(bool), Bool(bool),
Number(RcStr),
String(RcStr), String(RcStr),
JSON(RcStr), Array(Vec<CompileTimeDefineValue>),
Object(Vec<(RcStr, CompileTimeDefineValue)>),
Undefined, Undefined,
Evaluate(RcStr),
} }
impl From<bool> for CompileTimeDefineValue { impl From<bool> for CompileTimeDefineValue {
...@@ -136,7 +140,16 @@ impl From<&str> for CompileTimeDefineValue { ...@@ -136,7 +140,16 @@ impl From<&str> for CompileTimeDefineValue {
impl From<serde_json::Value> for CompileTimeDefineValue { impl From<serde_json::Value> for CompileTimeDefineValue {
fn from(value: serde_json::Value) -> Self { fn from(value: serde_json::Value) -> Self {
Self::JSON(value.to_string().into()) match value {
serde_json::Value::Null => Self::Null,
serde_json::Value::Bool(b) => Self::Bool(b),
serde_json::Value::Number(n) => Self::Number(n.to_string().into()),
serde_json::Value::String(s) => Self::String(s.into()),
serde_json::Value::Array(a) => Self::Array(a.into_iter().map(|i| i.into()).collect()),
serde_json::Value::Object(m) => {
Self::Object(m.into_iter().map(|(k, v)| (k.into(), v.into())).collect())
}
}
} }
} }
......
...@@ -57,7 +57,7 @@ pub fn benchmark(c: &mut Criterion) { ...@@ -57,7 +57,7 @@ pub fn benchmark(c: &mut Criterion) {
program.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, false)); program.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, false));
let eval_context = EvalContext::new( let eval_context = EvalContext::new(
&program, Some(&program),
unresolved_mark, unresolved_mark,
top_level_mark, top_level_mark,
Default::default(), Default::default(),
......
...@@ -4,10 +4,15 @@ use std::{ ...@@ -4,10 +4,15 @@ use std::{
sync::Arc, sync::Arc,
}; };
use anyhow::{Ok, Result};
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use swc_core::{ use swc_core::{
atoms::Atom, atoms::Atom,
common::{GLOBALS, Mark, Span, Spanned, SyntaxContext, comments::Comments, pass::AstNodePath}, base::try_with_handler,
common::{
GLOBALS, Mark, SourceMap, Span, Spanned, SyntaxContext, comments::Comments,
pass::AstNodePath, sync::Lrc,
},
ecma::{ ecma::{
ast::*, ast::*,
atoms::atom, atoms::atom,
...@@ -26,6 +31,7 @@ use super::{ ...@@ -26,6 +31,7 @@ use super::{
use crate::{ use crate::{
SpecifiedModuleType, SpecifiedModuleType,
analyzer::{WellKnownObjectKind, is_unresolved}, analyzer::{WellKnownObjectKind, is_unresolved},
references::constant_value::parse_single_expr_lit,
utils::{AstPathRange, unparen}, utils::{AstPathRange, unparen},
}; };
...@@ -311,7 +317,7 @@ impl EvalContext { ...@@ -311,7 +317,7 @@ impl EvalContext {
/// webpackIgnore or turbopackIgnore comments, you must pass those in, /// webpackIgnore or turbopackIgnore comments, you must pass those in,
/// since the AST does not include comments by default. /// since the AST does not include comments by default.
pub fn new( pub fn new(
module: &Program, module: Option<&Program>,
unresolved_mark: Mark, unresolved_mark: Mark,
top_level_mark: Mark, top_level_mark: Mark,
force_free_values: Arc<FxHashSet<Id>>, force_free_values: Arc<FxHashSet<Id>>,
...@@ -321,7 +327,9 @@ impl EvalContext { ...@@ -321,7 +327,9 @@ impl EvalContext {
Self { Self {
unresolved_mark, unresolved_mark,
top_level_mark, top_level_mark,
imports: ImportMap::analyze(module, source, comments), imports: module.map_or(ImportMap::default(), |m| {
ImportMap::analyze(m, source, comments)
}),
force_free_values, force_free_values,
} }
} }
...@@ -719,6 +727,29 @@ impl EvalContext { ...@@ -719,6 +727,29 @@ impl EvalContext {
_ => JsValue::unknown_empty(true, "unsupported expression"), _ => JsValue::unknown_empty(true, "unsupported expression"),
} }
} }
pub fn eval_single_expr_lit(expr_lit: RcStr) -> Result<JsValue> {
let cm = Lrc::new(SourceMap::default());
let js_value = try_with_handler(cm, Default::default(), |_| {
GLOBALS.set(&Default::default(), || {
let expr = parse_single_expr_lit(expr_lit);
let eval_context = EvalContext::new(
None,
Mark::new(),
Mark::new(),
Default::default(),
None,
None,
);
Ok(eval_context.eval(&expr))
})
})
.map_err(|e| e.to_pretty_error())?;
Ok(js_value)
}
} }
enum EarlyReturn { enum EarlyReturn {
......
...@@ -33,7 +33,10 @@ use turbopack_core::compile_time_info::{ ...@@ -33,7 +33,10 @@ use turbopack_core::compile_time_info::{
use self::imports::ImportAnnotations; use self::imports::ImportAnnotations;
pub(crate) use self::imports::ImportMap; pub(crate) use self::imports::ImportMap;
use crate::{references::require_context::RequireContextMap, utils::StringifyJs}; use crate::{
analyzer::graph::EvalContext, references::require_context::RequireContextMap,
utils::StringifyJs,
};
pub mod builtin; pub mod builtin;
pub mod graph; pub mod graph;
...@@ -581,38 +584,73 @@ impl From<ConstantValue> for JsValue { ...@@ -581,38 +584,73 @@ impl From<ConstantValue> for JsValue {
} }
} }
impl From<&CompileTimeDefineValue> for JsValue { impl TryFrom<&CompileTimeDefineValue> for JsValue {
fn from(v: &CompileTimeDefineValue) -> Self { type Error = anyhow::Error;
match v {
CompileTimeDefineValue::String(s) => JsValue::Constant(s.as_str().into()), fn try_from(value: &CompileTimeDefineValue) -> Result<Self> {
CompileTimeDefineValue::Bool(b) => JsValue::Constant((*b).into()), match value {
CompileTimeDefineValue::JSON(_) => { CompileTimeDefineValue::Null => Ok(JsValue::Constant(ConstantValue::Null)),
JsValue::unknown_empty(false, "compile time injected JSON") CompileTimeDefineValue::Bool(b) => Ok(JsValue::Constant((*b).into())),
CompileTimeDefineValue::Number(n) => Ok(JsValue::Constant(ConstantValue::Num(
ConstantNumber(n.as_str().parse::<f64>()?),
))),
CompileTimeDefineValue::String(s) => Ok(JsValue::Constant(s.as_str().into())),
CompileTimeDefineValue::Array(a) => {
let mut js_value = JsValue::Array {
total_nodes: a.len() as u32,
items: a.iter().map(|i| i.try_into()).collect::<Result<Vec<_>>>()?,
mutable: false,
};
js_value.update_total_nodes();
Ok(js_value)
} }
CompileTimeDefineValue::Undefined => JsValue::Constant(ConstantValue::Undefined), CompileTimeDefineValue::Object(m) => {
let mut js_value = JsValue::Object {
total_nodes: m.len() as u32,
parts: m
.iter()
.map(|(k, v)| {
Ok::<ObjectPart, anyhow::Error>(ObjectPart::KeyValue(
k.clone().into(),
v.try_into()?,
))
})
.collect::<Result<Vec<_>>>()?,
mutable: false,
};
js_value.update_total_nodes();
Ok(js_value)
}
CompileTimeDefineValue::Undefined => Ok(JsValue::Constant(ConstantValue::Undefined)),
CompileTimeDefineValue::Evaluate(s) => EvalContext::eval_single_expr_lit(s.clone()),
} }
} }
} }
impl From<&FreeVarReference> for JsValue { impl TryFrom<&FreeVarReference> for JsValue {
fn from(v: &FreeVarReference) -> Self { type Error = anyhow::Error;
match v {
FreeVarReference::Value(v) => v.into(), fn try_from(value: &FreeVarReference) -> Result<Self> {
match value {
FreeVarReference::Value(v) => v.try_into(),
FreeVarReference::Ident(_) => { FreeVarReference::Ident(_) => {
JsValue::unknown_empty(false, "compile time injected ident") Ok(JsValue::unknown_empty(false, "compile time injected ident"))
}
FreeVarReference::Member(_, _) => {
JsValue::unknown_empty(false, "compile time injected member")
}
FreeVarReference::EcmaScriptModule { .. } => {
JsValue::unknown_empty(false, "compile time injected free var module")
}
FreeVarReference::Error(_) => {
JsValue::unknown_empty(false, "compile time injected free var error")
} }
FreeVarReference::Member(_, _) => Ok(JsValue::unknown_empty(
false,
"compile time injected member",
)),
FreeVarReference::EcmaScriptModule { .. } => Ok(JsValue::unknown_empty(
false,
"compile time injected free var module",
)),
FreeVarReference::Error(_) => Ok(JsValue::unknown_empty(
false,
"compile time injected free var error",
)),
FreeVarReference::InputRelative(kind) => { FreeVarReference::InputRelative(kind) => {
use turbopack_core::compile_time_info::InputRelativeConstant; use turbopack_core::compile_time_info::InputRelativeConstant;
JsValue::unknown_empty( Ok(JsValue::unknown_empty(
false, false,
match kind { match kind {
InputRelativeConstant::DirName => { InputRelativeConstant::DirName => {
...@@ -622,7 +660,7 @@ impl From<&FreeVarReference> for JsValue { ...@@ -622,7 +660,7 @@ impl From<&FreeVarReference> for JsValue {
"compile time injected free var referencing the file name" "compile time injected free var referencing the file name"
} }
}, },
) ))
} }
} }
} }
...@@ -4069,7 +4107,7 @@ mod tests { ...@@ -4069,7 +4107,7 @@ mod tests {
m.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, false)); m.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, false));
let eval_context = EvalContext::new( let eval_context = EvalContext::new(
&m, Some(&m),
unresolved_mark, unresolved_mark,
top_level_mark, top_level_mark,
Default::default(), Default::default(),
......
...@@ -497,7 +497,7 @@ async fn parse_file_content( ...@@ -497,7 +497,7 @@ async fn parse_file_content(
}); });
let eval_context = EvalContext::new( let eval_context = EvalContext::new(
&parsed_program, Some(&parsed_program),
unresolved_mark, unresolved_mark,
top_level_mark, top_level_mark,
Arc::new(var_with_ts_declare), Arc::new(var_with_ts_declare),
......
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::quote; use swc_core::{
use turbo_tasks::{NonLocalValue, TaskInput, Vc, debug::ValueDebugFormat, trace::TraceRawVcs}; common::{DUMMY_SP, FileName, SourceMap, sync::Lrc},
ecma::{
ast::{ArrayLit, EsVersion, Expr, KeyValueProp, ObjectLit, Prop, PropName, Str},
parser::{Syntax, parse_file_as_expr},
},
quote,
};
use turbo_rcstr::RcStr;
use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbopack_core::{chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue}; use turbopack_core::{chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue};
use super::AstPath; use super::AstPath;
...@@ -21,7 +29,6 @@ use crate::{ ...@@ -21,7 +29,6 @@ use crate::{
TraceRawVcs, TraceRawVcs,
ValueDebugFormat, ValueDebugFormat,
NonLocalValue, NonLocalValue,
TaskInput,
)] )]
pub struct ConstantValueCodeGen { pub struct ConstantValueCodeGen {
value: CompileTimeDefineValue, value: CompileTimeDefineValue,
...@@ -39,24 +46,8 @@ impl ConstantValueCodeGen { ...@@ -39,24 +46,8 @@ impl ConstantValueCodeGen {
let value = self.value.clone(); let value = self.value.clone();
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| { let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| {
*expr = match value { // TODO: avoid this clone
CompileTimeDefineValue::Bool(true) => { *expr = define_env_to_expr((value).clone());
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())
}
// undefined can be re-bound, so use `void 0` to avoid any risks
CompileTimeDefineValue::Undefined => {
quote!("(\"TURBOPACK compile-time value\", void 0)" as Expr)
}
};
}); });
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]))
...@@ -68,3 +59,66 @@ impl From<ConstantValueCodeGen> for CodeGen { ...@@ -68,3 +59,66 @@ impl From<ConstantValueCodeGen> for CodeGen {
CodeGen::ConstantValueCodeGen(val) CodeGen::ConstantValueCodeGen(val)
} }
} }
fn define_env_to_expr(value: CompileTimeDefineValue) -> Expr {
match value {
CompileTimeDefineValue::Null => {
quote!("(\"TURBOPACK compile-time value\", null)" as Expr)
}
CompileTimeDefineValue::Bool(true) => {
quote!("(\"TURBOPACK compile-time value\", true)" as Expr)
}
CompileTimeDefineValue::Bool(false) => {
quote!("(\"TURBOPACK compile-time value\", false)" as Expr)
}
CompileTimeDefineValue::Number(ref n) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = n.parse::<f64>().unwrap().into())
}
CompileTimeDefineValue::String(ref s) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = s.to_string().into())
}
CompileTimeDefineValue::Array(a) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = Expr::Array(ArrayLit {
span: DUMMY_SP,
elems: a.into_iter().map(|i| Some(define_env_to_expr(i).into())).collect(),
}))
}
CompileTimeDefineValue::Object(m) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = Expr::Object(ObjectLit {
span: DUMMY_SP,
props: m
.into_iter()
.map(|(k, v)| {
swc_core::ecma::ast::PropOrSpread::Prop(
Prop::KeyValue(KeyValueProp {
key: PropName::Str(Str::from(k.as_str())),
value: define_env_to_expr(v).into(),
})
.into(),
)
})
.collect(),
}))
}
CompileTimeDefineValue::Undefined => {
quote!("(\"TURBOPACK compile-time value\", void 0)" as Expr)
}
CompileTimeDefineValue::Evaluate(ref s) => parse_single_expr_lit(s.clone()),
}
}
pub(crate) fn parse_single_expr_lit(expr_lit: RcStr) -> Expr {
let cm = Lrc::new(SourceMap::default());
let fm = cm.new_source_file(FileName::Anon.into(), expr_lit.clone());
parse_file_as_expr(
&fm,
Syntax::Es(Default::default()),
EsVersion::latest(),
None,
&mut vec![],
)
.map_or(
quote!("(\"Failed parsed TURBOPACK compile-time value\", $s)" as Expr, s: Expr = expr_lit.as_str().into()),
|expr| quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = *expr),
)
}
...@@ -2906,11 +2906,11 @@ async fn value_visitor_inner( ...@@ -2906,11 +2906,11 @@ async fn value_visitor_inner(
&DefinableNameSegment::TypeOf, &DefinableNameSegment::TypeOf,
) )
{ {
return Ok(((&*value.await?).into(), true)); return Ok(((&*value.await?).try_into()?, true));
} }
if let Some(value) = v.match_define(&*compile_time_info.defines.individual().await?) { if let Some(value) = v.match_define(&*compile_time_info.defines.individual().await?) {
return Ok(((&*value.await?).into(), true)); return Ok(((&*value.await?).try_into()?, true));
} }
} }
let value = match v { let value = match v {
......
...@@ -570,7 +570,7 @@ pub(super) async fn split( ...@@ -570,7 +570,7 @@ pub(super) async fn split(
.map(|module| { .map(|module| {
let program = Program::Module(module); let program = Program::Module(module);
let eval_context = EvalContext::new( let eval_context = EvalContext::new(
&program, Some(&program),
eval_context.unresolved_mark, eval_context.unresolved_mark,
eval_context.top_level_mark, eval_context.top_level_mark,
eval_context.force_free_values.clone(), eval_context.force_free_values.clone(),
...@@ -695,7 +695,7 @@ pub(crate) async fn part_of_module( ...@@ -695,7 +695,7 @@ pub(crate) async fn part_of_module(
let program = Program::Module(module); let program = Program::Module(module);
let eval_context = EvalContext::new( let eval_context = EvalContext::new(
&program, Some(&program),
eval_context.unresolved_mark, eval_context.unresolved_mark,
eval_context.top_level_mark, eval_context.top_level_mark,
eval_context.force_free_values.clone(), eval_context.force_free_values.clone(),
......
...@@ -34,7 +34,7 @@ use turbopack_core::{ ...@@ -34,7 +34,7 @@ use turbopack_core::{
EvaluatableAssets, MinifyType, availability_info::AvailabilityInfo, EvaluatableAssets, MinifyType, availability_info::AvailabilityInfo,
}, },
compile_time_defines, compile_time_defines,
compile_time_info::CompileTimeInfo, compile_time_info::{CompileTimeDefineValue, CompileTimeInfo, DefinableNameSegment},
condition::ContextCondition, condition::ContextCondition,
context::AssetContext, context::AssetContext,
environment::{BrowserEnvironment, Environment, ExecutionEnvironment, NodeJsEnvironment}, environment::{BrowserEnvironment, Environment, ExecutionEnvironment, NodeJsEnvironment},
...@@ -296,15 +296,33 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -296,15 +296,33 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
.to_resolved() .to_resolved()
.await?; .await?;
let defines = compile_time_defines!( let mut defines = compile_time_defines!(
process.turbopack = true, process.turbopack = true,
process.env.TURBOPACK = true, process.env.TURBOPACK = true,
process.env.NODE_ENV = "development", process.env.NODE_ENV = "development",
DEFINED_VALUE = "value", DEFINED_VALUE = "value",
DEFINED_TRUE = true, DEFINED_TRUE = true,
DEFINED_NULL = json!(null),
DEFINED_INT = json!(1),
DEFINED_FLOAT = json!(0.01),
DEFINED_ARRAY = json!([ false, 0, "1", { "v": "v" }, null ]),
A.VERY.LONG.DEFINED.VALUE = json!({ "test": true }), A.VERY.LONG.DEFINED.VALUE = json!({ "test": true }),
); );
defines.0.insert(
vec![DefinableNameSegment::from("DEFINED_EVALUATE")],
CompileTimeDefineValue::Evaluate("1 + 1".into()),
);
defines.0.insert(
vec![DefinableNameSegment::from("DEFINED_EVALUATE_NESTED")],
CompileTimeDefineValue::Array(vec![
CompileTimeDefineValue::Bool(true),
CompileTimeDefineValue::Undefined,
CompileTimeDefineValue::Evaluate("() => 1".into()),
]),
);
let compile_time_info = CompileTimeInfo::builder(env) let compile_time_info = CompileTimeInfo::builder(env)
.defines(defines.clone().resolved_cell()) .defines(defines.clone().resolved_cell())
.free_var_references(free_var_references!(..defines.into_iter()).resolved_cell()) .free_var_references(free_var_references!(..defines.into_iter()).resolved_cell())
......
...@@ -6,6 +6,30 @@ if (DEFINED_TRUE) { ...@@ -6,6 +6,30 @@ if (DEFINED_TRUE) {
console.log('DEFINED_VALUE') console.log('DEFINED_VALUE')
} }
if (!DEFINED_NULL) {
console.log('DEFINED_NULL', DEFINED_NULL)
}
if (DEFINED_INT) {
console.log('DEFINED_INT', DEFINED_INT)
}
if (DEFINED_FLOAT) {
console.log('DEFINED_FLOAT', DEFINED_FLOAT)
}
if (DEFINED_ARRAY) {
console.log('DEFINED_ARRAY', DEFINED_ARRAY)
}
if (DEFINED_EVALUATE) {
console.log('DEFINED_EVALUATE', DEFINED_EVALUATE)
}
if (DEFINED_EVALUATE_NESTED) {
console.log('DEFINED_EVALUATE_NESTED', DEFINED_EVALUATE_NESTED)
}
if (A.VERY.LONG.DEFINED.VALUE) { if (A.VERY.LONG.DEFINED.VALUE) {
console.log('A.VERY.LONG.DEFINED.VALUE') console.log('A.VERY.LONG.DEFINED.VALUE')
} }
......
...@@ -9,7 +9,37 @@ if ("TURBOPACK compile-time truthy", 1) { ...@@ -9,7 +9,37 @@ if ("TURBOPACK compile-time truthy", 1) {
if ("TURBOPACK compile-time truthy", 1) { if ("TURBOPACK compile-time truthy", 1) {
console.log('DEFINED_VALUE'); console.log('DEFINED_VALUE');
} }
if ("TURBOPACK compile-time value", JSON.parse('{"test":true}')) { if ("TURBOPACK compile-time truthy", 1) {
console.log('DEFINED_NULL', ("TURBOPACK compile-time value", null));
}
if ("TURBOPACK compile-time truthy", 1) {
console.log('DEFINED_INT', ("TURBOPACK compile-time value", 1));
}
if ("TURBOPACK compile-time truthy", 1) {
console.log('DEFINED_FLOAT', ("TURBOPACK compile-time value", 0.01));
}
if ("TURBOPACK compile-time truthy", 1) {
console.log('DEFINED_ARRAY', ("TURBOPACK compile-time value", [
("TURBOPACK compile-time value", false),
("TURBOPACK compile-time value", 0),
("TURBOPACK compile-time value", "1"),
("TURBOPACK compile-time value", {
"v": ("TURBOPACK compile-time value", "v")
}),
("TURBOPACK compile-time value", null)
]));
}
if ("TURBOPACK compile-time truthy", 1) {
console.log('DEFINED_EVALUATE', ("TURBOPACK compile-time value", 1 + 1));
}
if ("TURBOPACK compile-time truthy", 1) {
console.log('DEFINED_EVALUATE_NESTED', ("TURBOPACK compile-time value", [
("TURBOPACK compile-time value", true),
("TURBOPACK compile-time value", void 0),
("TURBOPACK compile-time value", ()=>1)
]));
}
if ("TURBOPACK compile-time truthy", 1) {
console.log('A.VERY.LONG.DEFINED.VALUE'); console.log('A.VERY.LONG.DEFINED.VALUE');
} }
if ("TURBOPACK compile-time truthy", 1) { if ("TURBOPACK compile-time truthy", 1) {
...@@ -18,7 +48,9 @@ if ("TURBOPACK compile-time truthy", 1) { ...@@ -18,7 +48,9 @@ if ("TURBOPACK compile-time truthy", 1) {
if ("TURBOPACK compile-time falsy", 0) //TURBOPACK unreachable if ("TURBOPACK compile-time falsy", 0) //TURBOPACK unreachable
; ;
var p = process; var p = process;
console.log(("TURBOPACK compile-time value", JSON.parse('{"test":true}'))); console.log(("TURBOPACK compile-time value", {
"test": ("TURBOPACK compile-time value", true)
}));
console.log(("TURBOPACK compile-time value", "value")); console.log(("TURBOPACK compile-time value", "value"));
console.log(("TURBOPACK compile-time value", "development")); console.log(("TURBOPACK compile-time value", "development"));
if ("TURBOPACK compile-time falsy", 0) //TURBOPACK unreachable if ("TURBOPACK compile-time falsy", 0) //TURBOPACK unreachable
...@@ -31,4 +63,4 @@ console.log(("TURBOPACK compile-time value", "/ROOT/turbopack/crates/turbopack-t ...@@ -31,4 +63,4 @@ console.log(("TURBOPACK compile-time value", "/ROOT/turbopack/crates/turbopack-t
}}), }}),
]); ]);
//# sourceMappingURL=4e721_crates_turbopack-tests_tests_snapshot_comptime_define_input_index_4d74c0a3.js.map //# sourceMappingURL=4e721_crates_turbopack-tests_tests_snapshot_comptime_define_input_index_4d74c0a3.js.map
\ No newline at end of file
...@@ -2,5 +2,5 @@ ...@@ -2,5 +2,5 @@
"version": 3, "version": 3,
"sources": [], "sources": [],
"sections": [ "sections": [
{"offset": {"line": 5, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/define/input/index.js"],"sourcesContent":["if (DEFINED_VALUE) {\n console.log('DEFINED_VALUE')\n}\n\nif (DEFINED_TRUE) {\n console.log('DEFINED_VALUE')\n}\n\nif (A.VERY.LONG.DEFINED.VALUE) {\n console.log('A.VERY.LONG.DEFINED.VALUE')\n}\n\nif (process.env.NODE_ENV) {\n console.log('something')\n}\n\nif (process.env.NODE_ENV === 'production') {\n console.log('production')\n}\n\nvar p = process\n\nconsole.log(A.VERY.LONG.DEFINED.VALUE)\nconsole.log(DEFINED_VALUE)\nconsole.log(p.env.NODE_ENV)\n\nif (p.env.NODE_ENV === 'production') {\n console.log('production')\n}\n\np.env.NODE_ENV == 'production'\n ? console.log('production')\n : console.log('development')\n\n// TODO short-circuit is not implemented yet\np.env.NODE_ENV != 'production' && console.log('development')\np.env.NODE_ENV == 'production' && console.log('production')\n\nconsole.log(__dirname)\n"],"names":[],"mappings":"AAAA,wCAAmB;IACjB,QAAQ,GAAG,CAAC;AACd;AAEA,wCAAkB;IAChB,QAAQ,GAAG,CAAC;AACd;AAEA,iEAA+B;IAC7B,QAAQ,GAAG,CAAC;AACd;AAEA,wCAA0B;IACxB,QAAQ,GAAG,CAAC;AACd;AAEA;;AAIA,IAAI,IAAI;AAER,QAAQ,GAAG;AACX,QAAQ,GAAG;AACX,QAAQ,GAAG;AAEX;;AAIA,sCACI,0BACA,QAAQ,GAAG,CAAC;AAEhB,4CAA4C;AAC5C,mDAAkB,gBAAgB,QAAQ,GAAG,CAAC;AAC9C,mDAAkB,gBAAgB,QAAQ,GAAG,CAAC;AAE9C,QAAQ,GAAG"}}] {"offset": {"line": 5, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/define/input/index.js"],"sourcesContent":["if (DEFINED_VALUE) {\n console.log('DEFINED_VALUE')\n}\n\nif (DEFINED_TRUE) {\n console.log('DEFINED_VALUE')\n}\n\nif (!DEFINED_NULL) {\n console.log('DEFINED_NULL', DEFINED_NULL)\n}\n\nif (DEFINED_INT) {\n console.log('DEFINED_INT', DEFINED_INT)\n}\n\nif (DEFINED_FLOAT) {\n console.log('DEFINED_FLOAT', DEFINED_FLOAT)\n}\n\nif (DEFINED_ARRAY) {\n console.log('DEFINED_ARRAY', DEFINED_ARRAY)\n}\n\nif (DEFINED_EVALUATE) {\n console.log('DEFINED_EVALUATE', DEFINED_EVALUATE)\n}\n\nif (DEFINED_EVALUATE_NESTED) {\n console.log('DEFINED_EVALUATE_NESTED', DEFINED_EVALUATE_NESTED)\n}\n\nif (A.VERY.LONG.DEFINED.VALUE) {\n console.log('A.VERY.LONG.DEFINED.VALUE')\n}\n\nif (process.env.NODE_ENV) {\n console.log('something')\n}\n\nif (process.env.NODE_ENV === 'production') {\n console.log('production')\n}\n\nvar p = process\n\nconsole.log(A.VERY.LONG.DEFINED.VALUE)\nconsole.log(DEFINED_VALUE)\nconsole.log(p.env.NODE_ENV)\n\nif (p.env.NODE_ENV === 'production') {\n console.log('production')\n}\n\np.env.NODE_ENV == 'production'\n ? console.log('production')\n : console.log('development')\n\n// TODO short-circuit is not implemented yet\np.env.NODE_ENV != 'production' && console.log('development')\np.env.NODE_ENV == 'production' && console.log('production')\n\nconsole.log(__dirname)\n"],"names":[],"mappings":"AAAA,wCAAmB;IACjB,QAAQ,GAAG,CAAC;AACd;AAEA,wCAAkB;IAChB,QAAQ,GAAG,CAAC;AACd;AAEA,wCAAmB;IACjB,QAAQ,GAAG,CAAC;AACd;AAEA,wCAAiB;IACf,QAAQ,GAAG,CAAC;AACd;AAEA,wCAAmB;IACjB,QAAQ,GAAG,CAAC;AACd;AAEA,wCAAmB;IACjB,QAAQ,GAAG,CAAC;;;;;;;;;AACd;AAEA,wCAAsB;IACpB,QAAQ,GAAG,CAAC,qDAzBd,IAAI;AA0BJ;AAEA,wCAA6B;IAC3B,QAAQ,GAAG,CAAC;;;yCA7Bd,IAAM;;AA8BN;AAEA,wCAA+B;IAC7B,QAAQ,GAAG,CAAC;AACd;AAEA,wCAA0B;IACxB,QAAQ,GAAG,CAAC;AACd;AAEA;;AAIA,IAAI,IAAI;AAER,QAAQ,GAAG;;;AACX,QAAQ,GAAG;AACX,QAAQ,GAAG;AAEX;;AAIA,sCACI,0BACA,QAAQ,GAAG,CAAC;AAEhB,4CAA4C;AAC5C,mDAAkB,gBAAgB,QAAQ,GAAG,CAAC;AAC9C,mDAAkB,gBAAgB,QAAQ,GAAG,CAAC;AAE9C,QAAQ,GAAG"}}]
} }
\ No newline at end of file
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