Unverified Commit 78f6bea7 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Revert "[turbopack] Model `||`, `&&`, and `??` as control flow operators (#85837)" (#86432)

This reverts commit 23b741a9.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent eb8fea0f
......@@ -41,12 +41,9 @@ pub fn benchmark(c: &mut Criterion) {
for result in results {
let entry = result.unwrap();
if entry.file_type().unwrap().is_dir() {
let input = entry.path().join("input.js");
if !input.exists() {
eprintln!("Missing file: {input:?} skipping");
continue;
}
let name = entry.file_name().into_string().unwrap();
let input = entry.path().join("input.js");
let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
let fm = cm.load_file(&input).unwrap();
GLOBALS.set(&swc_core::common::Globals::new(), || {
......
......@@ -45,11 +45,6 @@ impl EffectsBlock {
pub fn is_empty(&self) -> bool {
self.effects.is_empty()
}
fn normalize(&mut self) {
for e in self.effects.iter_mut() {
e.normalize();
}
}
}
#[derive(Debug)]
......@@ -75,52 +70,47 @@ pub enum ConditionalKind {
r#else: Box<EffectsBlock>,
},
/// The expression on the right side of the `&&` operator.
And { rhs_effects: Vec<Effect> },
And { expr: Box<EffectsBlock> },
/// The expression on the right side of the `||` operator.
Or { rhs_effects: Vec<Effect> },
Or { expr: Box<EffectsBlock> },
/// The expression on the right side of the `??` operator.
NullishCoalescing { rhs_effects: Vec<Effect> },
NullishCoalescing { expr: Box<EffectsBlock> },
/// The expression on the right side of a labeled statement.
Labeled { body: Box<EffectsBlock> },
}
impl ConditionalKind {
fn is_empty(&self) -> bool {
match self {
ConditionalKind::If { then: block }
| ConditionalKind::Else { r#else: block }
| ConditionalKind::Labeled { body: block } => block.effects.is_empty(),
ConditionalKind::IfElse { then, r#else, .. }
| ConditionalKind::Ternary { then, r#else, .. } => then.is_empty() && r#else.is_empty(),
ConditionalKind::And { rhs_effects, .. }
| ConditionalKind::Or { rhs_effects, .. }
| ConditionalKind::NullishCoalescing { rhs_effects, .. } => rhs_effects.is_empty(),
ConditionalKind::IfElseMultiple { then, r#else, .. } => {
then.iter().chain(r#else.iter()).all(|b| b.is_empty())
}
}
}
/// Normalizes all contained values.
pub fn normalize(&mut self) {
match self {
ConditionalKind::If { then: block }
| ConditionalKind::Else { r#else: block }
| ConditionalKind::Labeled { body: block } => block.normalize(),
| ConditionalKind::And { expr: block, .. }
| ConditionalKind::Or { expr: block, .. }
| ConditionalKind::NullishCoalescing { expr: block, .. } => {
for effect in &mut block.effects {
effect.normalize();
}
}
ConditionalKind::IfElse { then, r#else, .. }
| ConditionalKind::Ternary { then, r#else, .. } => {
then.normalize();
r#else.normalize();
}
ConditionalKind::And { rhs_effects, .. }
| ConditionalKind::Or { rhs_effects, .. }
| ConditionalKind::NullishCoalescing { rhs_effects, .. } => {
for effect in rhs_effects.iter_mut() {
for effect in &mut then.effects {
effect.normalize();
}
for effect in &mut r#else.effects {
effect.normalize();
}
}
ConditionalKind::IfElseMultiple { then, r#else, .. } => {
for block in then.iter_mut().chain(r#else.iter_mut()) {
block.normalize();
for effect in &mut block.effects {
effect.normalize();
}
}
}
ConditionalKind::Labeled { body } => {
for effect in &mut body.effects {
effect.normalize();
}
}
}
......@@ -141,7 +131,9 @@ impl EffectArg {
EffectArg::Value(value) => value.normalize(),
EffectArg::Closure(value, effects) => {
value.normalize();
effects.normalize();
for effect in &mut effects.effects {
effect.normalize();
}
}
EffectArg::Spread => {}
}
......@@ -2524,49 +2516,6 @@ impl VisitAstPath for Analyzer<'_> {
);
}
fn visit_bin_expr<'ast: 'r, 'r>(
&mut self,
expr: &'ast BinExpr,
ast_path: &mut AstNodePath<AstParentNodeRef<'r>>,
) {
// Some binary operators have control flow semantics.
match expr.op {
BinaryOp::LogicalAnd | BinaryOp::LogicalOr | BinaryOp::NullishCoalescing => {
// Visit the left hand node
{
let mut ast_path =
ast_path.with_guard(AstParentNodeRef::BinExpr(expr, BinExprField::Left));
expr.left.visit_with_ast_path(self, &mut ast_path);
};
let prev_effects = take(&mut self.effects);
let rhs_effects = {
let mut ast_path =
ast_path.with_guard(AstParentNodeRef::BinExpr(expr, BinExprField::Right));
expr.right.visit_with_ast_path(self, &mut ast_path);
take(&mut self.effects)
};
self.effects = prev_effects;
self.add_conditional_effect(
&expr.left,
ast_path,
AstParentKind::BinExpr(BinExprField::Left),
expr.span(),
match expr.op {
BinaryOp::LogicalAnd => ConditionalKind::And { rhs_effects },
BinaryOp::LogicalOr => ConditionalKind::Or { rhs_effects },
BinaryOp::NullishCoalescing => {
ConditionalKind::NullishCoalescing { rhs_effects }
}
_ => unreachable!(),
},
);
}
_ => <BinExpr as VisitWithAstPath<Self>>::visit_children_with_ast_path(
expr, self, ast_path,
),
}
}
fn visit_if_stmt<'ast: 'r, 'r>(
&mut self,
stmt: &'ast IfStmt,
......@@ -2795,7 +2744,7 @@ impl Analyzer<'_> {
{
return;
}
let condition = self.eval_context.eval(test);
let condition = Box::new(self.eval_context.eval(test));
if condition.is_unknown() {
if let Some(mut then) = then {
self.effects.append(&mut then.effects);
......@@ -2805,7 +2754,6 @@ impl Analyzer<'_> {
}
return;
}
let condition = Box::new(condition);
match (early_return_when_true, early_return_when_false) {
(true, false) => {
let early_return = EarlyReturn::Conditional {
......@@ -2835,21 +2783,20 @@ impl Analyzer<'_> {
}
(false, false) | (true, true) => {
let kind = match (then, r#else) {
(Some(then), Some(r#else)) => Some(ConditionalKind::IfElse { then, r#else }),
(Some(then), None) => Some(ConditionalKind::If { then }),
(None, Some(r#else)) => Some(ConditionalKind::Else { r#else }),
(None, None) => None,
(Some(then), Some(r#else)) => ConditionalKind::IfElse { then, r#else },
(Some(then), None) => ConditionalKind::If { then },
(None, Some(r#else)) => ConditionalKind::Else { r#else },
(None, None) => {
// No effects, ignore
return;
}
};
if let Some(kind) = kind
&& !kind.is_empty()
{
self.add_effect(Effect::Conditional {
condition,
kind: Box::new(kind),
ast_path: as_parent_path_with(ast_path, condition_ast_kind),
span,
});
}
self.add_effect(Effect::Conditional {
condition,
kind: Box::new(kind),
ast_path: as_parent_path_with(ast_path, condition_ast_kind),
span,
});
if early_return_when_false && early_return_when_true {
let early_return = EarlyReturn::Always {
prev_effects: take(&mut self.effects),
......@@ -2869,10 +2816,7 @@ impl Analyzer<'_> {
span: Span,
mut cond_kind: ConditionalKind,
) {
if cond_kind.is_empty() {
return;
}
let condition = self.eval_context.eval(test);
let condition = Box::new(self.eval_context.eval(test));
if condition.is_unknown() {
match &mut cond_kind {
ConditionalKind::If { then } => {
......@@ -2894,10 +2838,10 @@ impl Analyzer<'_> {
self.effects.append(&mut block.effects);
}
}
ConditionalKind::And { rhs_effects }
| ConditionalKind::Or { rhs_effects }
| ConditionalKind::NullishCoalescing { rhs_effects } => {
self.effects.append(rhs_effects);
ConditionalKind::And { expr }
| ConditionalKind::Or { expr }
| ConditionalKind::NullishCoalescing { expr } => {
self.effects.append(&mut expr.effects);
}
ConditionalKind::Labeled { body } => {
self.effects.append(&mut body.effects);
......@@ -2905,7 +2849,7 @@ impl Analyzer<'_> {
}
} else {
self.add_effect(Effect::Conditional {
condition: Box::new(condition),
condition,
kind: Box::new(cond_kind),
ast_path: as_parent_path_with(ast_path, ast_kind),
span,
......
......@@ -4110,14 +4110,15 @@ mod tests {
.await;
resolved.push((format!("{parent} -> {i} conditional"), condition));
match *kind {
ConditionalKind::If { then: block }
| ConditionalKind::Else { r#else: block }
| ConditionalKind::Labeled { body: block } => {
ConditionalKind::If { then } => {
queue
.extend(then.effects.into_iter().rev().map(|e| (i, e)));
}
ConditionalKind::Else { r#else } => {
queue.extend(
block.effects.into_iter().rev().map(|e| (i, e)),
r#else.effects.into_iter().rev().map(|e| (i, e)),
);
}
ConditionalKind::IfElse { then, r#else }
| ConditionalKind::Ternary { then, r#else } => {
queue.extend(
......@@ -4138,10 +4139,12 @@ mod tests {
);
}
}
ConditionalKind::And { rhs_effects }
| ConditionalKind::Or { rhs_effects }
| ConditionalKind::NullishCoalescing { rhs_effects } => {
queue.extend(rhs_effects.into_iter().rev().map(|e| (i, e)));
ConditionalKind::And { expr }
| ConditionalKind::Or { expr }
| ConditionalKind::NullishCoalescing { expr }
| ConditionalKind::Labeled { body: expr } => {
queue
.extend(expr.effects.into_iter().rev().map(|e| (i, e)));
}
};
steps
......
......@@ -35,7 +35,6 @@ use crate::{
exports_info::{ExportsInfoBinding, ExportsInfoRef},
ident::IdentReplacement,
member::MemberReplacement,
replace_parent_with_child::ReplaceParentWithChild,
require_context::RequireContextAssetReferenceCodeGen,
unreachable::Unreachable,
worker::WorkerAssetReferenceCodeGen,
......@@ -200,7 +199,6 @@ pub enum CodeGen {
RequireContextAssetReferenceCodeGen(RequireContextAssetReferenceCodeGen),
UrlAssetReferenceCodeGen(UrlAssetReferenceCodeGen),
WorkerAssetReferenceCodeGen(WorkerAssetReferenceCodeGen),
ReplaceParentWithChild(ReplaceParentWithChild),
}
impl CodeGen {
......@@ -214,8 +212,8 @@ impl CodeGen {
match self {
Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(ctx).await,
Self::CjsRequireCacheAccess(v) => v.code_generation(ctx).await,
Self::ConstantConditionCodeGen(v) => v.code_generation(),
Self::ConstantValueCodeGen(v) => v.code_generation(),
Self::ConstantConditionCodeGen(v) => v.code_generation(ctx).await,
Self::ConstantValueCodeGen(v) => v.code_generation(ctx).await,
Self::DynamicExpression(v) => v.code_generation(ctx).await,
Self::EsmBinding(v) => v.code_generation(ctx, scope_hoisting_context).await,
Self::EsmModuleItem(v) => v.code_generation(ctx).await,
......@@ -233,7 +231,6 @@ impl CodeGen {
Self::RequireContextAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::UrlAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::WorkerAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::ReplaceParentWithChild(v) => v.code_generation(),
}
}
}
......
......@@ -88,7 +88,7 @@ impl<'a> ApplyVisitors<'a, '_> {
let kind = ast_path[index];
if let Some(visitors) = find_range(current_visitors, &kind, index) {
// visitors contains all items that match kind at index. Some of them terminate
// here, some need further visiting. The terminating items are at the start due to
// here, some need furth visiting. The terminating items are at the start due to
// sorting of the list.
index += 1;
......
use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::quote;
use turbo_tasks::{NonLocalValue, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbopack_core::chunk::ChunkingContext;
use super::AstPath;
use crate::{
......@@ -31,7 +32,10 @@ impl ConstantConditionCodeGen {
ConstantConditionCodeGen { value, path }
}
pub fn code_generation(&self) -> Result<CodeGeneration> {
pub async fn code_generation(
&self,
_chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> {
let value = self.value;
let visitors = [create_visitor!(
exact,
......
......@@ -9,8 +9,8 @@ use swc_core::{
quote,
};
use turbo_rcstr::RcStr;
use turbo_tasks::{NonLocalValue, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbopack_core::compile_time_info::CompileTimeDefineValue;
use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbopack_core::{chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue};
use super::AstPath;
use crate::{
......@@ -39,11 +39,15 @@ impl ConstantValueCodeGen {
pub fn new(value: CompileTimeDefineValue, path: AstPath) -> Self {
ConstantValueCodeGen { value, path }
}
pub fn code_generation(&self) -> Result<CodeGeneration> {
pub async fn code_generation(
&self,
_chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> {
let value = self.value.clone();
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| {
*expr = define_env_to_expr(&value);
// TODO: avoid this clone
*expr = define_env_to_expr((value).clone());
});
Ok(CodeGeneration::visitors(vec![visitor]))
......@@ -56,7 +60,7 @@ impl From<ConstantValueCodeGen> for CodeGen {
}
}
fn define_env_to_expr(value: &CompileTimeDefineValue) -> Expr {
fn define_env_to_expr(value: CompileTimeDefineValue) -> Expr {
match value {
CompileTimeDefineValue::Null => {
quote!("(\"TURBOPACK compile-time value\", null)" as Expr)
......@@ -67,23 +71,23 @@ fn define_env_to_expr(value: &CompileTimeDefineValue) -> Expr {
CompileTimeDefineValue::Bool(false) => {
quote!("(\"TURBOPACK compile-time value\", false)" as Expr)
}
CompileTimeDefineValue::Number(n) => {
CompileTimeDefineValue::Number(ref n) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = n.parse::<f64>().unwrap().into())
}
CompileTimeDefineValue::String(s) => {
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.iter().map(|i| Some(define_env_to_expr(i).into())).collect(),
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
.iter()
.into_iter()
.map(|(k, v)| {
swc_core::ecma::ast::PropOrSpread::Prop(
Prop::KeyValue(KeyValueProp {
......@@ -99,7 +103,7 @@ fn define_env_to_expr(value: &CompileTimeDefineValue) -> Expr {
CompileTimeDefineValue::Undefined => {
quote!("(\"TURBOPACK compile-time value\", void 0)" as Expr)
}
CompileTimeDefineValue::Evaluate(s) => parse_single_expr_lit(s.clone()),
CompileTimeDefineValue::Evaluate(ref s) => parse_single_expr_lit(s.clone()),
}
}
......
use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::{
common::util::take::Take,
ecma::{
ast::{BinExpr, Expr},
visit::{AstParentKind, fields::BinExprField},
},
quote,
};
use turbo_tasks::{NonLocalValue, debug::ValueDebugFormat, trace::TraceRawVcs};
use super::AstPath;
use crate::{
code_gen::{CodeGen, CodeGeneration},
create_visitor,
};
/// Used to replace expressions like `<truthy> || <something>` with `<truthy>`
#[derive(
PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue, Debug, Hash,
)]
pub struct ReplaceParentWithChild {
path: AstPath,
}
impl ReplaceParentWithChild {
pub fn new(path: AstPath) -> Self {
Self { path }
}
pub fn code_generation(&self) -> Result<CodeGeneration> {
let parent_path = &self.path[0..(self.path.len() - 1)];
let to_replace_with = *self.path.last().unwrap();
let AstParentKind::BinExpr(field) = to_replace_with else {
panic!("invalid path, must point at a BinExpr not a {to_replace_with:?}");
};
let visitor = create_visitor!(parent_path, visit_mut_expr, |parent_expr: &mut Expr| {
match parent_expr {
Expr::Bin(BinExpr { left, right, .. }) => {
let child = match field {
BinExprField::Left => left.take(),
BinExprField::Right => right.take(),
_ => {
panic!("Can only replace with expression children, got {field:?}");
}
};
*parent_expr = quote!("(\"TURBOPACK simplified expression\", $e)" as Expr, e: Expr = *child);
}
_ => {
// do nothing, the AST must have been modified and our operator or child
// removed.
}
};
});
Ok(CodeGeneration::visitors(vec![visitor]))
}
}
impl From<ReplaceParentWithChild> for CodeGen {
fn from(val: ReplaceParentWithChild) -> Self {
CodeGen::ReplaceParentWithChild(val)
}
}
[
Conditional {
condition: Constant(
True,
),
kind: Ternary {
then: EffectsBlock {
effects: [],
range: Exact(
[
Program(
Module,
),
Module(
Body(
0,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Cond,
),
CondExpr(
Cons,
),
],
),
},
else: EffectsBlock {
effects: [],
range: Exact(
[
Program(
Module,
),
Module(
Body(
0,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Cond,
),
CondExpr(
Alt,
),
],
),
},
},
ast_path: [
Program(
Module,
),
Module(
Body(
0,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Cond,
),
CondExpr(
Test,
),
],
span: 18..34,
},
Call {
func: FreeVar(
"import",
......@@ -265,6 +415,187 @@
],
span: 57..64,
},
Conditional {
condition: Binary(
7,
Member(
5,
Member(
3,
FreeVar(
"process",
),
Constant(
Str(
Atom(
"env",
),
),
),
),
Constant(
Str(
Atom(
"NEXT_RUNTIME",
),
),
),
),
StrictEqual,
Constant(
Str(
Atom(
"edge",
),
),
),
),
kind: Ternary {
then: EffectsBlock {
effects: [],
range: Exact(
[
Program(
Module,
),
Module(
Body(
1,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Cond,
),
CondExpr(
Cons,
),
],
),
},
else: EffectsBlock {
effects: [],
range: Exact(
[
Program(
Module,
),
Module(
Body(
1,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Cond,
),
CondExpr(
Alt,
),
],
),
},
},
ast_path: [
Program(
Module,
),
Module(
Body(
1,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Call,
),
CallExpr(
Args(
0,
),
),
ExprOrSpread(
Expr,
),
Expr(
Cond,
),
CondExpr(
Test,
),
],
span: 57..196,
},
Call {
func: FreeVar(
"import",
......
0 -> 1 call = import*0*("a")
0 -> 1 conditional = true
0 -> 2 call = import*0*("a")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 4 free var = FreeVar(process)
0 -> 5 free var = FreeVar(process)
0 -> 6 conditional = (process.env*0*["NEXT_RUNTIME"] === "edge")
- *0* process.env: The Node.js process.env property: https://nodejs.org/api/process.html#processenv
0 -> 5 call = import*0*(
0 -> 7 call = import*0*(
(???*1* ? "next/dist/compiled/@vercel/og/index.edge.js" : "next/dist/compiled/@vercel/og/index.node.js")
)
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
......@@ -11,21 +16,21 @@
⚠️ nested operation
- *2* process.env: The Node.js process.env property: https://nodejs.org/api/process.html#processenv
0 -> 6 conditional = true
0 -> 8 conditional = true
6 -> 7 call = import*0*("a")
8 -> 9 call = import*0*("a")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
6 -> 8 call = import*0*("b")
8 -> 10 call = import*0*("b")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 9 conditional = true
0 -> 11 conditional = true
0 -> 12 conditional = true
0 -> 14 conditional = true
12 -> 13 unreachable = ???*0*
14 -> 15 unreachable = ???*0*
- *0* unreachable
⚠️ This value might have side effects
0 -> 14 call = import*0*("c")
0 -> 16 call = import*0*("c")
- *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
......@@ -7,7 +7,11 @@
0 -> 7 free var = FreeVar(console)
0 -> 8 member call = ???*0*["debug"]("####", ???*1*, (???*2* ? true : false))
0 -> 8 conditional = ???*0*
- *0* arguments[1]
⚠️ function calls are not analyzed yet
0 -> 9 member call = ???*0*["debug"]("####", ???*1*, (???*2* ? true : false))
- *0* FreeVar(console)
⚠️ unknown global
⚠️ This value might have side effects
......@@ -16,7 +20,11 @@
- *2* arguments[1]
⚠️ function calls are not analyzed yet
0 -> 12 call = (...) => parent(???*0*, (???*2* ? ???*3* : (???*10* | undefined)), (???*15* | {}){truthy})
0 -> 12 conditional = ???*0*
- *0* arguments[1]
⚠️ function calls are not analyzed yet
0 -> 14 call = (...) => parent(???*0*, (???*2* ? ???*3* : (???*10* | undefined)), (???*15* | {}){truthy})
- *0* ???*1*[key]
⚠️ unknown object
- *1* arguments[0]
......@@ -56,8 +64,8 @@
- *16* arguments[2]
⚠️ function calls are not analyzed yet
0 -> 13 unreachable = ???*0*
0 -> 15 unreachable = ???*0*
- *0* unreachable
⚠️ This value might have side effects
0 -> 14 call = (...) => parent({"wrapper": {"data": {"key": {}}}}, "", {})
0 -> 16 call = (...) => parent({"wrapper": {"data": {"key": {}}}}, "", {})
0 -> 1 conditional = 3
0 -> 1 free var = FreeVar(global)
1 -> 2 free var = FreeVar(global)
0 -> 2 free var = FreeVar(global)
0 -> 3 conditional = 2
0 -> 3 free var = FreeVar(global)
3 -> 4 free var = FreeVar(global)
0 -> 4 free var = FreeVar(global)
0 -> 5 conditional = 2
0 -> 5 free var = FreeVar(global)
5 -> 6 free var = FreeVar(global)
0 -> 6 free var = FreeVar(global)
0 -> 7 conditional = 0
0 -> 7 free var = FreeVar(global)
7 -> 8 free var = FreeVar(global)
0 -> 9 free var = FreeVar(global)
0 -> 10 conditional = true
10 -> 11 free var = FreeVar(global)
0 -> 12 free var = FreeVar(global)
0 -> 13 conditional = false
13 -> 14 free var = FreeVar(global)
0 -> 8 free var = FreeVar(global)
......@@ -28,6 +28,14 @@
- *0* unreachable
⚠️ This value might have side effects
0 -> 13 unreachable = ???*0*
0 -> 12 conditional = ((0 | ???*0*) === 0)
- *0* (???*1* + ???*2*)
⚠️ nested operation
- *1* clientComponentLoadTimes
⚠️ circular variable reference
- *2* unsupported expression
⚠️ This value might have side effects
0 -> 14 unreachable = ???*0*
- *0* unreachable
⚠️ This value might have side effects
......@@ -7,7 +7,13 @@
0 -> 5 free var = FreeVar(JSON)
0 -> 6 member call = ???*0*["stringify"](
0 -> 6 conditional = ((???*0* | "true") === "true")
- *0* ???*1*["variable"]
⚠️ unknown object
- *1* arguments[0]
⚠️ function calls are not analyzed yet
0 -> 7 member call = ???*0*["stringify"](
{
"condition": ((???*1* | "true") === "true"),
"buggedConditionalCheck": (???*3* ? "true" : "false")
......@@ -27,11 +33,11 @@
- *5* arguments[0]
⚠️ function calls are not analyzed yet
0 -> 7 unreachable = ???*0*
0 -> 8 unreachable = ???*0*
- *0* unreachable
⚠️ This value might have side effects
0 -> 8 call = (...) => FreeVar(JSON)["stringify"](
0 -> 9 call = (...) => FreeVar(JSON)["stringify"](
{
"condition": (variable === "true"),
"buggedConditionalCheck": ((variable === "true") ? "true" : "false")
......
......@@ -56,6 +56,7 @@ p.env.NODE_ENV == 'production'
? console.log('production')
: console.log('development')
// TODO short-circuit is not implemented yet
p.env.NODE_ENV != 'production' && console.log('development')
p.env.NODE_ENV == 'production' && console.log('production')
......
......@@ -54,8 +54,9 @@ console.log(("TURBOPACK compile-time value", "development"));
if ("TURBOPACK compile-time falsy", 0) //TURBOPACK unreachable
;
("TURBOPACK compile-time falsy", 0) ? "TURBOPACK unreachable" : console.log('development');
"TURBOPACK simplified expression", console.log('development');
"TURBOPACK simplified expression", ("TURBOPACK compile-time value", "development") == 'production';
// TODO short-circuit is not implemented yet
("TURBOPACK compile-time value", "development") != 'production' && console.log('development');
("TURBOPACK compile-time value", "development") == 'production' && console.log('production');
console.log(("TURBOPACK compile-time value", "/ROOT/turbopack/crates/turbopack-tests/tests/snapshot/comptime/define/input"));
}),
]);
......
......@@ -2,5 +2,5 @@
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 3, "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\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;mCAEkB,QAAQ,GAAG,CAAC;mCAC9C,mDAAkB;AAElB,QAAQ,GAAG"}}]
{"offset": {"line": 3, "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