Commit 37e12dd3

37e12dd33c1fMerged

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

Description

Struct#dig with literal keys

dig(:member) / dig(index) resolves a member at compile time (exact type); dig(:member, key) indexes into a hash/array member. Adds struct_member_idx for symbol/integer literal key resolution.

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

Details

Commit
37e12dd33c1f
Parent
4046dec61061

src/analyze.cmodifiedView file

@@ -32,6 +32,27 @@
3232
3333 /* ---- call inference ---- */
3434
35+/* Resolve a struct member from a literal key node: a SymbolNode names a
36+ member; an IntegerNode is a positional index. Returns the member index
37+ (0-based, matching ivar order) or -1. */
38+static int struct_member_idx(Compiler *c, ClassInfo *sc, int keynode) {
39+ const NodeTable *nt = c->nt;
40+ const char *kty = nt_type(nt, keynode);
41+ if (!kty) return -1;
42+ if (!strcmp(kty, "SymbolNode")) {
43+ const char *kn = nt_str(nt, keynode, "value");
44+ if (!kn) return -1;
45+ char ivn[256]; snprintf(ivn, sizeof ivn, "@%s", kn);
46+ int iv = comp_ivar_index(sc, ivn);
47+ return iv; /* ivar order == member order */
48+ }
49+ if (!strcmp(kty, "IntegerNode")) {
50+ int idx = (int)nt_int(nt, keynode, "value", -1);
51+ if (idx >= 0 && idx < sc->nivars) return idx;
52+ }
53+ return -1;
54+}
55+
3556 static TyKind infer_call(Compiler *c, int id) {
3657 const NodeTable *nt = c->nt;
3758 const char *name = nt_str(nt, id, "name");
@@ -110,9 +131,21 @@
110131
111132 /* Struct instance methods */
112133 if (recv >= 0 && ty_is_object(rt) && c->classes[ty_object_class(rt)].is_struct) {
134+ ClassInfo *sc = &c->classes[ty_object_class(rt)];
113135 if (!strcmp(name, "to_a") || !strcmp(name, "values") ||
114136 !strcmp(name, "deconstruct") || !strcmp(name, "members")) return TY_POLY_ARRAY;
115137 if (!strcmp(name, "to_h")) return TY_SYM_POLY_HASH;
138+ if (!strcmp(name, "dig") && argc >= 1) {
139+ int mi = struct_member_idx(c, sc, argv[0]);
140+ if (mi >= 0) {
141+ TyKind mt = sc->ivar_types[mi];
142+ if (argc == 1) return mt;
143+ /* dig(member, key, ...): index into the member's container */
144+ if (ty_is_hash(mt) && argc == 2) return ty_hash_val(mt);
145+ if (ty_is_array(mt) && argc == 2) return ty_array_elem(mt);
146+ return TY_POLY;
147+ }
148+ }
116149 }
117150
118151 /* obj.method(...) -> the method's return type (walks the superclass chain) */