Commit d7f36aa3

d7f36aa3bd06Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): #303 module ivar @h = {} infers hash type from writes

A module ivar initialized to an empty hash literal (@slots = {}) froze its type at the empty-hash default str_int_hash even when the module's class methods only ever wrote a sym → string mapping into it. The storage decl said sp_StrIntHash * but the write site emitted sp_StrIntHash_set(h, sp_sym_to_s(k), v) — a const char * value into the hash's mrb_int v parameter — and the read site emitted (cst_M_slots >> k) & 1 because infer_type on @slots inside def self.get fell through to the int-bit- extract default for [].

Three fixes:

  1. infer_type's InstanceVariableReadNode arm: when inside a module class method (compile_expr already routes @iname here to cst_<mod>_<iname>), look the slot up in the const table so the inferred type is the hash class instead of the catch-all "int". Without this, @slots[k] lowered through the int-bit extract path even after the storage type was correct.

  2. New refine_module_ivar_types pass: walks each module's class- method bodies for @<iname>[k] = v and @<iname> << v style writes, picks the most specific hash / array shape from the observed key + value types, and updates @const_types. Runs in generate_code after the param-type inference loop has stabilized so infer_type(args[i]) resolves to the call-site- widened type instead of the placeholder "int" the params would carry at module-collect time.

  3. Const-init emit (cst_<name> = <init>) and main()-block emit: when the refined type disagrees with what compile_expr's default emit picks (sp_StrIntHash_new() for {}), emit the matching sp_<HashClass>_new() directly. Same for empty array refinement. The runtime @needs_* flags get set during the refine pass so emit_sym_runtime can declare the matching struct + helpers in time.

After refining, re-run return / call-type inference so methods that return the refined const (e.g. def self.add(s); @items << s; end) see the new shape instead of the stale sp_IntArray * return type the iteration-loop computed.

Fixes #303

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

Details

Commit
d7f36aa3bd06
Parent
d054d4cc3e7e

spinel_codegen.rbmodifiedView file

@@ -1961,6 +1961,26 @@
19611961 if @current_class_idx >= 0
19621962 return cls_ivar_type(@current_class_idx, @nd_name[nid])
19631963 end
1964+ # Issue #303: inside a module class method (`def self.foo` in
1965+ # `module M`, compiled as the top-level `M_cls_foo`), an ivar
1966+ # read like `@slots` resolves to `cst_M_slots` — already handled
1967+ # by compile_expr's matching arm. Mirror that resolution here so
1968+ # infer_type returns the slot's recorded type instead of falling
1969+ # through to "int", which would route `@slots[k]` through the
1970+ # int-bit-extract codegen even though the storage is a hash.
1971+ mi3 = 0
1972+ while mi3 < @module_names.length
1973+ mmod = @module_names[mi3]
1974+ if mmod != "" && @current_method_name.start_with?(mmod + "_cls_")
1975+ iname = @nd_name[nid]
1976+ cname3 = mmod + "_" + iname[1, iname.length - 1]
1977+ ci3 = find_const_idx(cname3)
1978+ if ci3 >= 0
1979+ return @const_types[ci3]
1980+ end
1981+ end
1982+ mi3 = mi3 + 1
1983+ end
19641984 tit = toplevel_ivar_type(@nd_name[nid])
19651985 if tit != ""
19661986 return tit
@@ -7729,6 +7749,223 @@
77297749 }
77307750 end
77317751
7752+ # Issue #303: refine module-ivar types for empty-container literals
7753+ # (`@h = {}` / `@arr = []`) by walking the module's class-method
7754+ # bodies for `@h[k] = v` / `@h << v` style writes and picking the
7755+ # most specific hash / array shape from the observed key + value
7756+ # types. Without this the empty-hash default `str_int_hash` stays
7757+ # frozen and a sym-key / string-value write site emits a typed-
7758+ # mismatch sp_StrIntHash_set call.
7759+ #
7760+ # Called from generate_code after the param-type inference loop so
7761+ # `infer_type(args[i])` resolves params to their call-site-widened
7762+ # types — refining at module-collect time would see every param as
7763+ # the placeholder "int".
7764+ def refine_all_module_ivar_types
7765+ mi = 0
7766+ while mi < @module_names.length
7767+ mname_m = @module_names[mi]
7768+ body_m = @module_body_ids[mi]
7769+ if mname_m != "" && body_m >= 0
7770+ refine_module_ivar_types(mname_m, get_stmts(body_m))
7771+ end
7772+ mi = mi + 1
7773+ end
7774+ end
7775+
7776+ def refine_module_ivar_types(mname, body_stmts)
7777+ body_stmts.each { |sid|
7778+ next unless @nd_type[sid] == "InstanceVariableWriteNode"
7779+ iname = @nd_name[sid]
7780+ cname2 = mname + "_" + iname[1, iname.length - 1]
7781+ ci = find_const_idx(cname2)
7782+ next if ci < 0
7783+ cur = @const_types[ci]
7784+ # Only refine when the recorded type is the empty-hash default
7785+ # (str_int_hash) or empty-array default (int_array).
7786+ next unless cur == "str_int_hash" || cur == "int_array"
7787+ expr_id = @nd_expression[sid]
7788+ next unless expr_id >= 0
7789+ next unless (cur == "str_int_hash" && is_empty_hash_literal(expr_id) == 1) ||
7790+ (cur == "int_array" && is_empty_array_literal(expr_id) == 1)
7791+ # Walk all class methods in the module looking for writes to
7792+ # this ivar.
7793+ key_t_set = "".split(",")
7794+ val_t_set = "".split(",")
7795+ body_stmts.each { |sid2|
7796+ next unless @nd_type[sid2] == "DefNode"
7797+ bid = @nd_body[sid2]
7798+ next unless bid >= 0
7799+ # The def's params live in the top-level method table under the
7800+ # synthetic `<mname>_cls_<dmname>` name. Pull the
7801+ # call-site-widened types from there and declare them in a
7802+ # temporary scope so `infer_type(LocalVariableReadNode)` for
7803+ # those params resolves correctly during the walk.
7804+ synth_name = mname + "_cls_" + @nd_name[sid2]
7805+ mi3 = find_method_idx(synth_name)
7806+ push_scope
7807+ if mi3 >= 0
7808+ pnames3 = @meth_param_names[mi3].split(",")
7809+ ptypes3 = @meth_param_types[mi3].split(",")
7810+ k3 = 0
7811+ while k3 < pnames3.length
7812+ pt3 = "int"
7813+ if k3 < ptypes3.length
7814+ pt3 = ptypes3[k3]
7815+ end
7816+ declare_var(pnames3[k3], pt3)
7817+ k3 = k3 + 1
7818+ end
7819+ end
7820+ saved_meth = @current_method_name
7821+ @current_method_name = synth_name
7822+ scan_module_ivar_writes(bid, iname, key_t_set, val_t_set)
7823+ @current_method_name = saved_meth
7824+ pop_scope
7825+ }
7826+ if cur == "str_int_hash"
7827+ # Pick the hash class that fits the observed (key, value) types.
7828+ new_t = pick_hash_class(key_t_set, val_t_set)
7829+ if new_t != "" && new_t != cur
7830+ @const_types[ci] = new_t
7831+ # Set the @needs_* flag so emit_sym_runtime / future hash
7832+ # runtime emitters declare the matching struct + helpers
7833+ # before this const's `cst_<name>` declaration is rendered.
7834+ mark_hash_needs(new_t)
7835+ end
7836+ elsif cur == "int_array"
7837+ new_t = pick_array_class(val_t_set)
7838+ if new_t != "" && new_t != cur
7839+ @const_types[ci] = new_t
7840+ mark_array_needs(new_t)
7841+ end
7842+ end
7843+ }
7844+ end
7845+
7846+ def mark_hash_needs(t)
7847+ if t == "sym_int_hash"
7848+ @needs_sym_int_hash = 1
7849+ elsif t == "sym_str_hash"
7850+ @needs_sym_str_hash = 1
7851+ elsif t == "str_str_hash"
7852+ @needs_str_str_hash = 1
7853+ elsif t == "int_str_hash"
7854+ @needs_int_str_hash = 1
7855+ elsif t == "sym_poly_hash"
7856+ @needs_sym_poly_hash = 1
7857+ @needs_rb_value = 1
7858+ elsif t == "str_poly_hash"
7859+ @needs_str_poly_hash = 1
7860+ @needs_rb_value = 1
7861+ end
7862+ end
7863+
7864+ def mark_array_needs(t)
7865+ if t == "float_array"
7866+ @needs_float_array = 1
7867+ elsif t == "str_array"
7868+ @needs_str_array = 1
7869+ elsif t == "poly_array"
7870+ @needs_rb_value = 1
7871+ end
7872+ end
7873+
7874+ # Walk `nid` accumulating distinct key + value types observed at
7875+ # `@<iname>[k] = v` / `@<iname> << v` style writes.
7876+ def scan_module_ivar_writes(nid, iname, key_t_set, val_t_set)
7877+ if nid < 0
7878+ return
7879+ end
7880+ t = @nd_type[nid]
7881+ if t == "CallNode"
7882+ mname_call = @nd_name[nid]
7883+ recv = @nd_receiver[nid]
7884+ if recv >= 0 && @nd_type[recv] == "InstanceVariableReadNode" && @nd_name[recv] == iname
7885+ args_id = @nd_arguments[nid]
7886+ if args_id >= 0
7887+ arg_ids = get_args(args_id)
7888+ if mname_call == "[]=" && arg_ids.length >= 2
7889+ kt = infer_type(arg_ids[0])
7890+ vt = infer_type(arg_ids[1])
7891+ uniq_push(key_t_set, kt)
7892+ uniq_push(val_t_set, vt)
7893+ elsif (mname_call == "<<" || mname_call == "push") && arg_ids.length >= 1
7894+ vt = infer_type(arg_ids[0])
7895+ uniq_push(val_t_set, vt)
7896+ end
7897+ end
7898+ end
7899+ end
7900+ cs = []
7901+ push_child_ids(nid, cs)
7902+ k = 0
7903+ while k < cs.length
7904+ scan_module_ivar_writes(cs[k], iname, key_t_set, val_t_set)
7905+ k = k + 1
7906+ end
7907+ end
7908+
7909+ def uniq_push(set, val)
7910+ found = 0
7911+ k = 0
7912+ while k < set.length
7913+ if set[k] == val
7914+ found = 1
7915+ break
7916+ end
7917+ k = k + 1
7918+ end
7919+ if found == 0
7920+ set.push(val)
7921+ end
7922+ end
7923+
7924+ def pick_hash_class(key_t_set, val_t_set)
7925+ return "" if key_t_set.length == 0 || val_t_set.length == 0
7926+ # Heterogeneous keys → poly hash; mixed values → poly hash too.
7927+ sym_keys = key_t_set.length == 1 && key_t_set[0] == "symbol"
7928+ str_keys = key_t_set.length == 1 && key_t_set[0] == "string"
7929+ int_keys = key_t_set.length == 1 && key_t_set[0] == "int"
7930+ int_vals = val_t_set.length == 1 && val_t_set[0] == "int"
7931+ str_vals = val_t_set.length == 1 && val_t_set[0] == "string"
7932+ if sym_keys && int_vals
7933+ return "sym_int_hash"
7934+ end
7935+ if sym_keys && str_vals
7936+ return "sym_str_hash"
7937+ end
7938+ if str_keys && int_vals
7939+ return "str_int_hash"
7940+ end
7941+ if str_keys && str_vals
7942+ return "str_str_hash"
7943+ end
7944+ if int_keys && str_vals
7945+ return "int_str_hash"
7946+ end
7947+ # Fall back to poly when the observed pair doesn't fit a typed hash.
7948+ if sym_keys
7949+ return "sym_poly_hash"
7950+ end
7951+ if str_keys
7952+ return "str_poly_hash"
7953+ end
7954+ ""
7955+ end
7956+
7957+ def pick_array_class(val_t_set)
7958+ return "" if val_t_set.length == 0
7959+ if val_t_set.length == 1
7960+ vt = val_t_set[0]
7961+ return "int_array" if vt == "int"
7962+ return "float_array" if vt == "float"
7963+ return "str_array" if vt == "string"
7964+ return "sym_array" if vt == "symbol"
7965+ end
7966+ "poly_array"
7967+ end
7968+
77327969 # ---------- FFI declaration scanning ----------
77337970 #
77347971 # Each ffi_* DSL form inside a `module M ... end` body is recognized by
@@ -13049,6 +13286,19 @@
1304913286 infer_class_body_call_types
1305013287 infer_ivar_types_from_writers
1305113288 infer_all_returns
13289+ # Issue #303: param types are now stable, so module ivar refinement
13290+ # (which infers hash / array specialization from `@h[k] = v` writes
13291+ # in class-method bodies) sees the right key / value types instead
13292+ # of the placeholder "int" they'd carry at module-collect time.
13293+ # After refining, re-run return / call-type inference so methods
13294+ # that read or push the refined const see the new shape (e.g. a
13295+ # `def self.add(s); @items << s; end` whose return is now
13296+ # `sp_StrArray *` rather than the placeholder `sp_IntArray *`).
13297+ refine_all_module_ivar_types
13298+ infer_all_returns
13299+ infer_function_body_call_types
13300+ infer_class_body_call_types
13301+ infer_all_returns
1305213302 # Fix lambda return types based on call-site usage
1305313303 fix_lambda_return_types
1305413304 # Pre-detect bigint variables before feature detection
@@ -17660,7 +17910,52 @@
1766017910 else
1766117911 @current_lexical_scope = ""
1766217912 end
17663- val = compile_expr(@const_expr_ids[i])
17913+ # Issue #303: when refine_module_ivar_types widened the const
17914+ # type from the empty-hash default `str_int_hash` to a more
17915+ # specific shape (sym_str_hash etc.), emit the matching
17916+ # `sp_<Hash>_new()` directly instead of falling through to
17917+ # compile_expr's default `sp_StrIntHash_new()`. Same for
17918+ # empty-array refinement.
17919+ val = ""
17920+ ct_init = @const_types[i]
17921+ eid_init = @const_expr_ids[i]
17922+ if is_empty_hash_literal(eid_init) == 1
17923+ if ct_init == "sym_int_hash"
17924+ val = "sp_SymIntHash_new()"
17925+ @needs_sym_int_hash = 1
17926+ elsif ct_init == "sym_str_hash"
17927+ val = "sp_SymStrHash_new()"
17928+ @needs_sym_str_hash = 1
17929+ elsif ct_init == "str_str_hash"
17930+ val = "sp_StrStrHash_new()"
17931+ @needs_str_str_hash = 1
17932+ elsif ct_init == "int_str_hash"
17933+ val = "sp_IntStrHash_new()"
17934+ @needs_int_str_hash = 1
17935+ elsif ct_init == "sym_poly_hash"
17936+ val = "sp_SymPolyHash_new()"
17937+ @needs_sym_poly_hash = 1
17938+ elsif ct_init == "str_poly_hash"
17939+ val = "sp_StrPolyHash_new()"
17940+ @needs_str_poly_hash = 1
17941+ end
17942+ elsif is_empty_array_literal(eid_init) == 1
17943+ if ct_init == "float_array"
17944+ val = "sp_FloatArray_new()"
17945+ @needs_float_array = 1
17946+ elsif ct_init == "str_array"
17947+ val = "sp_StrArray_new()"
17948+ @needs_str_array = 1
17949+ elsif ct_init == "sym_array"
17950+ val = "sp_IntArray_new()"
17951+ elsif ct_init == "poly_array"
17952+ val = "sp_PolyArray_new()"
17953+ @needs_rb_value = 1
17954+ end
17955+ end
17956+ if val == ""
17957+ val = compile_expr(eid_init)
17958+ end
1766417959 @current_lexical_scope = old_scope
1766517960 emit(" cst_" + @const_names[i] + " = " + val + ";")
1766617961 if type_is_pointer(@const_types[i]) == 1