Commit be5a4bf6
be5a4bf62966Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
Type a bare-yield method's call by the call-site block value
A method whose body is just yield returns the block's value; since it
inlines per call site, infer the return type from THIS site's block
(string for { "str" }, int for { 7 }) instead of the unified poly. Fixes
the block value being printed as a garbage int.
Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]
Details
- Commit
- be5a4bf62966
- Parent
- ff4346fcad7c
src/analyze.cmodifiedView file
@@ -53,6 +53,30 @@
5353
return -1;5454
}5555
56+
/* Last statement of a scope's body, or -1. */57+
static int scope_body_last(Compiler *c, int mi) {58+
int body = c->scopes[mi].body;59+
if (body < 0 || !nt_type(c->nt, body) || strcmp(nt_type(c->nt, body), "StatementsNode")) return -1;60+
int n = 0; const int *bb = nt_arr(c->nt, body, "body", &n);61+
return n > 0 ? bb[n - 1] : -1;62+
}63+
64+
/* The return type of a call to method `mi`. A method whose body is just a65+
bare `yield` returns the block's value -- and since it inlines per call66+
site, use THIS site's block value type rather than the unified return. */67+
static TyKind method_call_ret(Compiler *c, int mi, int call_id) {68+
int last = scope_body_last(c, mi);69+
if (last >= 0 && nt_type(c->nt, last) && !strcmp(nt_type(c->nt, last), "YieldNode")) {70+
int blk = nt_ref(c->nt, call_id, "block");71+
if (blk >= 0) {72+
int bbody = nt_ref(c->nt, blk, "body");73+
int bn = 0; const int *bb = bbody >= 0 ? nt_arr(c->nt, bbody, "body", &bn) : NULL;74+
if (bn > 0) return infer_type(c, bb[bn - 1]);75+
}76+
}77+
return c->scopes[mi].ret;78+
}79+
5680
static TyKind infer_call(Compiler *c, int id) {5781
const NodeTable *nt = c->nt;5882
const char *name = nt_str(nt, id, "name");@@ -214,7 +238,7 @@
214238
}215239
}216240
int mi = comp_method_in_chain(c, cid, name, NULL);217-
if (mi >= 0) return c->scopes[mi].ret;241+
if (mi >= 0) return method_call_ret(c, mi, id);218242
if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) return TY_STRING;219243
}220244
@@ -229,14 +253,14 @@
229253
if (iv >= 0) return c->classes[self->class_id].ivar_types[iv];230254
}231255
int mi = comp_method_in_chain(c, self->class_id, name, NULL);232-
if (mi >= 0) return c->scopes[mi].ret;256+
if (mi >= 0) return method_call_ret(c, mi, id);233257
}234258
}235259
236260
/* user-defined free-function call (no receiver) */237261
if (recv < 0) {238262
int mi = comp_method_index(c, name);239-
if (mi >= 0) return c->scopes[mi].ret;263+
if (mi >= 0) return method_call_ret(c, mi, id);240264
/* Kernel conversions */241265
if (!strcmp(name, "Integer") && argc == 1) return TY_INT;242266
if (!strcmp(name, "Float") && argc == 1) return TY_FLOAT;