diff --git a/crates/perry-hir/src/lower_decl/body_stmt.rs b/crates/perry-hir/src/lower_decl/body_stmt.rs index f9339940c0b..ad3f4a3e295 100644 --- a/crates/perry-hir/src/lower_decl/body_stmt.rs +++ b/crates/perry-hir/src/lower_decl/body_stmt.rs @@ -309,16 +309,40 @@ pub fn lower_body_stmt(ctx: &mut LoweringContext, stmt: &ast::Stmt) -> Result` ctor params. Static `new C()` // sites still pass captures as trailing args directly. - if let Some(captured) = ctx.lookup_class_captures(&class.name) { - if !captured.is_empty() { - let captures: Vec = - captured.iter().map(|id| Expr::LocalGet(*id)).collect(); - result.push(Stmt::Expr(Expr::RegisterClassCaptures { - class_name: class.name.clone(), - captures, - })); - } + let captured_exprs: Vec = ctx + .lookup_class_captures(&class.name) + .map(|ids| ids.iter().map(|id| Expr::LocalGet(*id)).collect()) + .unwrap_or_default(); + if !captured_exprs.is_empty() { + result.push(Stmt::Expr(Expr::RegisterClassCaptures { + class_name: class.name.clone(), + captures: captured_exprs.clone(), + })); } + // #6465: a capturing class DECLARATION in a factory needs + // per-evaluation semantics, same as a class expression. + // `RegisterClassCaptures` above is a class-id-keyed, + // last-wins registry — when the enclosing function runs more + // than once (effect's `makeException`, called once per + // exception kind), every escaped class value replayed the + // LAST call's captures: all of effect's core error classes + // reported `_tag` "TimeoutException", masking the real error + // in any `Cause.pretty` output and breaking every + // `catchTag`-style dispatch. Bind the declared name to a + // `ClassExprFresh` value (the #1772/#1787 machinery class + // EXPRESSIONS already use) so each evaluation carries its own + // captured environment on its own heap class object. Scoped + // to capture-only classes: one with static state keeps the + // shared-template path, whose interleaved static-init + // statements below target the template by name. Prototype + // identity is still shared per template — the remaining gap + // tracked on #6465. + let has_static_state = !class.static_fields.is_empty() + || class + .static_methods + .iter() + .any(|m| m.name.starts_with("__perry_static_init_")); + let fresh_binding = !captured_exprs.is_empty() && !has_static_state; // Static field initializers + static blocks for a // function-nested class. The module-level path // (`lower/stmt.rs`) emits these into `module.init`; here they @@ -335,7 +359,31 @@ pub fn lower_body_stmt(ctx: &mut LoweringContext, stmt: &ast::Stmt) -> Result Result