Commit 053918ba
053918baaa56Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified
Description
Array#each_with_object: return type inference and codegen
Implements array.each_with_object(init) { |x, acc| ... } for typed array receivers. Uses g_pre-based prelude pattern like emit_minmax_by_expr.
- analyze.c: infer return type as accumulator init type in infer_type; bind element to p0 and accumulator to p1 in infer_block_params
- codegen.c: emit_each_with_object_expr writes loop to g_pre, returns accumulator temp; poly-type mismatch handled via emit_boxed_text
Co-Authored-By: Claude Sonnet 4.6 [email protected]
Details
- Commit
- 053918baaa56
- Parent
- fc67cce30cd0
src/analyze.cmodifiedView file
@@ -613,6 +613,16 @@
613613
}614614
return ty_array_elem(rt);615615
}616+
if (!strcmp(name, "each_with_object") && argc > 0 && argv) {617+
TyKind at = infer_type(c, argv[0]);618+
if (at == TY_UNKNOWN) {619+
const char *a0ty = nt_type(nt, argv[0]);620+
int an0 = 0;621+
if (a0ty && !strcmp(a0ty, "ArrayNode")) nt_arr(nt, argv[0], "elements", &an0);622+
if (a0ty && !strcmp(a0ty, "ArrayNode") && an0 == 0) return TY_INT_ARRAY;623+
}624+
return at;625+
}616626
if (!strcmp(name, "tally") && argc == 0) {617627
if (rt == TY_INT_ARRAY) return TY_INT_INT_HASH;618628
if (rt == TY_STR_ARRAY) return TY_STR_INT_HASH;@@ -2547,6 +2557,40 @@
25472557
continue;25482558
}25492559
2560+
/* array.each_with_object(init) { |x, acc| } binds element + accumulator */2561+
if (!strcmp(name, "each_with_object") && ty_is_array(rt)) {2562+
Scope *es = comp_scope_of(c, block);2563+
if (p0) {2564+
TyKind et = ty_array_elem(rt);2565+
LocalVar *ep = scope_local_intern(es, p0); ep->is_block_param = 1;2566+
if (!(ty_is_array(ep->type) && !ty_is_array(et))) {2567+
TyKind em = ty_unify(ep->type, et);2568+
if (em != ep->type) { ep->type = em; changed = 1; }2569+
}2570+
}2571+
const char *p1_name = block_param_name(c, block, 1);2572+
if (p1_name) {2573+
int ewobj_args = nt_ref(nt, id, "arguments");2574+
int ewobj_argc = 0;2575+
const int *ewobj_argv = ewobj_args >= 0 ? nt_arr(nt, ewobj_args, "arguments", &ewobj_argc) : NULL;2576+
if (ewobj_argc > 0 && ewobj_argv) {2577+
TyKind at = infer_type(c, ewobj_argv[0]);2578+
if (at == TY_UNKNOWN) {2579+
const char *a0ty = nt_type(nt, ewobj_argv[0]);2580+
int an0 = 0;2581+
if (a0ty && !strcmp(a0ty, "ArrayNode")) nt_arr(nt, ewobj_argv[0], "elements", &an0);2582+
if (a0ty && !strcmp(a0ty, "ArrayNode") && an0 == 0) at = TY_INT_ARRAY;2583+
}2584+
if (at != TY_UNKNOWN) {2585+
LocalVar *ap = scope_local_intern(es, p1_name); ap->is_block_param = 1;2586+
TyKind am = ty_unify(ap->type, at);2587+
if (am != ap->type) { ap->type = am; changed = 1; }2588+
}2589+
}2590+
}2591+
continue;2592+
}2593+
25502594
/* hash.merge(other) { |k, v1, v2| } binds key + both conflicting values */25512595
if (!strcmp(name, "merge") && ty_is_hash(rt)) {25522596
Scope *ms = comp_scope_of(c, block);src/codegen.cmodifiedView file
Loading diff…