Commit 696097b7
696097b787fdMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 1 file · ~1 modified
Description
feat: Phase 8 - polymorphism with sp_RbVal tagged union
Add poly detection for function params called with different types. Add sp_RbVal tagged union (int/str/float/bool/nil/obj) with boxing. Add poly dispatch for object method calls based on cls_id. Add sp_poly_puts, sp_poly_to_s, sp_poly_nil_p helpers. Handle poly in case/in pattern matching and string interpolation.
Tests passing: bm_poly, bm_mega, bm_pattern
Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]
Details
- Commit
- 696097b787fd
- Parent
- e0b31b172982
spinel_codegen.rbmodifiedView file
@@ -129,6 +129,10 @@
129129
@needs_file_io = 0130130
@needs_mutable_str = 0131131
@needs_rb_value = 0132+
133+
# Poly tracking: functions with params called with different types134+
@poly_funcs = "".split(",")135+
@poly_param_types = "".split(",")132136
end133137
134138
def join_sep(arr, sep)@@ -978,6 +982,9 @@
978982
if mname == "empty?"979983
return "bool"980984
end985+
if mname == "nil?"986+
return "bool"987+
end981988
if mname == "has_key?"982989
return "bool"983990
end@@ -1152,9 +1159,24 @@
11521159
return "int_array"11531160
end11541161
1155-
# Method call on object1162+
# Method call on poly11561163
if recv >= 011571164
rt = infer_type(recv)1165+
if rt == "poly"1166+
if mname == "nil?"1167+
return "bool"1168+
end1169+
# Check all classes for this method and return the first matching return type1170+
ci = 01171+
while ci < @cls_names.length1172+
midx = cls_find_method_direct(ci, mname)1173+
if midx >= 01174+
return cls_method_return(ci, mname)1175+
end1176+
ci = ci + 11177+
end1178+
return "int"1179+
end11581180
if is_obj_type(rt) == 111591181
cname = rt[4, rt.length - 4]11601182
ci = find_class_idx(cname)@@ -1263,6 +1285,9 @@
12631285
if t == "str_str_hash"12641286
return "sp_StrStrHash *"12651287
end1288+
if t == "poly"1289+
return "sp_RbVal"1290+
end12661291
if is_obj_type(t) == 112671292
cname = t[4, t.length - 4]12681293
return "sp_" + cname + " *"@@ -1289,6 +1314,9 @@
12891314
if t == "nil"12901315
return "0"12911316
end1317+
if t == "poly"1318+
return "sp_box_nil()"1319+
end12921320
if type_is_pointer(t) == 112931321
return "NULL"12941322
end@@ -2814,9 +2842,161 @@
28142842
pop_scope28152843
end28162844
2845+
def detect_poly_params2846+
# Scan all call sites to detect functions called with different param types2847+
stmts = get_body_stmts(@root_id)2848+
i = 02849+
while i < stmts.length2850+
detect_poly_in_node(stmts[i])2851+
i = i + 12852+
end2853+
end2854+
2855+
def detect_poly_in_node(nid)2856+
if nid < 02857+
return2858+
end2859+
if @nd_type[nid] == "CallNode"2860+
mname = @nd_name[nid]2861+
if @nd_receiver[nid] < 02862+
mi = find_method_idx(mname)2863+
if mi >= 02864+
args_id = @nd_arguments[nid]2865+
if args_id >= 02866+
arg_ids = get_args(args_id)2867+
ptypes = @meth_param_types[mi].split(",")2868+
k = 02869+
while k < arg_ids.length2870+
at = infer_type(arg_ids[k])2871+
if k < ptypes.length2872+
ct = ptypes[k]2873+
if ct != at2874+
if ct != "poly"2875+
# Types differ - mark as poly2876+
ptypes[k] = "poly"2877+
@needs_rb_value = 12878+
end2879+
end2880+
end2881+
k = k + 12882+
end2883+
@meth_param_types[mi] = join_sep(ptypes, ",")2884+
end2885+
end2886+
end2887+
end2888+
# Recurse2889+
if @nd_body[nid] >= 02890+
detect_poly_in_node(@nd_body[nid])2891+
end2892+
stmts = parse_id_list(@nd_stmts[nid])2893+
k = 02894+
while k < stmts.length2895+
detect_poly_in_node(stmts[k])2896+
k = k + 12897+
end2898+
if @nd_expression[nid] >= 02899+
detect_poly_in_node(@nd_expression[nid])2900+
end2901+
if @nd_arguments[nid] >= 02902+
detect_poly_in_node(@nd_arguments[nid])2903+
end2904+
args = parse_id_list(@nd_args[nid])2905+
k = 02906+
while k < args.length2907+
detect_poly_in_node(args[k])2908+
k = k + 12909+
end2910+
if @nd_predicate[nid] >= 02911+
detect_poly_in_node(@nd_predicate[nid])2912+
end2913+
if @nd_subsequent[nid] >= 02914+
detect_poly_in_node(@nd_subsequent[nid])2915+
end2916+
if @nd_else_clause[nid] >= 02917+
detect_poly_in_node(@nd_else_clause[nid])2918+
end2919+
if @nd_block[nid] >= 02920+
detect_poly_in_node(@nd_block[nid])2921+
end2922+
conds = parse_id_list(@nd_conditions[nid])2923+
k = 02924+
while k < conds.length2925+
detect_poly_in_node(conds[k])2926+
k = k + 12927+
end2928+
end2929+
2930+
def detect_poly_locals2931+
# Detect local variables assigned different types in main scope2932+
stmts = get_body_stmts(@root_id)2933+
local_types = "".split(",")2934+
local_names = "".split(",")2935+
i = 02936+
while i < stmts.length2937+
sid = stmts[i]2938+
if @nd_type[sid] != "DefNode"2939+
if @nd_type[sid] != "ClassNode"2940+
scan_poly_assigns(sid, local_names, local_types)2941+
end2942+
end2943+
i = i + 12944+
end2945+
end2946+
2947+
def scan_poly_assigns(nid, names, types)2948+
if nid < 02949+
return2950+
end2951+
if @nd_type[nid] == "LocalVariableWriteNode"2952+
lname = @nd_name[nid]2953+
at = infer_type(@nd_expression[nid])2954+
idx = -12955+
k = 02956+
while k < names.length2957+
if names[k] == lname2958+
idx = k2959+
end2960+
k = k + 12961+
end2962+
if idx >= 02963+
if types[idx] != at2964+
if types[idx] != "poly"2965+
types[idx] = "poly"2966+
@needs_rb_value = 12967+
end2968+
end2969+
else2970+
names.push(lname)2971+
types.push(at)2972+
end2973+
end2974+
# Recurse2975+
if @nd_body[nid] >= 02976+
scan_poly_assigns(@nd_body[nid], names, types)2977+
end2978+
stmts = parse_id_list(@nd_stmts[nid])2979+
k = 02980+
while k < stmts.length2981+
scan_poly_assigns(stmts[k], names, types)2982+
k = k + 12983+
end2984+
if @nd_expression[nid] >= 02985+
scan_poly_assigns(@nd_expression[nid], names, types)2986+
end2987+
if @nd_subsequent[nid] >= 02988+
scan_poly_assigns(@nd_subsequent[nid], names, types)2989+
end2990+
if @nd_else_clause[nid] >= 02991+
scan_poly_assigns(@nd_else_clause[nid], names, types)2992+
end2993+
end2994+
28172995
def compile28182996
collect_all28192997
infer_main_call_types2998+
detect_poly_params2999+
detect_poly_locals28203000
# Re-infer return types after main call type fixes28213001
infer_all_returns28223002
detect_features@@ -2854,6 +3034,9 @@
28543034
end28553035
emit_string_helpers28563036
end3037+
if @needs_rb_value == 13038+
emit_rb_value_runtime3039+
end28573040
if @needs_setjmp == 128583041
emit_setjmp_runtime28593042
end@@ -3000,6 +3183,37 @@
30003183
emit_raw("")30013184
end30023185
3186+
def emit_rb_value_runtime3187+
emit_raw("/* NaN-boxed polymorphic value */")3188+
emit_raw("typedef uint64_t sp_RbValue;")3189+
emit_raw("#define SP_TAG_INT 0")3190+
emit_raw("#define SP_TAG_STR 1")3191+
emit_raw("#define SP_TAG_FLT 2")3192+
emit_raw("#define SP_TAG_BOOL 3")3193+
emit_raw("#define SP_TAG_NIL 4")3194+
emit_raw("#define SP_TAG_OBJ 5")3195+
emit_raw("typedef struct { int tag; union { mrb_int i; const char *s; mrb_float f; mrb_bool b; void *p; int cls_id; } v; } sp_RbVal;")3196+
emit_raw("static sp_RbVal sp_box_int(mrb_int v) { sp_RbVal r; r.tag = SP_TAG_INT; r.v.i = v; return r; }")3197+
emit_raw("static sp_RbVal sp_box_str(const char *v) { sp_RbVal r; r.tag = SP_TAG_STR; r.v.s = v; return r; }")3198+
emit_raw("static sp_RbVal sp_box_float(mrb_float v) { sp_RbVal r; r.tag = SP_TAG_FLT; r.v.f = v; return r; }")3199+
emit_raw("static sp_RbVal sp_box_bool(mrb_bool v) { sp_RbVal r; r.tag = SP_TAG_BOOL; r.v.b = v; return r; }")3200+
emit_raw("static sp_RbVal sp_box_nil(void) { sp_RbVal r; r.tag = SP_TAG_NIL; r.v.i = 0; return r; }")3201+
emit_raw("static sp_RbVal sp_box_obj(void *p, int cls_id) { sp_RbVal r; r.tag = SP_TAG_OBJ; r.v.p = p; r.v.cls_id = cls_id; return r; }")3202+
emit_raw("static void sp_poly_puts(sp_RbVal v) {")3203+
emit_raw(" switch (v.tag) {")3204+
emit_raw(" case SP_TAG_INT: printf(\"%lld\\n\", (long long)v.v.i); break;")3205+
emit_raw(" case SP_TAG_STR: if (v.v.s) { fputs(v.v.s, stdout); if (!*v.v.s || v.v.s[strlen(v.v.s)-1] != '\\n') putchar('\\n'); } else putchar('\\n'); break;")3206+
emit_raw(" case SP_TAG_FLT: printf(\"%g\\n\", v.v.f); break;")3207+
emit_raw(" case SP_TAG_BOOL: puts(v.v.b ? \"true\" : \"false\"); break;")3208+
emit_raw(" case SP_TAG_NIL: putchar('\\n'); break;")3209+
emit_raw(" default: printf(\"%lld\\n\", (long long)v.v.i); break;")3210+
emit_raw(" }")3211+
emit_raw("}")3212+
emit_raw("static mrb_bool sp_poly_nil_p(sp_RbVal v) { return v.tag == SP_TAG_NIL; }")3213+
emit_raw("static const char *sp_poly_to_s(sp_RbVal v) { switch (v.tag) { case SP_TAG_INT: { char *b = (char*)malloc(32); snprintf(b, 32, \"%lld\", (long long)v.v.i); return b; } case SP_TAG_STR: return v.v.s ? v.v.s : \"\"; case SP_TAG_FLT: { char *b = (char*)malloc(64); snprintf(b, 64, \"%g\", v.v.f); return b; } case SP_TAG_BOOL: return v.v.b ? \"true\" : \"false\"; case SP_TAG_NIL: return \"\"; default: return \"\"; } }")3214+
emit_raw("")3215+
end3216+
30033217
def emit_setjmp_runtime30043218
emit_raw("#include <setjmp.h>")30053219
emit_raw("#define SP_EXC_STACK_MAX 64")@@ -3840,6 +4054,23 @@
38404054
names.push(lname)38414055
types.push(infer_type(@nd_expression[nid]))38424056
end4057+
else4058+
if not_in(lname, params) == 14059+
# Check if type changed4060+
at = infer_type(@nd_expression[nid])4061+
ki = 04062+
while ki < names.length4063+
if names[ki] == lname4064+
if types[ki] != at4065+
if types[ki] != "poly"4066+
types[ki] = "poly"4067+
@needs_rb_value = 14068+
end4069+
end4070+
end4071+
ki = ki + 14072+
end4073+
end38434074
end38444075
end38454076
if @nd_type[nid] == "LocalVariableOperatorWriteNode"@@ -4376,8 +4607,13 @@
43764607
fmt = fmt + "%s"43774608
arg_exprs.push("(" + compile_expr(inner) + " ? \"true\" : \"false\")")43784609
else4379-
fmt = fmt + "%lld"4380-
arg_exprs.push("(long long)" + compile_expr(inner))4610+
if it == "poly"4611+
fmt = fmt + "%s"4612+
arg_exprs.push("sp_poly_to_s(" + compile_expr(inner) + ")")4613+
else4614+
fmt = fmt + "%lld"4615+
arg_exprs.push("(long long)" + compile_expr(inner))4616+
end43814617
end43824618
end43834619
end@@ -4843,6 +5079,11 @@
48435079
end48445080
end48455081
5082+
# Poly method calls5083+
if recv_type == "poly"5084+
return compile_poly_method_call(nid, rc, mname)5085+
end5086+
48465087
# Object method calls48475088
if is_obj_type(recv_type) == 148485089
cname = recv_type[4, recv_type.length - 4]@@ -4895,6 +5136,32 @@
48955136
"0"48965137
end48975138
5139+
def compile_poly_method_call(nid, rc, mname)5140+
@needs_rb_value = 15141+
if mname == "nil?"5142+
return "sp_poly_nil_p(" + rc + ")"5143+
end5144+
# For object method calls, dispatch based on cls_id5145+
# Generate: switch on v.tag and cls_id5146+
tmp = new_temp5147+
emit(" const char *" + tmp + " = \"\";")5148+
emit(" if (" + rc + ".tag == SP_TAG_OBJ) {")5149+
# Dispatch to each possible class5150+
i = 05151+
while i < @cls_names.length5152+
cname = @cls_names[i]5153+
mi = cls_find_method(@cls_names.length - 1 - i, mname)5154+
# Check if this class has the method5155+
midx = cls_find_method_direct(i, mname)5156+
if midx >= 05157+
emit(" if (" + rc + ".v.cls_id == " + i.to_s + ") " + tmp + " = sp_" + cname + "_" + sanitize_name(mname) + "((sp_" + cname + " *)" + rc + ".v.p);")5158+
end5159+
i = i + 15160+
end5161+
emit(" }")5162+
tmp5163+
end5164+
48985165
def compile_eq(nid, op)48995166
recv = @nd_receiver[nid]49005167
lt = infer_type(recv)@@ -4941,6 +5208,32 @@
49415208
"(" + lc + " " + op + " " + rc + ")"49425209
end49435210
5211+
def box_expr_to_poly(nid)5212+
at = infer_type(nid)5213+
val = compile_expr(nid)5214+
if at == "int"5215+
return "sp_box_int(" + val + ")"5216+
end5217+
if at == "string"5218+
return "sp_box_str(" + val + ")"5219+
end5220+
if at == "float"5221+
return "sp_box_float(" + val + ")"5222+
end5223+
if at == "bool"5224+
return "sp_box_bool(" + val + ")"5225+
end5226+
if at == "nil"5227+
return "sp_box_nil()"5228+
end5229+
if is_obj_type(at) == 15230+
cname = at[4, at.length - 4]5231+
ci = find_class_idx(cname)5232+
return "sp_box_obj(" + val + ", " + ci.to_s + ")"5233+
end5234+
"sp_box_int(" + val + ")"5235+
end5236+
49445237
def compile_call_args_with_defaults(nid, mi)49455238
args_id = @nd_arguments[nid]49465239
arg_ids = []@@ -4948,6 +5241,7 @@
49485241
arg_ids = get_args(args_id)49495242
end49505243
pnames = @meth_param_names[mi].split(",")5244+
ptypes = @meth_param_types[mi].split(",")49515245
defaults = @meth_has_defaults[mi].split(",")49525246
result = ""49535247
k = 0@@ -4956,6 +5250,14 @@
49565250
result = result + ", "49575251
end49585252
if k < arg_ids.length5253+
# Check if param is poly - box the value5254+
if k < ptypes.length5255+
if ptypes[k] == "poly"5256+
result = result + box_expr_to_poly(arg_ids[k])5257+
k = k + 15258+
next5259+
end5260+
end49595261
result = result + compile_expr(arg_ids[k])49605262
else49615263
# Use default value@@ -5132,9 +5434,16 @@
51325434
end51335435
t = @nd_type[nid]51345436
if t == "LocalVariableWriteNode"5437+
lname = @nd_name[nid]5438+
vt = find_var_type(lname)5439+
if vt == "poly"5440+
# Box the value5441+
emit(" lv_" + lname + " = " + box_expr_to_poly(@nd_expression[nid]) + ";")5442+
return5443+
end51355444
val = compile_expr(@nd_expression[nid])5136-
emit(" lv_" + @nd_name[nid] + " = " + val + ";")5137-
set_var_type(@nd_name[nid], infer_type(@nd_expression[nid]))5445+
emit(" lv_" + lname + " = " + val + ";")5446+
set_var_type(lname, infer_type(@nd_expression[nid]))51385447
return51395448
end51405449
if t == "LocalVariableOperatorWriteNode"@@ -5432,20 +5741,21 @@
54325741
end54335742
54345743
def compile_case_match_stmt(nid)5435-
# case/in pattern matching5436-
# For now, handle type patterns (Integer, String, Float, true, false, nil)5437-
# and value patterns54385744
pred = @nd_predicate[nid]54395745
pred_type = infer_type(pred)54405746
pred_val = compile_expr(pred)54415747
tmp = new_temp5442-
if pred_type == "string"5443-
emit(" const char *" + tmp + " = " + pred_val + ";")5748+
if pred_type == "poly"5749+
emit(" sp_RbVal " + tmp + " = " + pred_val + ";")54445750
else5445-
if pred_type == "float"5446-
emit(" mrb_float " + tmp + " = " + pred_val + ";")5751+
if pred_type == "string"5752+
emit(" const char *" + tmp + " = " + pred_val + ";")54475753
else5448-
emit(" mrb_int " + tmp + " = " + pred_val + ";")5754+
if pred_type == "float"5755+
emit(" mrb_float " + tmp + " = " + pred_val + ";")5756+
else5757+
emit(" mrb_int " + tmp + " = " + pred_val + ";")5758+
end54495759
end54505760
end54515761
conds = parse_id_list(@nd_conditions[nid])@@ -5485,34 +5795,60 @@
54855795
pt = @nd_type[pat_id]54865796
if pt == "ConstantReadNode"54875797
cname = @nd_name[pat_id]5798+
if pred_type == "poly"5799+
if cname == "Integer"5800+
return tmp + ".tag == SP_TAG_INT"5801+
end5802+
if cname == "String"5803+
return tmp + ".tag == SP_TAG_STR"5804+
end5805+
if cname == "Float"5806+
return tmp + ".tag == SP_TAG_FLT"5807+
end5808+
return "0"5809+
end54885810
if cname == "Integer"5489-
return "1" # For monomorphic int, always true5811+
return "1"54905812
end54915813
if cname == "String"5492-
return "1" # For monomorphic string, always true5814+
return "1"54935815
end54945816
if cname == "Float"5495-
return "1" # For monomorphic float, always true5817+
return "1"54965818
end54975819
return "0"54985820
end54995821
if pt == "IntegerNode"5822+
if pred_type == "poly"5823+
return "(" + tmp + ".tag == SP_TAG_INT && " + tmp + ".v.i == " + @nd_value[pat_id].to_s + ")"5824+
end55005825
return tmp + " == " + @nd_value[pat_id].to_s55015826
end55025827
if pt == "StringNode"5828+
if pred_type == "poly"5829+
return "(" + tmp + ".tag == SP_TAG_STR && strcmp(" + tmp + ".v.s, " + c_string_literal(@nd_content[pat_id]) + ") == 0)"5830+
end55035831
return "strcmp(" + tmp + ", " + c_string_literal(@nd_content[pat_id]) + ") == 0"55045832
end55055833
if pt == "NilNode"5834+
if pred_type == "poly"5835+
return tmp + ".tag == SP_TAG_NIL"5836+
end55065837
return tmp + " == 0"55075838
end55085839
if pt == "TrueNode"5840+
if pred_type == "poly"5841+
return "(" + tmp + ".tag == SP_TAG_BOOL && " + tmp + ".v.b)"5842+
end55095843
return tmp + " != 0"55105844
end55115845
if pt == "FalseNode"5846+
if pred_type == "poly"5847+
return "(" + tmp + ".tag == SP_TAG_BOOL && !" + tmp + ".v.b)"5848+
end55125849
return tmp + " == 0"55135850
end55145851
if pt == "AlternationPatternNode"5515-
# true | false pattern55165852
left = compile_in_pattern(@nd_left[pat_id], tmp, pred_type)55175853
right = compile_in_pattern(@nd_right[pat_id], tmp, pred_type)55185854
return "(" + left + " || " + right + ")"@@ -5931,6 +6267,12 @@
59316267
aid = arg_ids[k]59326268
at = infer_type(aid)59336269
val = compile_expr(aid)6270+
if at == "poly"6271+
@needs_rb_value = 16272+
emit(" sp_poly_puts(" + val + ");")6273+
k = k + 16274+
next6275+
end59346276
if at == "int"59356277
emit(" printf(\"%lld\\n\", (long long)" + val + ");")59366278
else@@ -7339,13 +7681,17 @@
73397681
pred_type = infer_type(pred)73407682
pred_val = compile_expr(pred)73417683
tmp = new_temp7342-
if pred_type == "string"7343-
emit(" const char *" + tmp + " = " + pred_val + ";")7684+
if pred_type == "poly"7685+
emit(" sp_RbVal " + tmp + " = " + pred_val + ";")73447686
else7345-
if pred_type == "float"7346-
emit(" mrb_float " + tmp + " = " + pred_val + ";")7687+
if pred_type == "string"7688+
emit(" const char *" + tmp + " = " + pred_val + ";")73477689
else7348-
emit(" mrb_int " + tmp + " = " + pred_val + ";")7690+
if pred_type == "float"7691+
emit(" mrb_float " + tmp + " = " + pred_val + ";")7692+
else7693+
emit(" mrb_int " + tmp + " = " + pred_val + ";")7694+
end73497695
end73507696
end73517697
conds = parse_id_list(@nd_conditions[nid])