Commit 68efb64e

68efb64e4f89Merged

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

Description

Add yield-as-expression + bare value-expression statements

  • YieldNode in expression position (e.g. r << yield(x), yield(x) + 1) lowers to ({ bind block params; block body; }) whose value is the block body's last expression; analyze infers the yield value type from the method's call-site block bodies.
  • emit_stmt_inner: any remaining value-expression node is emitted as a bare <expr>; statement (e.g. a method body ending in result), which is the value when it's the last statement of an inlined expr method.
  • Iteration block params (each/times/range/hash/each_with_index/collect) now go through rename_local, so they're renamed correctly when their method is inlined.

make test: 37 (up from 34; the bare-statement fallback alone fixed several methods that end in a value expression).

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

Details

Commit
68efb64e4f89
Parent
dd1b4bb30e27

src/analyze.cmodifiedView file

@@ -347,6 +347,35 @@
347347 }
348348 return ty_hash_of(kt, vt);
349349 }
350+ if (!strcmp(ty, "YieldNode")) {
351+ /* value of yield = the block body's value at a call site of this method */
352+ int mi = (int)(comp_scope_of(c, id) - c->scopes);
353+ for (int cid = 0; cid < nt->count; cid++) {
354+ const char *cty = nt_type(nt, cid);
355+ if (!cty || strcmp(cty, "CallNode")) continue;
356+ int blk = nt_ref(nt, cid, "block");
357+ if (blk < 0) continue;
358+ const char *cn = nt_str(nt, cid, "name");
359+ int crecv = nt_ref(nt, cid, "receiver");
360+ int rmi = -1;
361+ if (crecv < 0) {
362+ rmi = comp_method_index(c, cn);
363+ if (rmi < 0) {
364+ Scope *cs = comp_scope_of(c, cid);
365+ if (cs->class_id >= 0) rmi = comp_method_in_chain(c, cs->class_id, cn, NULL);
366+ }
367+ } else {
368+ TyKind crt = infer_type(c, crecv);
369+ if (ty_is_object(crt)) rmi = comp_method_in_chain(c, ty_object_class(crt), cn, NULL);
370+ }
371+ if (rmi != mi) continue;
372+ int bb = nt_ref(nt, blk, "body");
373+ int bn = 0;
374+ const int *bd = bb >= 0 ? nt_arr(nt, bb, "body", &bn) : NULL;
375+ return bn > 0 ? infer_type(c, bd[bn - 1]) : TY_NIL;
376+ }
377+ return TY_UNKNOWN;
378+ }
350379 if (!strcmp(ty, "SuperNode") || !strcmp(ty, "ForwardingSuperNode")) {
351380 Scope *s = comp_scope_of(c, id);
352381 if (s->class_id < 0 || !s->name) return TY_UNKNOWN;