Unverified Commit 23b741a9 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

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

Handle control flow _operators_ in the turbopack analyzer in order to trigger dead code handling and trim dependencies from dead branches.

This was partially implemented but we were not producing the actual effects for them.

I explored adding support for `?.` as well, but it is a massive complexity issue, so for now that is deferred.
parent a5230703
...@@ -41,9 +41,12 @@ pub fn benchmark(c: &mut Criterion) { ...@@ -41,9 +41,12 @@ pub fn benchmark(c: &mut Criterion) {
for result in results { for result in results {
let entry = result.unwrap(); let entry = result.unwrap();
if entry.file_type().unwrap().is_dir() { if entry.file_type().unwrap().is_dir() {
let name = entry.file_name().into_string().unwrap();
let input = entry.path().join("input.js"); 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 cm = Arc::new(SourceMap::new(FilePathMapping::empty())); let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
let fm = cm.load_file(&input).unwrap(); let fm = cm.load_file(&input).unwrap();
GLOBALS.set(&swc_core::common::Globals::new(), || { GLOBALS.set(&swc_core::common::Globals::new(), || {
......
...@@ -45,6 +45,11 @@ impl EffectsBlock { ...@@ -45,6 +45,11 @@ impl EffectsBlock {
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.effects.is_empty() self.effects.is_empty()
} }
fn normalize(&mut self) {
for e in self.effects.iter_mut() {
e.normalize();
}
}
} }
#[derive(Debug)] #[derive(Debug)]
...@@ -70,47 +75,52 @@ pub enum ConditionalKind { ...@@ -70,47 +75,52 @@ pub enum ConditionalKind {
r#else: Box<EffectsBlock>, r#else: Box<EffectsBlock>,
}, },
/// The expression on the right side of the `&&` operator. /// The expression on the right side of the `&&` operator.
And { expr: Box<EffectsBlock> }, And { rhs_effects: Vec<Effect> },
/// The expression on the right side of the `||` operator. /// The expression on the right side of the `||` operator.
Or { expr: Box<EffectsBlock> }, Or { rhs_effects: Vec<Effect> },
/// The expression on the right side of the `??` operator. /// The expression on the right side of the `??` operator.
NullishCoalescing { expr: Box<EffectsBlock> }, NullishCoalescing { rhs_effects: Vec<Effect> },
/// The expression on the right side of a labeled statement. /// The expression on the right side of a labeled statement.
Labeled { body: Box<EffectsBlock> }, Labeled { body: Box<EffectsBlock> },
} }
impl ConditionalKind { 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. /// Normalizes all contained values.
pub fn normalize(&mut self) { pub fn normalize(&mut self) {
match self { match self {
ConditionalKind::If { then: block } ConditionalKind::If { then: block }
| ConditionalKind::Else { r#else: block } | ConditionalKind::Else { r#else: block }
| ConditionalKind::And { expr: block, .. } | ConditionalKind::Labeled { body: block } => block.normalize(),
| ConditionalKind::Or { expr: block, .. }
| ConditionalKind::NullishCoalescing { expr: block, .. } => {
for effect in &mut block.effects {
effect.normalize();
}
}
ConditionalKind::IfElse { then, r#else, .. } ConditionalKind::IfElse { then, r#else, .. }
| ConditionalKind::Ternary { then, r#else, .. } => { | ConditionalKind::Ternary { then, r#else, .. } => {
for effect in &mut then.effects { then.normalize();
effect.normalize(); r#else.normalize();
} }
for effect in &mut r#else.effects { ConditionalKind::And { rhs_effects, .. }
| ConditionalKind::Or { rhs_effects, .. }
| ConditionalKind::NullishCoalescing { rhs_effects, .. } => {
for effect in rhs_effects.iter_mut() {
effect.normalize(); effect.normalize();
} }
} }
ConditionalKind::IfElseMultiple { then, r#else, .. } => { ConditionalKind::IfElseMultiple { then, r#else, .. } => {
for block in then.iter_mut().chain(r#else.iter_mut()) { for block in then.iter_mut().chain(r#else.iter_mut()) {
for effect in &mut block.effects { block.normalize();
effect.normalize();
}
}
}
ConditionalKind::Labeled { body } => {
for effect in &mut body.effects {
effect.normalize();
} }
} }
} }
...@@ -131,9 +141,7 @@ impl EffectArg { ...@@ -131,9 +141,7 @@ impl EffectArg {
EffectArg::Value(value) => value.normalize(), EffectArg::Value(value) => value.normalize(),
EffectArg::Closure(value, effects) => { EffectArg::Closure(value, effects) => {
value.normalize(); value.normalize();
for effect in &mut effects.effects { effects.normalize();
effect.normalize();
}
} }
EffectArg::Spread => {} EffectArg::Spread => {}
} }
...@@ -2352,6 +2360,49 @@ impl VisitAstPath for Analyzer<'_> { ...@@ -2352,6 +2360,49 @@ 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>( fn visit_if_stmt<'ast: 'r, 'r>(
&mut self, &mut self,
stmt: &'ast IfStmt, stmt: &'ast IfStmt,
...@@ -2622,7 +2673,7 @@ impl Analyzer<'_> { ...@@ -2622,7 +2673,7 @@ impl Analyzer<'_> {
{ {
return; return;
} }
let condition = Box::new(self.eval_context.eval(test)); let condition = self.eval_context.eval(test);
if condition.is_unknown() { if condition.is_unknown() {
if let Some(mut then) = then { if let Some(mut then) = then {
self.effects.append(&mut then.effects); self.effects.append(&mut then.effects);
...@@ -2632,6 +2683,7 @@ impl Analyzer<'_> { ...@@ -2632,6 +2683,7 @@ impl Analyzer<'_> {
} }
return; return;
} }
let condition = Box::new(condition);
match (early_return_when_true, early_return_when_false) { match (early_return_when_true, early_return_when_false) {
(true, false) => { (true, false) => {
self.early_return_stack.push(EarlyReturn::Conditional { self.early_return_stack.push(EarlyReturn::Conditional {
...@@ -2659,20 +2711,21 @@ impl Analyzer<'_> { ...@@ -2659,20 +2711,21 @@ impl Analyzer<'_> {
} }
(false, false) | (true, true) => { (false, false) | (true, true) => {
let kind = match (then, r#else) { let kind = match (then, r#else) {
(Some(then), Some(r#else)) => ConditionalKind::IfElse { then, r#else }, (Some(then), Some(r#else)) => Some(ConditionalKind::IfElse { then, r#else }),
(Some(then), None) => ConditionalKind::If { then }, (Some(then), None) => Some(ConditionalKind::If { then }),
(None, Some(r#else)) => ConditionalKind::Else { r#else }, (None, Some(r#else)) => Some(ConditionalKind::Else { r#else }),
(None, None) => { (None, None) => None,
// No effects, ignore
return;
}
}; };
self.add_effect(Effect::Conditional { if let Some(kind) = kind
condition, && !kind.is_empty()
kind: Box::new(kind), {
ast_path: as_parent_path_with(ast_path, condition_ast_kind), self.add_effect(Effect::Conditional {
span, 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 { if early_return_when_false && early_return_when_true {
self.early_return_stack.push(EarlyReturn::Always { self.early_return_stack.push(EarlyReturn::Always {
prev_effects: take(&mut self.effects), prev_effects: take(&mut self.effects),
...@@ -2691,7 +2744,10 @@ impl Analyzer<'_> { ...@@ -2691,7 +2744,10 @@ impl Analyzer<'_> {
span: Span, span: Span,
mut cond_kind: ConditionalKind, mut cond_kind: ConditionalKind,
) { ) {
let condition = Box::new(self.eval_context.eval(test)); if cond_kind.is_empty() {
return;
}
let condition = self.eval_context.eval(test);
if condition.is_unknown() { if condition.is_unknown() {
match &mut cond_kind { match &mut cond_kind {
ConditionalKind::If { then } => { ConditionalKind::If { then } => {
...@@ -2713,10 +2769,10 @@ impl Analyzer<'_> { ...@@ -2713,10 +2769,10 @@ impl Analyzer<'_> {
self.effects.append(&mut block.effects); self.effects.append(&mut block.effects);
} }
} }
ConditionalKind::And { expr } ConditionalKind::And { rhs_effects }
| ConditionalKind::Or { expr } | ConditionalKind::Or { rhs_effects }
| ConditionalKind::NullishCoalescing { expr } => { | ConditionalKind::NullishCoalescing { rhs_effects } => {
self.effects.append(&mut expr.effects); self.effects.append(rhs_effects);
} }
ConditionalKind::Labeled { body } => { ConditionalKind::Labeled { body } => {
self.effects.append(&mut body.effects); self.effects.append(&mut body.effects);
...@@ -2724,7 +2780,7 @@ impl Analyzer<'_> { ...@@ -2724,7 +2780,7 @@ impl Analyzer<'_> {
} }
} else { } else {
self.add_effect(Effect::Conditional { self.add_effect(Effect::Conditional {
condition, condition: Box::new(condition),
kind: Box::new(cond_kind), kind: Box::new(cond_kind),
ast_path: as_parent_path_with(ast_path, ast_kind), ast_path: as_parent_path_with(ast_path, ast_kind),
span, span,
......
...@@ -4107,15 +4107,14 @@ mod tests { ...@@ -4107,15 +4107,14 @@ mod tests {
.await; .await;
resolved.push((format!("{parent} -> {i} conditional"), condition)); resolved.push((format!("{parent} -> {i} conditional"), condition));
match *kind { match *kind {
ConditionalKind::If { then } => { ConditionalKind::If { then: block }
queue | ConditionalKind::Else { r#else: block }
.extend(then.effects.into_iter().rev().map(|e| (i, e))); | ConditionalKind::Labeled { body: block } => {
}
ConditionalKind::Else { r#else } => {
queue.extend( queue.extend(
r#else.effects.into_iter().rev().map(|e| (i, e)), block.effects.into_iter().rev().map(|e| (i, e)),
); );
} }
ConditionalKind::IfElse { then, r#else } ConditionalKind::IfElse { then, r#else }
| ConditionalKind::Ternary { then, r#else } => { | ConditionalKind::Ternary { then, r#else } => {
queue.extend( queue.extend(
...@@ -4136,12 +4135,10 @@ mod tests { ...@@ -4136,12 +4135,10 @@ mod tests {
); );
} }
} }
ConditionalKind::And { expr } ConditionalKind::And { rhs_effects }
| ConditionalKind::Or { expr } | ConditionalKind::Or { rhs_effects }
| ConditionalKind::NullishCoalescing { expr } | ConditionalKind::NullishCoalescing { rhs_effects } => {
| ConditionalKind::Labeled { body: expr } => { queue.extend(rhs_effects.into_iter().rev().map(|e| (i, e)));
queue
.extend(expr.effects.into_iter().rev().map(|e| (i, e)));
} }
}; };
steps steps
......
...@@ -35,6 +35,7 @@ use crate::{ ...@@ -35,6 +35,7 @@ use crate::{
exports_info::{ExportsInfoBinding, ExportsInfoRef}, exports_info::{ExportsInfoBinding, ExportsInfoRef},
ident::IdentReplacement, ident::IdentReplacement,
member::MemberReplacement, member::MemberReplacement,
replace_parent_with_child::ReplaceParentWithChild,
require_context::RequireContextAssetReferenceCodeGen, require_context::RequireContextAssetReferenceCodeGen,
unreachable::Unreachable, unreachable::Unreachable,
worker::WorkerAssetReferenceCodeGen, worker::WorkerAssetReferenceCodeGen,
...@@ -199,6 +200,7 @@ pub enum CodeGen { ...@@ -199,6 +200,7 @@ pub enum CodeGen {
RequireContextAssetReferenceCodeGen(RequireContextAssetReferenceCodeGen), RequireContextAssetReferenceCodeGen(RequireContextAssetReferenceCodeGen),
UrlAssetReferenceCodeGen(UrlAssetReferenceCodeGen), UrlAssetReferenceCodeGen(UrlAssetReferenceCodeGen),
WorkerAssetReferenceCodeGen(WorkerAssetReferenceCodeGen), WorkerAssetReferenceCodeGen(WorkerAssetReferenceCodeGen),
ReplaceParentWithChild(ReplaceParentWithChild),
} }
impl CodeGen { impl CodeGen {
...@@ -212,8 +214,8 @@ impl CodeGen { ...@@ -212,8 +214,8 @@ impl CodeGen {
match self { match self {
Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(ctx).await, Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(ctx).await,
Self::CjsRequireCacheAccess(v) => v.code_generation(ctx).await, Self::CjsRequireCacheAccess(v) => v.code_generation(ctx).await,
Self::ConstantConditionCodeGen(v) => v.code_generation(ctx).await, Self::ConstantConditionCodeGen(v) => v.code_generation(),
Self::ConstantValueCodeGen(v) => v.code_generation(ctx).await, Self::ConstantValueCodeGen(v) => v.code_generation(),
Self::DynamicExpression(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::EsmBinding(v) => v.code_generation(ctx, scope_hoisting_context).await,
Self::EsmModuleItem(v) => v.code_generation(ctx).await, Self::EsmModuleItem(v) => v.code_generation(ctx).await,
...@@ -231,6 +233,7 @@ impl CodeGen { ...@@ -231,6 +233,7 @@ impl CodeGen {
Self::RequireContextAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::RequireContextAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::UrlAssetReferenceCodeGen(v) => v.code_generation(ctx).await, Self::UrlAssetReferenceCodeGen(v) => v.code_generation(ctx).await,
Self::WorkerAssetReferenceCodeGen(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, '_> { ...@@ -88,7 +88,7 @@ impl<'a> ApplyVisitors<'a, '_> {
let kind = ast_path[index]; let kind = ast_path[index];
if let Some(visitors) = find_range(current_visitors, &kind, index) { if let Some(visitors) = find_range(current_visitors, &kind, index) {
// visitors contains all items that match kind at index. Some of them terminate // visitors contains all items that match kind at index. Some of them terminate
// here, some need furth visiting. The terminating items are at the start due to // here, some need further visiting. The terminating items are at the start due to
// sorting of the list. // sorting of the list.
index += 1; index += 1;
......
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use swc_core::quote; use swc_core::quote;
use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbopack_core::chunk::ChunkingContext;
use super::AstPath; use super::AstPath;
use crate::{ use crate::{
...@@ -32,10 +31,7 @@ impl ConstantConditionCodeGen { ...@@ -32,10 +31,7 @@ impl ConstantConditionCodeGen {
ConstantConditionCodeGen { value, path } ConstantConditionCodeGen { value, path }
} }
pub async fn code_generation( pub fn code_generation(&self) -> Result<CodeGeneration> {
&self,
_chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> {
let value = self.value; let value = self.value;
let visitors = [create_visitor!( let visitors = [create_visitor!(
exact, exact,
......
...@@ -9,8 +9,8 @@ use swc_core::{ ...@@ -9,8 +9,8 @@ use swc_core::{
quote, quote,
}; };
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbopack_core::{chunk::ChunkingContext, compile_time_info::CompileTimeDefineValue}; use turbopack_core::compile_time_info::CompileTimeDefineValue;
use super::AstPath; use super::AstPath;
use crate::{ use crate::{
...@@ -39,15 +39,11 @@ impl ConstantValueCodeGen { ...@@ -39,15 +39,11 @@ impl ConstantValueCodeGen {
pub fn new(value: CompileTimeDefineValue, path: AstPath) -> Self { pub fn new(value: CompileTimeDefineValue, path: AstPath) -> Self {
ConstantValueCodeGen { value, path } ConstantValueCodeGen { value, path }
} }
pub async fn code_generation( pub fn code_generation(&self) -> Result<CodeGeneration> {
&self,
_chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> {
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| {
// TODO: avoid this clone *expr = define_env_to_expr(&value);
*expr = define_env_to_expr((value).clone());
}); });
Ok(CodeGeneration::visitors(vec![visitor])) Ok(CodeGeneration::visitors(vec![visitor]))
...@@ -60,7 +56,7 @@ impl From<ConstantValueCodeGen> for CodeGen { ...@@ -60,7 +56,7 @@ impl From<ConstantValueCodeGen> for CodeGen {
} }
} }
fn define_env_to_expr(value: CompileTimeDefineValue) -> Expr { fn define_env_to_expr(value: &CompileTimeDefineValue) -> Expr {
match value { match value {
CompileTimeDefineValue::Null => { CompileTimeDefineValue::Null => {
quote!("(\"TURBOPACK compile-time value\", null)" as Expr) quote!("(\"TURBOPACK compile-time value\", null)" as Expr)
...@@ -71,23 +67,23 @@ fn define_env_to_expr(value: CompileTimeDefineValue) -> Expr { ...@@ -71,23 +67,23 @@ fn define_env_to_expr(value: CompileTimeDefineValue) -> Expr {
CompileTimeDefineValue::Bool(false) => { CompileTimeDefineValue::Bool(false) => {
quote!("(\"TURBOPACK compile-time value\", false)" as Expr) quote!("(\"TURBOPACK compile-time value\", false)" as Expr)
} }
CompileTimeDefineValue::Number(ref n) => { CompileTimeDefineValue::Number(n) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = n.parse::<f64>().unwrap().into()) quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = n.parse::<f64>().unwrap().into())
} }
CompileTimeDefineValue::String(ref s) => { CompileTimeDefineValue::String(s) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = s.to_string().into()) quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = s.to_string().into())
} }
CompileTimeDefineValue::Array(a) => { CompileTimeDefineValue::Array(a) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = Expr::Array(ArrayLit { quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = Expr::Array(ArrayLit {
span: DUMMY_SP, span: DUMMY_SP,
elems: a.into_iter().map(|i| Some(define_env_to_expr(i).into())).collect(), elems: a.iter().map(|i| Some(define_env_to_expr(i).into())).collect(),
})) }))
} }
CompileTimeDefineValue::Object(m) => { CompileTimeDefineValue::Object(m) => {
quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = Expr::Object(ObjectLit { quote!("(\"TURBOPACK compile-time value\", $e)" as Expr, e: Expr = Expr::Object(ObjectLit {
span: DUMMY_SP, span: DUMMY_SP,
props: m props: m
.into_iter() .iter()
.map(|(k, v)| { .map(|(k, v)| {
swc_core::ecma::ast::PropOrSpread::Prop( swc_core::ecma::ast::PropOrSpread::Prop(
Prop::KeyValue(KeyValueProp { Prop::KeyValue(KeyValueProp {
...@@ -103,7 +99,7 @@ fn define_env_to_expr(value: CompileTimeDefineValue) -> Expr { ...@@ -103,7 +99,7 @@ fn define_env_to_expr(value: CompileTimeDefineValue) -> Expr {
CompileTimeDefineValue::Undefined => { CompileTimeDefineValue::Undefined => {
quote!("(\"TURBOPACK compile-time value\", void 0)" as Expr) quote!("(\"TURBOPACK compile-time value\", void 0)" as Expr)
} }
CompileTimeDefineValue::Evaluate(ref s) => parse_single_expr_lit(s.clone()), CompileTimeDefineValue::Evaluate(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 { Call {
func: FreeVar( func: FreeVar(
"import", "import",
...@@ -415,187 +265,6 @@ ...@@ -415,187 +265,6 @@
], ],
span: 57..64, 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 { Call {
func: FreeVar( func: FreeVar(
"import", "import",
......
0 -> 1 conditional = true 0 -> 1 call = import*0*("a")
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* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 5 free var = FreeVar(process) 0 -> 4 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 -> 7 call = import*0*( 0 -> 5 call = import*0*(
(???*1* ? "next/dist/compiled/@vercel/og/index.edge.js" : "next/dist/compiled/@vercel/og/index.node.js") (???*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 - *0* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
...@@ -16,21 +11,21 @@ ...@@ -16,21 +11,21 @@
⚠️ nested operation ⚠️ nested operation
- *2* process.env: The Node.js process.env property: https://nodejs.org/api/process.html#processenv - *2* process.env: The Node.js process.env property: https://nodejs.org/api/process.html#processenv
0 -> 8 conditional = true 0 -> 6 conditional = true
8 -> 9 call = import*0*("a") 6 -> 7 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* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
8 -> 10 call = import*0*("b") 6 -> 8 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* import: The dynamic import() method from the ESM specification: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
0 -> 11 conditional = true 0 -> 9 conditional = true
0 -> 14 conditional = true 0 -> 12 conditional = true
14 -> 15 unreachable = ???*0* 12 -> 13 unreachable = ???*0*
- *0* unreachable - *0* unreachable
⚠️ This value might have side effects ⚠️ This value might have side effects
0 -> 16 call = import*0*("c") 0 -> 14 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 - *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,11 +7,7 @@ ...@@ -7,11 +7,7 @@
0 -> 7 free var = FreeVar(console) 0 -> 7 free var = FreeVar(console)
0 -> 8 conditional = ???*0* 0 -> 8 member call = ???*0*["debug"]("####", ???*1*, (???*2* ? true : false))
- *0* arguments[1]
⚠️ function calls are not analyzed yet
0 -> 9 member call = ???*0*["debug"]("####", ???*1*, (???*2* ? true : false))
- *0* FreeVar(console) - *0* FreeVar(console)
⚠️ unknown global ⚠️ unknown global
⚠️ This value might have side effects ⚠️ This value might have side effects
...@@ -20,11 +16,7 @@ ...@@ -20,11 +16,7 @@
- *2* arguments[1] - *2* arguments[1]
⚠️ function calls are not analyzed yet ⚠️ function calls are not analyzed yet
0 -> 12 conditional = ???*0* 0 -> 12 call = (...) => parent(???*0*, (???*2* ? ???*3* : (???*10* | undefined)), (???*15* | {}){truthy})
- *0* arguments[1]
⚠️ function calls are not analyzed yet
0 -> 14 call = (...) => parent(???*0*, (???*2* ? ???*3* : (???*10* | undefined)), (???*15* | {}){truthy})
- *0* ???*1*[key] - *0* ???*1*[key]
⚠️ unknown object ⚠️ unknown object
- *1* arguments[0] - *1* arguments[0]
...@@ -64,8 +56,8 @@ ...@@ -64,8 +56,8 @@
- *16* arguments[2] - *16* arguments[2]
⚠️ function calls are not analyzed yet ⚠️ function calls are not analyzed yet
0 -> 15 unreachable = ???*0* 0 -> 13 unreachable = ???*0*
- *0* unreachable - *0* unreachable
⚠️ This value might have side effects ⚠️ This value might have side effects
0 -> 16 call = (...) => parent({"wrapper": {"data": {"key": {}}}}, "", {}) 0 -> 14 call = (...) => parent({"wrapper": {"data": {"key": {}}}}, "", {})
0 -> 1 free var = FreeVar(global) 0 -> 1 conditional = 3
0 -> 2 free var = FreeVar(global) 1 -> 2 free var = FreeVar(global)
0 -> 3 free var = FreeVar(global) 0 -> 3 conditional = 2
0 -> 4 free var = FreeVar(global) 3 -> 4 free var = FreeVar(global)
0 -> 5 free var = FreeVar(global) 0 -> 5 conditional = 2
0 -> 6 free var = FreeVar(global) 5 -> 6 free var = FreeVar(global)
0 -> 7 free var = FreeVar(global) 0 -> 7 conditional = 0
0 -> 8 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)
...@@ -28,14 +28,6 @@ ...@@ -28,14 +28,6 @@
- *0* unreachable - *0* unreachable
⚠️ This value might have side effects ⚠️ This value might have side effects
0 -> 12 conditional = ((0 | ???*0*) === 0) 0 -> 13 unreachable = ???*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 - *0* unreachable
⚠️ This value might have side effects ⚠️ This value might have side effects
...@@ -7,13 +7,7 @@ ...@@ -7,13 +7,7 @@
0 -> 5 free var = FreeVar(JSON) 0 -> 5 free var = FreeVar(JSON)
0 -> 6 conditional = ((???*0* | "true") === "true") 0 -> 6 member call = ???*0*["stringify"](
- *0* ???*1*["variable"]
⚠️ unknown object
- *1* arguments[0]
⚠️ function calls are not analyzed yet
0 -> 7 member call = ???*0*["stringify"](
{ {
"condition": ((???*1* | "true") === "true"), "condition": ((???*1* | "true") === "true"),
"buggedConditionalCheck": (???*3* ? "true" : "false") "buggedConditionalCheck": (???*3* ? "true" : "false")
...@@ -33,11 +27,11 @@ ...@@ -33,11 +27,11 @@
- *5* arguments[0] - *5* arguments[0]
⚠️ function calls are not analyzed yet ⚠️ function calls are not analyzed yet
0 -> 8 unreachable = ???*0* 0 -> 7 unreachable = ???*0*
- *0* unreachable - *0* unreachable
⚠️ This value might have side effects ⚠️ This value might have side effects
0 -> 9 call = (...) => FreeVar(JSON)["stringify"]( 0 -> 8 call = (...) => FreeVar(JSON)["stringify"](
{ {
"condition": (variable === "true"), "condition": (variable === "true"),
"buggedConditionalCheck": ((variable === "true") ? "true" : "false") "buggedConditionalCheck": ((variable === "true") ? "true" : "false")
......
...@@ -56,7 +56,6 @@ p.env.NODE_ENV == 'production' ...@@ -56,7 +56,6 @@ p.env.NODE_ENV == 'production'
? console.log('production') ? console.log('production')
: console.log('development') : 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('development')
p.env.NODE_ENV == 'production' && console.log('production') p.env.NODE_ENV == 'production' && console.log('production')
......
...@@ -54,9 +54,8 @@ console.log(("TURBOPACK compile-time value", "development")); ...@@ -54,9 +54,8 @@ console.log(("TURBOPACK compile-time value", "development"));
if ("TURBOPACK compile-time falsy", 0) //TURBOPACK unreachable if ("TURBOPACK compile-time falsy", 0) //TURBOPACK unreachable
; ;
("TURBOPACK compile-time falsy", 0) ? "TURBOPACK unreachable" : console.log('development'); ("TURBOPACK compile-time falsy", 0) ? "TURBOPACK unreachable" : console.log('development');
// TODO short-circuit is not implemented yet "TURBOPACK simplified expression", console.log('development');
("TURBOPACK compile-time value", "development") != 'production' && console.log('development'); "TURBOPACK simplified expression", ("TURBOPACK compile-time value", "development") == 'production';
("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")); console.log(("TURBOPACK compile-time value", "/ROOT/turbopack/crates/turbopack-tests/tests/snapshot/comptime/define/input"));
}), }),
]); ]);
......
...@@ -2,5 +2,5 @@ ...@@ -2,5 +2,5 @@
"version": 3, "version": 3,
"sources": [], "sources": [],
"sections": [ "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\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"}}] {"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"}}]
} }
\ 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