Commit d88cd194

d88cd194215bMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified

Description

Run class/module body side effects at the definition site

Statements in a class/module body (puts, constant writes, nested class/module bodies, user-method calls) now execute inline at the definition point, top-to-bottom like CRuby, instead of being dropped. Receiver-less calls default to declaration macros (attr_*, include, private, FFI/DSL directives) and are skipped; only output calls and resolved user-method calls run.

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
d88cd194215b
Parent
2863364f391a

src/codegen.cmodifiedView file

@@ -2508,7 +2508,32 @@
25082508 }
25092509 return;
25102510 }
2511- if (!strcmp(ty, "ClassNode") || !strcmp(ty, "ModuleNode")) { return; } /* methods emitted separately */
2511+ if (!strcmp(ty, "ClassNode") || !strcmp(ty, "ModuleNode")) {
2512+ /* Run the body's side-effecting statements at the definition site
2513+ (top-to-bottom, like CRuby). Method/attr/alias declarations are
2514+ handled elsewhere; everything else (puts, constant writes, nested
2515+ class/module bodies) executes inline here. */
2516+ int body = nt_ref(nt, id, "body");
2517+ int n = 0;
2518+ const int *stmts = body >= 0 ? nt_arr(nt, body, "body", &n) : NULL;
2519+ for (int k = 0; k < n; k++) {
2520+ const char *sty = nt_type(nt, stmts[k]);
2521+ if (!sty) continue;
2522+ if (!strcmp(sty, "DefNode") || !strcmp(sty, "AliasMethodNode")) continue;
2523+ /* A receiver-less call in a class body is, by default, a declaration
2524+ macro (attr_*, include, private, an FFI/DSL directive) -- skip it.
2525+ Only run the genuine side-effecting ones: output calls and calls
2526+ that resolve to a user-defined method. */
2527+ if (!strcmp(sty, "CallNode") && nt_ref(nt, stmts[k], "receiver") < 0) {
2528+ const char *cn = nt_str(nt, stmts[k], "name");
2529+ int is_output = cn && (!strcmp(cn, "puts") || !strcmp(cn, "print") || !strcmp(cn, "p"));
2530+ int is_user = cn && comp_method_index(c, cn) >= 0;
2531+ if (!is_output && !is_user) continue;
2532+ }
2533+ emit_stmt(c, stmts[k], b, indent);
2534+ }
2535+ return;
2536+ }
25122537 if (!strcmp(ty, "SuperNode") || !strcmp(ty, "ForwardingSuperNode")) {
25132538 emit_indent(b, indent); emit_super(c, id, b); buf_puts(b, ";\n"); return;
25142539 }