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 = 0
130130 @needs_mutable_str = 0
131131 @needs_rb_value = 0
132+
133+ # Poly tracking: functions with params called with different types
134+ @poly_funcs = "".split(",")
135+ @poly_param_types = "".split(",")
132136 end
133137
134138 def join_sep(arr, sep)
@@ -978,6 +982,9 @@
978982 if mname == "empty?"
979983 return "bool"
980984 end
985+ if mname == "nil?"
986+ return "bool"
987+ end
981988 if mname == "has_key?"
982989 return "bool"
983990 end
@@ -1152,9 +1159,24 @@
11521159 return "int_array"
11531160 end
11541161
1155- # Method call on object
1162+ # Method call on poly
11561163 if recv >= 0
11571164 rt = infer_type(recv)
1165+ if rt == "poly"
1166+ if mname == "nil?"
1167+ return "bool"
1168+ end
1169+ # Check all classes for this method and return the first matching return type
1170+ ci = 0
1171+ while ci < @cls_names.length
1172+ midx = cls_find_method_direct(ci, mname)
1173+ if midx >= 0
1174+ return cls_method_return(ci, mname)
1175+ end
1176+ ci = ci + 1
1177+ end
1178+ return "int"
1179+ end
11581180 if is_obj_type(rt) == 1
11591181 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 end
1288+ if t == "poly"
1289+ return "sp_RbVal"
1290+ end
12661291 if is_obj_type(t) == 1
12671292 cname = t[4, t.length - 4]
12681293 return "sp_" + cname + " *"
@@ -1289,6 +1314,9 @@
12891314 if t == "nil"
12901315 return "0"
12911316 end
1317+ if t == "poly"
1318+ return "sp_box_nil()"
1319+ end
12921320 if type_is_pointer(t) == 1
12931321 return "NULL"
12941322 end
@@ -2814,9 +2842,161 @@
28142842 pop_scope
28152843 end
28162844
2845+ def detect_poly_params
2846+ # Scan all call sites to detect functions called with different param types
2847+ stmts = get_body_stmts(@root_id)
2848+ i = 0
2849+ while i < stmts.length
2850+ detect_poly_in_node(stmts[i])
2851+ i = i + 1
2852+ end
2853+ end
2854+
2855+ def detect_poly_in_node(nid)
2856+ if nid < 0
2857+ return
2858+ end
2859+ if @nd_type[nid] == "CallNode"
2860+ mname = @nd_name[nid]
2861+ if @nd_receiver[nid] < 0
2862+ mi = find_method_idx(mname)
2863+ if mi >= 0
2864+ args_id = @nd_arguments[nid]
2865+ if args_id >= 0
2866+ arg_ids = get_args(args_id)
2867+ ptypes = @meth_param_types[mi].split(",")
2868+ k = 0
2869+ while k < arg_ids.length
2870+ at = infer_type(arg_ids[k])
2871+ if k < ptypes.length
2872+ ct = ptypes[k]
2873+ if ct != at
2874+ if ct != "poly"
2875+ # Types differ - mark as poly
2876+ ptypes[k] = "poly"
2877+ @needs_rb_value = 1
2878+ end
2879+ end
2880+ end
2881+ k = k + 1
2882+ end
2883+ @meth_param_types[mi] = join_sep(ptypes, ",")
2884+ end
2885+ end
2886+ end
2887+ end
2888+ # Recurse
2889+ if @nd_body[nid] >= 0
2890+ detect_poly_in_node(@nd_body[nid])
2891+ end
2892+ stmts = parse_id_list(@nd_stmts[nid])
2893+ k = 0
2894+ while k < stmts.length
2895+ detect_poly_in_node(stmts[k])
2896+ k = k + 1
2897+ end
2898+ if @nd_expression[nid] >= 0
2899+ detect_poly_in_node(@nd_expression[nid])
2900+ end
2901+ if @nd_arguments[nid] >= 0
2902+ detect_poly_in_node(@nd_arguments[nid])
2903+ end
2904+ args = parse_id_list(@nd_args[nid])
2905+ k = 0
2906+ while k < args.length
2907+ detect_poly_in_node(args[k])
2908+ k = k + 1
2909+ end
2910+ if @nd_predicate[nid] >= 0
2911+ detect_poly_in_node(@nd_predicate[nid])
2912+ end
2913+ if @nd_subsequent[nid] >= 0
2914+ detect_poly_in_node(@nd_subsequent[nid])
2915+ end
2916+ if @nd_else_clause[nid] >= 0
2917+ detect_poly_in_node(@nd_else_clause[nid])
2918+ end
2919+ if @nd_block[nid] >= 0
2920+ detect_poly_in_node(@nd_block[nid])
2921+ end
2922+ conds = parse_id_list(@nd_conditions[nid])
2923+ k = 0
2924+ while k < conds.length
2925+ detect_poly_in_node(conds[k])
2926+ k = k + 1
2927+ end
2928+ end
2929+
2930+ def detect_poly_locals
2931+ # Detect local variables assigned different types in main scope
2932+ stmts = get_body_stmts(@root_id)
2933+ local_types = "".split(",")
2934+ local_names = "".split(",")
2935+ i = 0
2936+ while i < stmts.length
2937+ 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+ end
2942+ end
2943+ i = i + 1
2944+ end
2945+ end
2946+
2947+ def scan_poly_assigns(nid, names, types)
2948+ if nid < 0
2949+ return
2950+ end
2951+ if @nd_type[nid] == "LocalVariableWriteNode"
2952+ lname = @nd_name[nid]
2953+ at = infer_type(@nd_expression[nid])
2954+ idx = -1
2955+ k = 0
2956+ while k < names.length
2957+ if names[k] == lname
2958+ idx = k
2959+ end
2960+ k = k + 1
2961+ end
2962+ if idx >= 0
2963+ if types[idx] != at
2964+ if types[idx] != "poly"
2965+ types[idx] = "poly"
2966+ @needs_rb_value = 1
2967+ end
2968+ end
2969+ else
2970+ names.push(lname)
2971+ types.push(at)
2972+ end
2973+ end
2974+ # Recurse
2975+ if @nd_body[nid] >= 0
2976+ scan_poly_assigns(@nd_body[nid], names, types)
2977+ end
2978+ stmts = parse_id_list(@nd_stmts[nid])
2979+ k = 0
2980+ while k < stmts.length
2981+ scan_poly_assigns(stmts[k], names, types)
2982+ k = k + 1
2983+ end
2984+ if @nd_expression[nid] >= 0
2985+ scan_poly_assigns(@nd_expression[nid], names, types)
2986+ end
2987+ if @nd_subsequent[nid] >= 0
2988+ scan_poly_assigns(@nd_subsequent[nid], names, types)
2989+ end
2990+ if @nd_else_clause[nid] >= 0
2991+ scan_poly_assigns(@nd_else_clause[nid], names, types)
2992+ end
2993+ end
2994+
28172995 def compile
28182996 collect_all
28192997 infer_main_call_types
2998+ detect_poly_params
2999+ detect_poly_locals
28203000 # Re-infer return types after main call type fixes
28213001 infer_all_returns
28223002 detect_features
@@ -2854,6 +3034,9 @@
28543034 end
28553035 emit_string_helpers
28563036 end
3037+ if @needs_rb_value == 1
3038+ emit_rb_value_runtime
3039+ end
28573040 if @needs_setjmp == 1
28583041 emit_setjmp_runtime
28593042 end
@@ -3000,6 +3183,37 @@
30003183 emit_raw("")
30013184 end
30023185
3186+ def emit_rb_value_runtime
3187+ 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+ end
3216+
30033217 def emit_setjmp_runtime
30043218 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 end
4057+ else
4058+ if not_in(lname, params) == 1
4059+ # Check if type changed
4060+ at = infer_type(@nd_expression[nid])
4061+ ki = 0
4062+ while ki < names.length
4063+ if names[ki] == lname
4064+ if types[ki] != at
4065+ if types[ki] != "poly"
4066+ types[ki] = "poly"
4067+ @needs_rb_value = 1
4068+ end
4069+ end
4070+ end
4071+ ki = ki + 1
4072+ end
4073+ end
38434074 end
38444075 end
38454076 if @nd_type[nid] == "LocalVariableOperatorWriteNode"
@@ -4376,8 +4607,13 @@
43764607 fmt = fmt + "%s"
43774608 arg_exprs.push("(" + compile_expr(inner) + " ? \"true\" : \"false\")")
43784609 else
4379- 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+ else
4614+ fmt = fmt + "%lld"
4615+ arg_exprs.push("(long long)" + compile_expr(inner))
4616+ end
43814617 end
43824618 end
43834619 end
@@ -4843,6 +5079,11 @@
48435079 end
48445080 end
48455081
5082+ # Poly method calls
5083+ if recv_type == "poly"
5084+ return compile_poly_method_call(nid, rc, mname)
5085+ end
5086+
48465087 # Object method calls
48475088 if is_obj_type(recv_type) == 1
48485089 cname = recv_type[4, recv_type.length - 4]
@@ -4895,6 +5136,32 @@
48955136 "0"
48965137 end
48975138
5139+ def compile_poly_method_call(nid, rc, mname)
5140+ @needs_rb_value = 1
5141+ if mname == "nil?"
5142+ return "sp_poly_nil_p(" + rc + ")"
5143+ end
5144+ # For object method calls, dispatch based on cls_id
5145+ # Generate: switch on v.tag and cls_id
5146+ tmp = new_temp
5147+ emit(" const char *" + tmp + " = \"\";")
5148+ emit(" if (" + rc + ".tag == SP_TAG_OBJ) {")
5149+ # Dispatch to each possible class
5150+ i = 0
5151+ while i < @cls_names.length
5152+ cname = @cls_names[i]
5153+ mi = cls_find_method(@cls_names.length - 1 - i, mname)
5154+ # Check if this class has the method
5155+ midx = cls_find_method_direct(i, mname)
5156+ if midx >= 0
5157+ emit(" if (" + rc + ".v.cls_id == " + i.to_s + ") " + tmp + " = sp_" + cname + "_" + sanitize_name(mname) + "((sp_" + cname + " *)" + rc + ".v.p);")
5158+ end
5159+ i = i + 1
5160+ end
5161+ emit(" }")
5162+ tmp
5163+ end
5164+
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 end
49435210
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+ end
5217+ if at == "string"
5218+ return "sp_box_str(" + val + ")"
5219+ end
5220+ if at == "float"
5221+ return "sp_box_float(" + val + ")"
5222+ end
5223+ if at == "bool"
5224+ return "sp_box_bool(" + val + ")"
5225+ end
5226+ if at == "nil"
5227+ return "sp_box_nil()"
5228+ end
5229+ if is_obj_type(at) == 1
5230+ cname = at[4, at.length - 4]
5231+ ci = find_class_idx(cname)
5232+ return "sp_box_obj(" + val + ", " + ci.to_s + ")"
5233+ end
5234+ "sp_box_int(" + val + ")"
5235+ end
5236+
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 end
49505243 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 end
49585252 if k < arg_ids.length
5253+ # Check if param is poly - box the value
5254+ if k < ptypes.length
5255+ if ptypes[k] == "poly"
5256+ result = result + box_expr_to_poly(arg_ids[k])
5257+ k = k + 1
5258+ next
5259+ end
5260+ end
49595261 result = result + compile_expr(arg_ids[k])
49605262 else
49615263 # Use default value
@@ -5132,9 +5434,16 @@
51325434 end
51335435 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 value
5441+ emit(" lv_" + lname + " = " + box_expr_to_poly(@nd_expression[nid]) + ";")
5442+ return
5443+ end
51355444 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 return
51395448 end
51405449 if t == "LocalVariableOperatorWriteNode"
@@ -5432,20 +5741,21 @@
54325741 end
54335742
54345743 def compile_case_match_stmt(nid)
5435- # case/in pattern matching
5436- # For now, handle type patterns (Integer, String, Float, true, false, nil)
5437- # and value patterns
54385744 pred = @nd_predicate[nid]
54395745 pred_type = infer_type(pred)
54405746 pred_val = compile_expr(pred)
54415747 tmp = new_temp
5442- if pred_type == "string"
5443- emit(" const char *" + tmp + " = " + pred_val + ";")
5748+ if pred_type == "poly"
5749+ emit(" sp_RbVal " + tmp + " = " + pred_val + ";")
54445750 else
5445- if pred_type == "float"
5446- emit(" mrb_float " + tmp + " = " + pred_val + ";")
5751+ if pred_type == "string"
5752+ emit(" const char *" + tmp + " = " + pred_val + ";")
54475753 else
5448- emit(" mrb_int " + tmp + " = " + pred_val + ";")
5754+ if pred_type == "float"
5755+ emit(" mrb_float " + tmp + " = " + pred_val + ";")
5756+ else
5757+ emit(" mrb_int " + tmp + " = " + pred_val + ";")
5758+ end
54495759 end
54505760 end
54515761 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+ end
5802+ if cname == "String"
5803+ return tmp + ".tag == SP_TAG_STR"
5804+ end
5805+ if cname == "Float"
5806+ return tmp + ".tag == SP_TAG_FLT"
5807+ end
5808+ return "0"
5809+ end
54885810 if cname == "Integer"
5489- return "1" # For monomorphic int, always true
5811+ return "1"
54905812 end
54915813 if cname == "String"
5492- return "1" # For monomorphic string, always true
5814+ return "1"
54935815 end
54945816 if cname == "Float"
5495- return "1" # For monomorphic float, always true
5817+ return "1"
54965818 end
54975819 return "0"
54985820 end
54995821 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+ end
55005825 return tmp + " == " + @nd_value[pat_id].to_s
55015826 end
55025827 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+ end
55035831 return "strcmp(" + tmp + ", " + c_string_literal(@nd_content[pat_id]) + ") == 0"
55045832 end
55055833 if pt == "NilNode"
5834+ if pred_type == "poly"
5835+ return tmp + ".tag == SP_TAG_NIL"
5836+ end
55065837 return tmp + " == 0"
55075838 end
55085839 if pt == "TrueNode"
5840+ if pred_type == "poly"
5841+ return "(" + tmp + ".tag == SP_TAG_BOOL && " + tmp + ".v.b)"
5842+ end
55095843 return tmp + " != 0"
55105844 end
55115845 if pt == "FalseNode"
5846+ if pred_type == "poly"
5847+ return "(" + tmp + ".tag == SP_TAG_BOOL && !" + tmp + ".v.b)"
5848+ end
55125849 return tmp + " == 0"
55135850 end
55145851 if pt == "AlternationPatternNode"
5515- # true | false pattern
55165852 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 = 1
6272+ emit(" sp_poly_puts(" + val + ");")
6273+ k = k + 1
6274+ next
6275+ end
59346276 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_temp
7342- if pred_type == "string"
7343- emit(" const char *" + tmp + " = " + pred_val + ";")
7684+ if pred_type == "poly"
7685+ emit(" sp_RbVal " + tmp + " = " + pred_val + ";")
73447686 else
7345- if pred_type == "float"
7346- emit(" mrb_float " + tmp + " = " + pred_val + ";")
7687+ if pred_type == "string"
7688+ emit(" const char *" + tmp + " = " + pred_val + ";")
73477689 else
7348- emit(" mrb_int " + tmp + " = " + pred_val + ";")
7690+ if pred_type == "float"
7691+ emit(" mrb_float " + tmp + " = " + pred_val + ";")
7692+ else
7693+ emit(" mrb_int " + tmp + " = " + pred_val + ";")
7694+ end
73497695 end
73507696 end
73517697 conds = parse_id_list(@nd_conditions[nid])