js2zig_core/zigir/emit/stmt/decl.rs
1// zigir/emit/stmt/decl.rs
2// Typedef, closure, variable, function, and class declaration emission.
3
4use crate::types::ZigType;
5use crate::zigir::emit::Emitter;
6use crate::zigir::emit::helpers::{EmitterHelpers, format_param_with_rest, format_return_type};
7use crate::zigir::types::{
8 IrAssignTarget, IrBlock, IrClassDecl, IrClassField, IrClassMethod, IrClosureStruct, IrExpr,
9 IrFnDecl, IrStmt, IrTypedef, IrVarDecl,
10};
11use std::collections::HashSet;
12
13/// Pick a type-appropriate zero value for a pre-declared constructor `var`
14/// when the field has no explicit `default` (R8-C7 + R8-E4/C6).
15///
16/// Zig requires every `var` to have an initialiser. We use the most natural
17/// "empty" value per ZigType; complex/owning types (Map, Set, ArrayList,
18/// BigInt, JsError, NamedStruct) fall back to `undefined` because they have
19/// no const-evaluable zero state. JS semantics for an uninitialised field is
20/// `undefined`, which lines up with `undefined` here for the dynamic types.
21/// For the common scalar types we pick a real zero so the value is safe to
22/// read even if the constructor never assigns the field.
23fn field_zero_value(ty: &ZigType) -> &'static str {
24 match ty {
25 ZigType::I64 | ZigType::Anytype | ZigType::AnytypeReturn => "0",
26 ZigType::F64 => "0.0",
27 ZigType::Bool => "false",
28 ZigType::Str => "\"\"",
29 // ArrayList has a const-evaluable empty state.
30 ZigType::ArrayList(_) => ".empty",
31 // JsAny / JsSymbol / BigInt / JsError / NamedStruct / Struct / AsyncIo
32 // — no const-zero; `undefined` is used intentionally as a bit pattern
33 // that will be overwritten before any read (the constructor assigns
34 // these fields before they're accessed). Using `undefined` here is
35 // safe because these are owning types stored by reference/pointer;
36 // the undefined value is never dereferenced or deinitialized.
37 _ => "undefined",
38 }
39}
40
41/// R8-E4/C6: Walk the constructor body and collect every identifier that is
42/// the target of an `IrStmt::Assign` anywhere in it (recursing through
43/// if/while/for/for-of/for-in/switch/try/block bodies AND destructuring
44/// targets). Zig 0.16.0 ast-check rejects `var` declarations that are never
45/// mutated with `"local variable is never mutated; consider using 'const'"`,
46/// so the Emitter must use `const` for pre-declared ctor fields that the
47/// constructor body never reassigns.
48///
49/// Destructure targets are included because `const { a, b } = obj` followed
50/// by a use of `a` near the struct return still has the binding declared as
51/// `const` by the Emitter's destructure path — but a *destructuring
52/// assignment* (`{ a, b } = obj;` — no `const`/`var` keyword) lowers to an
53/// `IrStmt::Assign { target: Destructure(...) }` that does mutate each
54/// binding, so those bindings count as "assigned" too and should be
55/// pre-declared `var` here to keep the rewrite legal at any scope.
56fn collect_assigned_idents_in_block(block: &IrBlock) -> HashSet<String> {
57 let mut out = HashSet::new();
58 collect_assigned_idents(&block.stmts, &mut out);
59 out
60}
61
62fn collect_assigned_idents(stmts: &[IrStmt], out: &mut HashSet<String>) {
63 for stmt in stmts {
64 match stmt {
65 IrStmt::Assign { target, .. } => match target {
66 IrAssignTarget::Ident(id) => {
67 out.insert(id.js_name.clone());
68 }
69 IrAssignTarget::Destructure(bindings) => {
70 for b in bindings {
71 out.insert(b.pattern.js_name.clone());
72 }
73 }
74 _ => {}
75 },
76 // C9: IrStmt::Expr can contain IrExpr::Update (field++) or
77 // IrExpr::Assign (field += val) with Ident targets produced by
78 // try_rewrite_this_field_assignment. Also covers BlockExpr
79 // (BigInt postfix expansion).
80 IrStmt::Expr(expr) => collect_assigned_idents_in_expr(expr, out),
81 IrStmt::If { then, else_, .. } => {
82 collect_assigned_idents(&then.stmts, out);
83 if let Some(eb) = else_ {
84 collect_assigned_idents(&eb.stmts, out);
85 }
86 }
87 IrStmt::While { body, .. } | IrStmt::DoWhile { body, .. } => {
88 collect_assigned_idents(&body.stmts, out);
89 }
90 // C9: also scan init and update (e.g., for (this.x = 0; ...; this.x++) {})
91 IrStmt::For {
92 init, update, body, ..
93 } => {
94 if let Some(i) = init {
95 collect_assigned_idents(std::slice::from_ref(i.as_ref()), out);
96 }
97 if let Some(u) = update {
98 collect_assigned_idents(std::slice::from_ref(u.as_ref()), out);
99 }
100 collect_assigned_idents(&body.stmts, out);
101 }
102 IrStmt::ForIn { body, .. } | IrStmt::ForOf { body, .. } => {
103 collect_assigned_idents(&body.stmts, out);
104 }
105 IrStmt::Switch { cases, .. } => {
106 for case in cases {
107 collect_assigned_idents(&case.body, out);
108 }
109 }
110 IrStmt::Try {
111 try_block,
112 catch_block,
113 finally,
114 ..
115 } => {
116 collect_assigned_idents(&try_block.stmts, out);
117 collect_assigned_idents(&catch_block.stmts, out);
118 if let Some(fb) = finally {
119 collect_assigned_idents(&fb.stmts, out);
120 }
121 }
122 IrStmt::Block(b) => collect_assigned_idents(&b.stmts, out),
123 _ => {}
124 }
125 }
126}
127
128/// C9: Scan an IrExpr for Ident-targeted mutations (Update / Assign).
129/// Handles compound assignments (`field += val`) and increment/decrement
130/// (`field++`) that are lowered as `IrStmt::Expr(IrExpr::Assign/Update{...})`
131/// rather than `IrStmt::Assign{...}`. Also recurses into BlockExpr (BigInt
132/// postfix expansion).
133fn collect_assigned_idents_in_expr(expr: &IrExpr, out: &mut HashSet<String>) {
134 match expr {
135 IrExpr::Update { target, .. } | IrExpr::Assign { target, .. } => {
136 if let IrAssignTarget::Ident(id) = target.as_ref() {
137 out.insert(id.js_name.clone());
138 }
139 }
140 IrExpr::BlockExpr { body, .. } => {
141 collect_assigned_idents(body, out);
142 }
143 _ => {}
144 }
145}
146
147/// R8-E5/C1: Check whether a class method body mutates `self` — i.e.,
148/// contains any `this.field = ...` assignment (an assignment whose target
149/// is an `IrAssignTarget::Member` on `IrExpr::This`).
150///
151/// If so, the method signature must use `self: *@This()` (mutable pointer)
152/// because Zig rejects assignment to a by-value parameter. Non-mutating
153/// methods keep the cheaper `self: @This()` (by-value) form.
154///
155/// In the IR, `this.x = v` inside an ExpressionStatement is lowered as
156/// `IrStmt::Expr(IrExpr::Assign { target: Member { object: This, .. }, .. })`,
157/// NOT as `IrStmt::Assign`. Similarly `++this.x` becomes
158/// `IrStmt::Expr(IrExpr::Update { target: Member { object: This, .. }, .. })`
159/// (non-BigInt) or `IrStmt::Expr(IrExpr::BlockExpr { body: [..., Expr(Assign { .. })], .. })`
160/// (BigInt). All three forms must be detected.
161fn method_mutates_self(body: &IrBlock) -> bool {
162 /// Returns true if the assignment target is `this.field` (a Member on This).
163 fn target_is_self_member(target: &IrAssignTarget) -> bool {
164 matches!(
165 target,
166 IrAssignTarget::Member { object, .. }
167 if matches!(object.as_ref(), IrExpr::This)
168 )
169 }
170
171 /// Returns true if an expression mutates `self` — i.e., it is an
172 /// assignment or update expression (possibly wrapped in a BlockExpr)
173 /// whose target is `this.field`.
174 fn expr_mutates_self(expr: &IrExpr) -> bool {
175 match expr {
176 IrExpr::Assign { target, .. } => target_is_self_member(target.as_ref()),
177 IrExpr::Update { target, .. } => target_is_self_member(target.as_ref()),
178 IrExpr::BlockExpr { body, result, .. } => {
179 stmts_mutate_self(body) || expr_mutates_self(result.as_ref())
180 }
181 _ => false,
182 }
183 }
184
185 fn stmts_mutate_self(stmts: &[IrStmt]) -> bool {
186 stmts.iter().any(stmt_mutates_self)
187 }
188
189 fn stmt_mutates_self(stmt: &IrStmt) -> bool {
190 match stmt {
191 IrStmt::Assign { target, .. } => target_is_self_member(target),
192 IrStmt::Expr(expr) => expr_mutates_self(expr),
193 IrStmt::If { then, else_, .. } => {
194 stmts_mutate_self(&then.stmts)
195 || else_
196 .as_ref()
197 .is_some_and(|eb| stmts_mutate_self(&eb.stmts))
198 }
199 IrStmt::While { body, .. } | IrStmt::DoWhile { body, .. } => {
200 stmts_mutate_self(&body.stmts)
201 }
202 // C9: also check init and update for `this.field++` / `this.field += val`
203 IrStmt::For {
204 init, update, body, ..
205 } => {
206 init.as_ref().is_some_and(|i| stmt_mutates_self(i))
207 || update.as_ref().is_some_and(|u| stmt_mutates_self(u))
208 || stmts_mutate_self(&body.stmts)
209 }
210 IrStmt::ForIn { body, .. } | IrStmt::ForOf { body, .. } => {
211 stmts_mutate_self(&body.stmts)
212 }
213 IrStmt::Switch { cases, .. } => cases.iter().any(|c| stmts_mutate_self(&c.body)),
214 IrStmt::Try {
215 try_block,
216 catch_block,
217 finally,
218 ..
219 } => {
220 stmts_mutate_self(&try_block.stmts)
221 || stmts_mutate_self(&catch_block.stmts)
222 || finally
223 .as_ref()
224 .is_some_and(|fb| stmts_mutate_self(&fb.stmts))
225 }
226 IrStmt::Block(b) => stmts_mutate_self(&b.stmts),
227 _ => false,
228 }
229 }
230
231 stmts_mutate_self(&body.stmts)
232}
233
234impl Emitter {
235 /// Resolve the return type string for a function/closure that may use `AnytypeReturn`.
236 ///
237 /// When the return type is `AnytypeReturn`, generates `@TypeOf(first_return_expr)`
238 /// (stripping `try` prefixes which are invalid in comptime type expressions).
239 /// For non-AnytypeReturn types, delegates to `format_return_type`.
240 pub(super) fn resolve_anytype_return(
241 &mut self,
242 return_type: &ZigType,
243 typeof_return_body: &Option<Box<crate::zigir::types::IrExpr>>,
244 is_async: bool,
245 can_throw: bool,
246 ) -> String {
247 // AnytypeReturn and Struct (anonymous object) both need @TypeOf
248 // because `.{ .field = T, ... }` is a struct literal, not a valid type.
249 if matches!(return_type, ZigType::AnytypeReturn | ZigType::Struct(_)) {
250 if let Some(body_expr) = typeof_return_body {
251 let captured = self.expr_to_string(body_expr);
252 let stripped = captured.replace("try ", "");
253 let base = format!("@TypeOf({})", stripped);
254 if is_async || can_throw {
255 format!("!{}", base)
256 } else {
257 base
258 }
259 } else {
260 // Fallback: no return expression found
261 if can_throw {
262 "!void".to_string()
263 } else {
264 "void".to_string()
265 }
266 }
267 } else {
268 format_return_type(return_type, is_async, can_throw)
269 }
270 }
271
272 pub(crate) fn emit_typedef(&mut self, typedef: &IrTypedef) {
273 self.writeln(&format!("const {} = struct {{", typedef.name));
274 self.indent_push();
275 for field in &typedef.fields {
276 // Note: zig_type already includes the '?' prefix for optional fields
277 // (set in lower/mod.rs), so we must NOT add another '?' here.
278 self.writeln(&format!("{}: {},", field.name, field.zig_type));
279 }
280 // Generate toJson() method for non-opaque typedefs
281 if typedef.has_to_json {
282 self.writeln("");
283 self.writeln("pub fn toJson(self: *const @This()) ![]u8 {");
284 self.indent_push();
285 self.writeln("var string = std.io.Writer.Allocating.init(js_allocator.allocator());");
286 self.writeln("errdefer string.deinit();");
287 self.writeln("try string.writer().print(\"{f}\", .{std.json.fmt(self.*, .{})});");
288 self.writeln("return string.toOwnedSlice();");
289 self.indent_pop();
290 self.writeln("}");
291 }
292 self.indent_pop();
293 self.writeln("};");
294 self.writeln("");
295 }
296
297 pub(crate) fn emit_closure_struct(&mut self, cs: &IrClosureStruct) {
298 self.writeln(&format!("const {} = struct {{", cs.name.zig_name));
299 self.indent_push();
300
301 // Captured variable fields
302 for cap in &cs.captured {
303 let ty_str = cap.zig_type.to_zig_type();
304 if cap.is_mut {
305 self.writeln(&format!("{}: *{},", cap.name.zig_name, ty_str));
306 } else {
307 self.writeln(&format!("{}: {},", cap.name.zig_name, ty_str));
308 }
309 }
310
311 // When the body is only @compileError, prefix params with `_` to suppress
312 // Zig's "unused function parameter" error — the function will never run.
313 let body_is_compile_error = cs
314 .body
315 .stmts
316 .iter()
317 .all(|s| matches!(s, IrStmt::CompileError { .. }));
318
319 // Call method signature
320 // Arrow fn (no captures): pub fn call(x: i64) i64 {
321 // Closure (has captures): pub fn call(self: *@This(), x: i64) i64 {
322 let mut sig = String::from("pub fn call(");
323 let has_self = !cs.captured.is_empty();
324 let mut need_comma = false;
325 if has_self {
326 if body_is_compile_error {
327 sig.push_str("_: *@This()");
328 } else {
329 sig.push_str("self: *@This()");
330 }
331 need_comma = true;
332 }
333 for param in &cs.fn_params {
334 if need_comma {
335 sig.push_str(", ");
336 }
337 if body_is_compile_error {
338 // Use bare `_` to suppress "unused parameter" error in Zig
339 let type_str = if param.is_rest {
340 "[]const JsAny".to_string()
341 } else {
342 param.zig_type.to_zig_type().into_owned()
343 };
344 sig.push_str(&format!("_: {}", type_str));
345 } else {
346 sig.push_str(&format_param_with_rest(
347 ¶m.name,
348 ¶m.zig_type,
349 param.is_rest,
350 ));
351 }
352 need_comma = true;
353 }
354 // Return type: use @TypeOf(expr) for AnytypeReturn, else normal type
355 let ret_type_str =
356 self.resolve_anytype_return(&cs.return_type, &cs.typeof_return_body, false, false);
357 sig.push_str(&format!(") {} {{", ret_type_str));
358 self.writeln(&sig);
359
360 self.indent_push();
361 self.emit_block_stmts_unlabeled(&cs.body);
362 self.indent_pop();
363
364 self.writeln("}");
365 self.indent_pop();
366 self.writeln("};");
367 }
368
369 pub(crate) fn emit_var_decl(&mut self, vd: &IrVarDecl) {
370 self.write_indent();
371
372 let kw = if vd.is_const { "const" } else { "var" };
373
374 if vd.is_json_parse {
375 // JSON.parse variable: `const name: Type = std.json.parse(Type, expr) catch @panic(...)`
376 let type_name = vd
377 .zig_type
378 .as_ref()
379 .map(|t| match t {
380 ZigType::NamedStruct(n) => n.clone(),
381 other => other.to_zig_type().into_owned(),
382 })
383 .unwrap_or_else(|| "i64".to_string());
384 self.write(&format!(
385 "{} {}: {} = std.json.parse({}, ",
386 kw, vd.name.zig_name, type_name, type_name
387 ));
388 if let Some(init) = &vd.init {
389 self.emit_expr(init);
390 }
391 if let Some(label) = &self.inside_try_block {
392 self.write(&format!(
393 ") catch |err| break :{} @as(anyerror!void, err)",
394 label
395 ));
396 } else if self.in_function {
397 // NOTE: `return error.JsThrow` requires the enclosing function
398 // to return an error union (`!T`). The lowerer only generates
399 // JSON.parse inside functions that return error unions, so this
400 // is safe in practice. If a future change allows JSON.parse in
401 // non-error-union functions, this path would produce a Zig
402 // compile error and would need revisiting.
403 self.write(") catch return error.JsThrow");
404 } else {
405 self.write(") catch @panic(\"JSON.parse failed\")");
406 }
407 } else if let Some(init) = &vd.init {
408 // Has initializer
409 // Special case: __arguments variable — emit as const slice with explicit type
410 // annotation so that even empty arrays (&.{} ) are typed as []const JsAny (slice,
411 // which supports indexing) rather than *const [0]JsAny (zero-length array, which
412 // does not support indexing).
413 if vd.name.zig_name == "__arguments" {
414 self.write(&format!("{} {}: []const JsAny = ", kw, vd.name.zig_name));
415 if let crate::zigir::types::IrExpr::ArrayLiteral(arr) = init {
416 self.write("&[_]JsAny{ ");
417 for (i, elem) in arr.elements.iter().enumerate() {
418 if i > 0 {
419 self.write(", ");
420 }
421 self.emit_expr(elem);
422 }
423 self.write(" }");
424 } else {
425 self.emit_expr(init);
426 }
427 } else {
428 let skip_type = vd
429 .zig_type
430 .as_ref()
431 .is_some_and(|t| matches!(t, ZigType::NamedStruct(_) | ZigType::ArrayList(_)));
432 if vd.is_const || skip_type {
433 self.write(&format!("{} {} = ", kw, vd.name.zig_name));
434 } else if let Some(ty) = &vd.zig_type {
435 self.write(&format!(
436 "{} {}: {} = ",
437 kw,
438 vd.name.zig_name,
439 ty.to_zig_type()
440 ));
441 } else {
442 self.write(&format!("{} {} = ", kw, vd.name.zig_name));
443 }
444 self.emit_expr(init);
445 }
446 } else {
447 // No initializer
448 self.write(&format!("{} {}", kw, vd.name.zig_name));
449 }
450
451 self.write(";\n");
452
453 // Var usage suppression for ArrayList/Map/Set variables
454 // whose value may not be read after compilation transforms.
455 if vd.needs_var_suppression {
456 self.write_indent();
457 self.write(&format!("_ = &{}; // var usage\n", vd.name.zig_name));
458 }
459
460 // Auto-cleanup: defer deinit for Map/Set/BigInt variables and class instances
461 // that contain Map/Set/ArrayList/BigInt fields, to prevent memory leaks.
462 if vd.needs_deinit
463 || matches!(&vd.zig_type, Some(ZigType::NamedStruct(name))
464 if name != "Map" && name != "Set" && name != "Date"
465 && name != "JsBigInt" && name != "JsRegExp" && name != "RegExp"
466 && name != "Error" && name != "JsError"
467 && self.class_needs_deinit.contains(name))
468 || matches!(&vd.zig_type, Some(ZigType::BigInt))
469 {
470 self.write_indent();
471 self.write(&format!(
472 "defer {}.deinit(js_allocator.allocator()); // auto-cleanup\n",
473 vd.name.zig_name
474 ));
475 }
476 }
477
478 pub(crate) fn emit_fn_decl(&mut self, fd: &IrFnDecl) {
479 let name = &fd.name.zig_name;
480
481 // Function signature — all top-level functions are `pub fn` in Zig.
482 // `is_export` only controls C ABI wrapper generation, not visibility.
483 self.write(&format!("pub fn {}(", name));
484
485 for (i, param) in fd.params.iter().enumerate() {
486 if i > 0 {
487 self.write(", ");
488 }
489 let type_str = if param.is_rest {
490 "[]const JsAny".to_string()
491 } else {
492 param.zig_type.to_zig_type().into_owned()
493 };
494 if param.is_unused {
495 // Output `_name: Type` for unused params to suppress Zig's unused-variable warning
496 self.write(&format!("_{}: {}", param.name.zig_name, type_str));
497 } else {
498 self.write(&format!("{}: {}", param.name.zig_name, type_str));
499 }
500 }
501
502 let ret_type = self.resolve_anytype_return(
503 &fd.return_type,
504 &fd.typeof_return_body,
505 fd.is_async,
506 fd.can_throw,
507 );
508 self.write(&format!(") {} {{\n", ret_type));
509
510 // Emit `_ = _param;` for unused params at the start of the body
511 self.indent_push();
512 self.in_function = true;
513 for param in &fd.params {
514 if param.is_unused {
515 self.writeln(&format!("_ = _{};", param.name.zig_name));
516 }
517 }
518
519 // Function body
520 self.emit_block_stmts_unlabeled(&fd.body);
521 self.in_function = false;
522 self.indent_pop();
523
524 self.writeln("}");
525 // NOTE: No trailing blank line.
526 // Inter-declaration spacing is handled at the module level if needed.
527 }
528
529 pub(crate) fn emit_class_decl(&mut self, class: &IrClassDecl) {
530 let class_name = &class.name.zig_name;
531
532 // Register class in needs_deinit set (redundant with pre-scan, but safe).
533 if class.needs_deinit {
534 self.class_needs_deinit.insert(class_name.clone());
535 }
536
537 self.writeln(&format!("const {} = struct {{", class_name));
538 self.indent_push();
539
540 // Struct fields
541 for field in &class.fields {
542 self.writeln(&format!(
543 "{}: {},",
544 field.name,
545 field.zig_type.to_zig_type()
546 ));
547 }
548 self.writeln("");
549
550 // Constructor → init()
551 if let Some(ctor) = &class.constructor {
552 self.emit_class_init(class_name, ctor, &class.fields);
553 } else {
554 // Default init()
555 self.emit_default_init(class_name, &class.fields);
556 }
557
558 // Methods
559 for method in &class.methods {
560 self.emit_class_method(class_name, method);
561 }
562
563 // deinit() method — generated when any field needs deinit (Map, Set,
564 // ArrayList, BigInt, or a NamedStruct class that itself needs deinit).
565 // Uses the propagated class_needs_deinit set from the pre-scan step.
566 if self.class_needs_deinit.contains(class_name.as_str()) {
567 self.writeln("");
568 self.writeln("pub fn deinit(self: *@This(), alloc: std.mem.Allocator) void {");
569 self.indent_push();
570 for field in &class.fields {
571 let needs_field_deinit = matches!(
572 &field.zig_type,
573 ZigType::NamedStruct(n)
574 if n == "Map" || n == "Set"
575 || self.class_needs_deinit.contains(n.as_str())
576 ) || matches!(&field.zig_type, ZigType::ArrayList(_))
577 || matches!(&field.zig_type, ZigType::BigInt);
578 if needs_field_deinit {
579 self.writeln(&format!("self.{}.deinit(alloc);", field.name));
580 }
581 }
582 self.indent_pop();
583 self.writeln("}");
584 }
585
586 self.indent_pop();
587 self.writeln("};");
588 self.writeln("");
589
590 // Static field initializers — emitted as module-scope `var` declarations.
591 // e.g. `static x = 1` → `var __ClassName_x: i64 = 1;`
592 for (field_name, init_expr, field_ty) in &class.static_inits {
593 let var_name = format!("__{}_{}", class_name, field_name);
594 self.write(&format!("var {}: ", var_name));
595 self.write(&format!("{} = ", field_ty.to_zig_type()));
596 self.emit_expr(init_expr);
597 self.writeln(";");
598
599 // Register static fields needing deinit in deinit_js2rust():
600 // Map, Set, ArrayList, BigInt, or NamedStruct class that needs deinit.
601 let needs_static_deinit = matches!(
602 field_ty,
603 ZigType::NamedStruct(n)
604 if n == "Map" || n == "Set"
605 || self.class_needs_deinit.contains(n.as_str())
606 ) || matches!(field_ty, ZigType::ArrayList(_))
607 || matches!(field_ty, ZigType::BigInt);
608 if needs_static_deinit {
609 self.static_deinit_buffer.push_str(&format!(
610 " {}.deinit(js_allocator.allocator());\n",
611 var_name
612 ));
613 }
614 }
615
616 // Static initialization blocks — collected into `static_init_buffer`.
617 // When any class has static blocks, the module-level `init_js2rust()`
618 // function is generated, which the orchestrator's root `init_js2rust()`
619 // auto-discovers and calls. This ensures static blocks execute at runtime
620 // (Zig's lazy analysis would otherwise skip unreferenced top-level `const`).
621 for block in &class.static_blocks {
622 if !block.stmts.is_empty() {
623 // Temporarily swap output to static_init_buffer so statements go there
624 let saved = std::mem::take(&mut self.output);
625 self.output = std::mem::take(&mut self.static_init_buffer);
626 for stmt in &block.stmts {
627 self.emit_stmt(stmt);
628 }
629 self.static_init_buffer = std::mem::take(&mut self.output);
630 self.output = saved;
631 }
632 }
633 }
634
635 /// Emit a struct literal return: `return .{ .field0 = val0, .field1 = val1, ... };`
636 /// Pairs are provided as `(field_name, value_string)` slices.
637 fn emit_struct_literal_return(&mut self, pairs: &[(&str, String)]) {
638 self.write_indent();
639 self.write("return .{ ");
640 for (i, (name, val)) in pairs.iter().enumerate() {
641 if i > 0 {
642 self.write(", ");
643 }
644 self.write(&format!(".{} = {}", name, val));
645 }
646 self.write(" };\n");
647 }
648
649 pub(super) fn emit_class_init(
650 &mut self,
651 class_name: &str,
652 ctor: &IrClassMethod,
653 fields: &[IrClassField],
654 ) {
655 let mut sig = "pub fn init(".to_string();
656 for (i, param) in ctor.params.iter().enumerate() {
657 if i > 0 {
658 sig.push_str(", ");
659 }
660 sig.push_str(&format_param_with_rest(
661 ¶m.name,
662 ¶m.zig_type,
663 param.is_rest,
664 ));
665 }
666 sig.push_str(&format!(") {} {{", class_name));
667 self.writeln(&sig);
668 self.indent_push();
669
670 // R8-C7 + R8-E4/C6: Pre-declare each class field at the top of the
671 // constructor body, so the Lowerer's rewritten `field = value` Assigns
672 // have a target to write to (no matter how deeply nested).
673 //
674 // The initialiser value comes from the field's `default` (its class
675 // body `x = ...`) when present, otherwise a type-appropriate zero.
676 // This means a constructor that *never* touches a field still yields
677 // the field's declared default instead of an undefined slot — which is
678 // the R8-E4/C6 fix.
679 //
680 // Whether each pre-declaration is `var` or `const` depends on whether
681 // the constructor body actually reassigns the field: Zig 0.16.0
682 // ast-check rejects a `var` that is never mutated, so a field that
683 // only carries its default through to the struct return must be
684 // declared `const`. We compute the set of assigned-identifier names
685 // up front (recursing into every nested container statement) and
686 // route each field accordingly.
687 let assigned = collect_assigned_idents_in_block(&ctor.body);
688 for f in fields {
689 let default_str = match &f.default {
690 Some(expr) => self.expr_to_string(expr),
691 None => field_zero_value(&f.zig_type).to_string(),
692 };
693 let kw = if assigned.contains(&f.name) {
694 "var"
695 } else {
696 "const"
697 };
698 self.writeln(&format!(
699 "{} {}: {} = {};",
700 kw,
701 f.name,
702 f.zig_type.to_zig_type(),
703 default_str
704 ));
705 }
706
707 // Constructor body — rewritten assignments target the vars above.
708 self.emit_block_stmts_unlabeled(&ctor.body);
709
710 // R8-C2: Skip the appended `return .{...}` if the body's last
711 // top-level statement is already a `Return`. Otherwise Zig would
712 // reject the appended return as unreachable code.
713 //
714 // Limitation: this only detects an explicit top-level trailing return.
715 // A return nested inside an if/switch branch still lets the appended
716 // return stand; that path will hit the appended struct return with
717 // whatever the branch left in the field vars, which matches JS
718 // "early return from ctor returns the partial instance".
719 let body_ends_in_return = ctor
720 .body
721 .stmts
722 .last()
723 .is_some_and(|last| matches!(last, IrStmt::Return { .. }));
724
725 if !body_ends_in_return {
726 // Return struct literal (from fields assigned in body — values are the local vars)
727 let pairs: Vec<(&str, String)> = fields
728 .iter()
729 .map(|f| (f.name.as_str(), f.name.clone()))
730 .collect();
731 self.emit_struct_literal_return(&pairs);
732 }
733
734 self.indent_pop();
735 self.writeln("}");
736 }
737
738 pub(super) fn emit_default_init(&mut self, class_name: &str, fields: &[IrClassField]) {
739 self.writeln(&format!("pub fn init() {} {{", class_name));
740 self.indent_push();
741 if fields.is_empty() {
742 self.writeln("return .{};");
743 } else {
744 let pairs: Vec<(&str, String)> = fields
745 .iter()
746 .map(|f| {
747 (
748 f.name.as_str(),
749 match &f.default {
750 Some(expr) => self.expr_to_string(expr),
751 None => field_zero_value(&f.zig_type).to_string(),
752 },
753 )
754 })
755 .collect();
756 self.emit_struct_literal_return(&pairs);
757 }
758 self.indent_pop();
759 self.writeln("}");
760 }
761
762 pub(super) fn emit_class_method(&mut self, _class_name: &str, method: &IrClassMethod) {
763 // R8-E5/C1: Methods that mutate `self` (assign to `self.field`) need
764 // `self: *@This()` so Zig allows the assignment. Non-mutating methods
765 // keep `self: @This()` (by-value) which is cheaper and works on both
766 // const and var instances.
767 let mut sig = if method.is_static {
768 format!("pub fn {}(", method.name)
769 } else if method_mutates_self(&method.body) {
770 format!("pub fn {}(self: *@This()", method.name)
771 } else {
772 format!("pub fn {}(self: @This()", method.name)
773 };
774
775 for param in &method.params {
776 sig.push_str(&format!(
777 ", {}",
778 format_param_with_rest(¶m.name, ¶m.zig_type, param.is_rest)
779 ));
780 }
781 sig.push_str(&format!(") {} {{", method.return_type.to_zig_type()));
782 self.writeln(&sig);
783
784 self.indent_push();
785 self.emit_block_stmts_unlabeled(&method.body);
786 self.indent_pop();
787
788 self.writeln("}");
789 }
790}