Commit 51767287

517672877dfaMerged

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

Description

Struct#to_h with a transform block + typed constructor prototype

to_h { |k, v| [nk, nv] } maps each member pair through the block, building a hash whose key/value types come from the block's returned pair (block params: k=symbol, v=poly). Also emit the struct constructor prototype with its real member param types so it matches the definition (an empty () prototype clashed with a _Bool member param).

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

Details

Commit
517672877dfa
Parent
37e12dd33c1f

src/analyze.cmodifiedView file

@@ -134,7 +134,27 @@
134134 ClassInfo *sc = &c->classes[ty_object_class(rt)];
135135 if (!strcmp(name, "to_a") || !strcmp(name, "values") ||
136136 !strcmp(name, "deconstruct") || !strcmp(name, "members")) return TY_POLY_ARRAY;
137- if (!strcmp(name, "to_h")) return TY_SYM_POLY_HASH;
137+ if (!strcmp(name, "to_h")) {
138+ int block = nt_ref(nt, id, "block");
139+ if (block >= 0) {
140+ /* to_h { |k,v| [nk, nv] }: hash type from the block's pair */
141+ int bbody = nt_ref(nt, block, "body");
142+ int bn = 0; const int *bb = bbody >= 0 ? nt_arr(nt, bbody, "body", &bn) : NULL;
143+ int last = bn > 0 ? bb[bn - 1] : -1;
144+ if (last >= 0 && nt_type(nt, last) && !strcmp(nt_type(nt, last), "ArrayNode")) {
145+ int en = 0; const int *els = nt_arr(nt, last, "elements", &en);
146+ if (en == 2) {
147+ TyKind kt = infer_type(c, els[0]), vt = infer_type(c, els[1]);
148+ if (kt == TY_SYMBOL) return TY_SYM_POLY_HASH;
149+ if (kt == TY_STRING && vt == TY_STRING) return TY_STR_STR_HASH;
150+ if (kt == TY_STRING) return TY_STR_POLY_HASH;
151+ TyKind h = ty_hash_of(kt, vt);
152+ return h != TY_UNKNOWN ? h : TY_STR_POLY_HASH;
153+ }
154+ }
155+ }
156+ return TY_SYM_POLY_HASH;
157+ }
138158 if (!strcmp(name, "dig") && argc >= 1) {
139159 int mi = struct_member_idx(c, sc, argv[0]);
140160 if (mi >= 0) {
@@ -1306,6 +1326,19 @@
13061326 int recv = nt_ref(nt, id, "receiver");
13071327 if (!name) continue;
13081328
1329+ /* struct.to_h { |k, v| ... }: k is a member symbol, v its (poly) value */
1330+ if (recv >= 0 && !strcmp(name, "to_h")) {
1331+ TyKind rt0 = infer_type(c, recv);
1332+ if (ty_is_object(rt0) && c->classes[ty_object_class(rt0)].is_struct) {
1333+ const char *kp = block_param_name(c, block, 0);
1334+ const char *vp = block_param_name(c, block, 1);
1335+ Scope *bs = comp_scope_of(c, block);
1336+ if (kp) { LocalVar *l = scope_local_intern(bs, kp); l->is_block_param = 1; if (l->type != TY_SYMBOL) { l->type = TY_SYMBOL; changed = 1; } }
1337+ if (vp) { LocalVar *l = scope_local_intern(bs, vp); l->is_block_param = 1; if (l->type != TY_POLY) { l->type = TY_POLY; changed = 1; } }
1338+ continue;
1339+ }
1340+ }
1341+
13091342 /* call to a user yielding method: block params take the yield arg types */
13101343 {
13111344 int mi = -1;