Skip to content
12 changes: 8 additions & 4 deletions crates/perry-codegen/src/expr/fs_await.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,15 +192,19 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result<String> {
// patterns eventually resolve. Without the timer ticks the
// await loop busy-waits forever.
ctx.current_block = wait_idx;
ctx.block().call_void("js_promise_run_microtasks", &[]);
ctx.block()
.call_void("js_promise_run_microtasks_await_loop", &[]);
// Drain the stdlib's tokio async queue — fetch, database
// queries, and other async stdlib operations queue their
// results via queue_promise_resolution and need this pump
// to actually resolve the promises on the main thread.
ctx.block().call_void("js_run_stdlib_pump", &[]);
let _ = ctx.block().call(I32, "js_timer_tick", &[]);
let _ = ctx.block().call(I32, "js_callback_timer_tick", &[]);
let _ = ctx.block().call(I32, "js_interval_timer_tick", &[]);
// #5437: tick through the await-loop entry, which suspends the
// timer dispatch guard — a busy-wait await inside a timer /
// setImmediate callback (every HTTP request handler) must still
// fire due timers or a setImmediate-scheduled resolution (React's
// server renderer) can never settle.
let _ = ctx.block().call(I32, "js_await_loop_tick_timers", &[]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

if !ctx.is_async_fn {
let wait_for_event_idx = ctx.new_block("await.wait_for_event");
Expand Down
2 changes: 2 additions & 0 deletions crates/perry-codegen/src/runtime_decls/strings_part2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,8 @@ pub(crate) fn declare_phase_b_strings_part2(module: &mut LlModule) {
// branch so `await thenable` enters the polling path.
module.declare_function("js_assimilate_thenable", DOUBLE, &[DOUBLE]);
module.declare_function("js_promise_run_microtasks", I32, &[]);
module.declare_function("js_promise_run_microtasks_await_loop", I32, &[]);
module.declare_function("js_await_loop_tick_timers", I32, &[]);
// ESM entry marker: first microtask drain finishes promise jobs before
// the nextTick queue (Node module-evaluation checkpoint ordering, #788).
module.declare_function("js_mark_entry_module_esm", VOID, &[]);
Expand Down
121 changes: 85 additions & 36 deletions crates/perry-hir/src/lower/expr_assign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -929,7 +929,28 @@ fn lower_assignment_target(
}

let object_expr = lower_expr(ctx, &member.obj)?;
let object = Box::new(object_expr.clone());
// #5437: `PutValueSet` / `PropertySet` carry the object expression
// in BOTH `target` and `receiver`, and codegen evaluates both. When
// the object is itself an assignment to a local — Next.js' React
// renderer does `(r = n2(t = new nX(t, ...), ...)).parentFlushed =
// !0` — duplicating it re-runs the assignment (and the nested `new
// nX`), so the Request was constructed twice with the already-
// reassigned `t` and its `resumableState` became another Request
// (dynamic-SSR 500). Evaluate the assignment ONCE as a prelude and
// read the just-assigned local back from both slots. Reusing the
// assignment's own already-slotted local avoids a fresh temp (which
// gets no codegen stack slot in expression position). Pure / non-
// assignment objects keep the long-standing duplicate-in-place
// shape so codegen fast paths and IR are unchanged.
let reuse_id = if let Expr::LocalSet(set_id, _) = &object_expr {
Some(*set_id)
} else {
None
};
let (mut prelude, object): (Option<Expr>, Box<Expr>) = match reuse_id {
Some(id) => (Some(object_expr), Box::new(Expr::LocalGet(id))),
None => (None, Box::new(object_expr.clone())),
};
match &member.prop {
ast::MemberProp::Ident(ident) => {
let property = ident.sym.to_string();
Expand All @@ -945,10 +966,13 @@ fn lower_assignment_target(
// writes — those are rare and meaningless on
// non-functions in practice).
if property == "prototype" {
return Ok(Expr::SetFunctionPrototype {
func: object,
proto: value,
});
return Ok(wrap_assign_object_prelude(
prelude.take(),
Expr::SetFunctionPrototype {
func: object,
proto: value,
},
));
}
// #1401: process.title = X — route through a runtime
// cell so subsequent reads see the new value. Without
Expand All @@ -962,13 +986,16 @@ fn lower_assignment_target(
}
}
}
Ok(Expr::PutValueSet {
target: object.clone(),
key: Box::new(Expr::String(property)),
value,
receiver: object,
strict: ctx.current_strict,
})
Ok(wrap_assign_object_prelude(
prelude.take(),
Expr::PutValueSet {
target: object.clone(),
key: Box::new(Expr::String(property)),
value,
receiver: object,
strict: ctx.current_strict,
},
))
}
ast::MemberProp::Computed(computed) => {
let index = Box::new(lower_expr(ctx, &computed.expr)?);
Expand All @@ -978,11 +1005,14 @@ fn lower_assignment_target(
if let Expr::LocalGet(id) = &*object {
if let Some((_, _, ty)) = ctx.locals.iter().find(|(_, lid, _)| lid == id) {
if matches!(ty, Type::Named(n) if n == "Uint8Array" || n == "Buffer") {
return Ok(Expr::Uint8ArraySet {
array: object,
index,
value,
});
return Ok(wrap_assign_object_prelude(
prelude.take(),
Expr::Uint8ArraySet {
array: object,
index,
value,
},
));
}
}
}
Expand All @@ -996,22 +1026,28 @@ fn lower_assignment_target(
&& key.chars().all(|c| c.is_ascii_digit())
&& !(key.len() > 1 && key.starts_with('0'));
if !is_numeric_string {
return Ok(Expr::PutValueSet {
target: object.clone(),
key: Box::new(Expr::String(key.clone())),
value,
receiver: object,
strict: ctx.current_strict,
});
return Ok(wrap_assign_object_prelude(
prelude.take(),
Expr::PutValueSet {
target: object.clone(),
key: Box::new(Expr::String(key.clone())),
value,
receiver: object,
strict: ctx.current_strict,
},
));
}
}
Ok(Expr::PutValueSet {
target: object.clone(),
key: index,
value,
receiver: object,
strict: ctx.current_strict,
})
Ok(wrap_assign_object_prelude(
prelude.take(),
Expr::PutValueSet {
target: object.clone(),
key: index,
value,
receiver: object,
strict: ctx.current_strict,
},
))
}
ast::MemberProp::PrivateName(private) => {
// Private field assignment: this.#field = value. Guard the
Expand All @@ -1024,11 +1060,14 @@ fn lower_assignment_target(
&property,
super::expr_member::PRIV_OP_WRITE,
);
Ok(Expr::PropertySet {
object,
property,
value,
})
Ok(wrap_assign_object_prelude(
prelude.take(),
Expr::PropertySet {
object,
property,
value,
},
))
}
}
}
Expand Down Expand Up @@ -1091,3 +1130,13 @@ fn lower_assignment_target(
other => Err(anyhow!("Unsupported assignment target: {:?}", other)),
}
}

/// #5437: prepend a once-evaluated object prelude (`LocalSet(tmp, object)`)
/// in front of an assignment expression that references the temp from both
/// `target` and `receiver`. `None` ⇒ the object was pure and used in place.
fn wrap_assign_object_prelude(prelude: Option<Expr>, e: Expr) -> Expr {
match prelude {
Some(p) => Expr::Sequence(vec![p, e]),
None => e,
}
}
59 changes: 43 additions & 16 deletions crates/perry-hir/src/lower/lower_expr/assignment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,30 @@ pub(crate) fn lower_expr_assignment(
}
}
let object_expr = lower_expr(ctx, &member.obj)?;
let object = Box::new(object_expr.clone());
match &member.prop {
// #5437: `PutValueSet` (and the private-name `PropertySet`) carry
// the object expression in BOTH `target` and `receiver`, and codegen
// evaluates both. When the object is itself an assignment to a local
// — Next.js' React renderer does
// `(r = n2(t = new nX(...), ...)).parentFlushed = !0` — duplicating
// it re-runs the assignment (and the nested `new nX`), constructing
// the Request twice with the now-reassigned `t` so its
// resumableState became another Request → dynamic-SSR 500. Evaluate
// the assignment ONCE as a prelude and read the just-assigned local
// back from both slots (reusing the assignment's own already-slotted
// local — a fresh temp gets no codegen stack slot in expression
// position). Pure / non-assignment objects keep the long-standing
// duplicate-in-place shape so codegen fast paths and IR are
// unchanged.
let reuse_id = if let Expr::LocalSet(set_id, _) = &object_expr {
Some(*set_id)
} else {
None
};
let (prelude, object): (Option<Expr>, Box<Expr>) = match reuse_id {
Some(id) => (Some(object_expr), Box::new(Expr::LocalGet(id))),
None => (None, Box::new(object_expr.clone())),
};
let result = match &member.prop {
ast::MemberProp::Ident(ident) => {
let property = ident.sym.to_string();
// Issue #711 part 2: `<expr>.prototype = <value>`
Expand All @@ -111,28 +133,29 @@ pub(crate) fn lower_expr_assignment(
// `someClass.prototype = X` writes on non-function
// values).
if property == "prototype" {
return Ok(Expr::SetFunctionPrototype {
Expr::SetFunctionPrototype {
func: object,
proto: value,
});
}
} else {
Expr::PutValueSet {
target: object.clone(),
key: Box::new(Expr::String(property)),
value,
receiver: object,
strict: ctx.current_strict,
}
}
Ok(Expr::PutValueSet {
target: object.clone(),
key: Box::new(Expr::String(property)),
value,
receiver: object,
strict: ctx.current_strict,
})
}
ast::MemberProp::Computed(computed) => {
let index = Box::new(lower_expr(ctx, &computed.expr)?);
Ok(Expr::PutValueSet {
Expr::PutValueSet {
target: object.clone(),
key: index,
value,
receiver: object,
strict: ctx.current_strict,
})
}
}
ast::MemberProp::PrivateName(private) => {
let property = format!("#{}", private.name);
Expand All @@ -142,13 +165,17 @@ pub(crate) fn lower_expr_assignment(
&property,
expr_member::PRIV_OP_WRITE,
);
Ok(Expr::PropertySet {
Expr::PropertySet {
object,
property,
value,
})
}
}
}
};
Ok(match prelude {
Some(p) => Expr::Sequence(vec![p, result]),
None => result,
})
}
// Recursively unwrap parens and type annotations
ast::Expr::Paren(paren) => lower_expr_assignment(ctx, &paren.expr, value),
Expand Down
44 changes: 40 additions & 4 deletions crates/perry-hir/src/lower_decl/class_captures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,21 +215,36 @@ pub fn synthesize_class_captures(
let mut id_map: std::collections::HashMap<LocalId, LocalId> =
std::collections::HashMap::new();
let mut prologue: Vec<Stmt> = Vec::new();
for &outer_id in &captures_vec {
for (index, &outer_id) in captures_vec.iter().enumerate() {
let new_id = ctx.fresh_local();
id_map.insert(outer_id, new_id);
let ty = captured_outer_types
.get(&outer_id)
.cloned()
.unwrap_or(Type::Any);
// FIELD-FIRST with a decl-site-snapshot fallback: the
// `this.__perry_cap_*` stash is written by the constructor AFTER
// `super()` returns, but a method can run EARLIER — a base-class
// constructor may virtual-dispatch into this class's override
// (Next.js: base `Server`'s ctor calls `this.getHasStaticDir()`,
// the `NextNodeServer` override, which reads the module-level
// `_fs` interop binding through its cap field → it read
// `undefined` and threw at boot, #5437). When the field is still
// undefined, fall back to the class's decl-site capture snapshot
// (same machinery as the ctor param rebinds above).
prologue.push(Stmt::Let {
id: new_id,
name: format!("__perry_cap_{}", outer_id),
ty,
mutable: true,
init: Some(Expr::PropertyGet {
object: Box::new(Expr::This),
property: format!("__perry_cap_{}", outer_id),
init: Some(Expr::ClassCaptureValue {
class_name: name.to_string(),
index: index as u32,
fallback: Some(Box::new(Expr::PropertyGet {
object: Box::new(Expr::This),
property: format!("__perry_cap_{}", outer_id),
})),
prefer_fallback: true,
}),
});
}
Expand Down Expand Up @@ -538,6 +553,7 @@ pub fn synthesize_class_captures(
// must already see the recovered value. Only the `this.__perry_cap_* =
// param` field STASHES must wait until after `super()` (no `this` exists
// before super) AND after all user stmts (see comment below).
let rebind_count = rebind_stmts.len();
for (i, stmt) in rebind_stmts.into_iter().enumerate() {
ctor.body.insert(i, stmt);
}
Expand All @@ -548,6 +564,26 @@ pub fn synthesize_class_captures(
// Inserting immediately after `super()` captured the pre-mutation value.
// Insert stashes before each explicit `return` so they run on every exit
// path, then append at the end for the fall-through path.
//
// BUT the stashes must ALSO run right after `super()` (or at entry for a
// non-derived ctor): the ctor body may invoke instance methods
// (`this.has = this.getHas()`), and a method reading a captured outer
// resolves it through the `this.__perry_cap_*` field. Stashing only at
// the end left those reads undefined — Next.js's base `Server`
// constructor calls `this.getHasStaticDir()`, which reads the
// module-level `_fs` interop binding via its cap field and threw
// "Cannot read properties of undefined (reading 'default')" at boot
// (#5437). So stash EARLY for intra-ctor method calls AND re-stash at
// the end / before returns so post-`super()` mutations still win in the
// final state. The assignments are idempotent.
let super_pos = ctor
.body
.iter()
.position(|s| matches!(s, Stmt::Expr(Expr::SuperCall(_) | Expr::SuperCallSpread(_))));
let early_insert_at = super_pos.map(|p| p + 1).unwrap_or(rebind_count);
for (i, stmt) in assignment_stmts.iter().cloned().enumerate() {
ctor.body.insert(early_insert_at + i, stmt);
}
insert_stashes_before_returns(&mut ctor.body, &assignment_stmts);
for stmt in assignment_stmts {
ctor.body.push(stmt);
Expand Down
Loading
Loading