Commit e0b31b17
e0b31b172982Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 1 file · ~1 modified
Description
feat: Phase 7 - mutable strings, Struct.new, case/in patterns
Add string << as sp_str_concat reassignment for mutable strings. Add String#reverse. Add Struct.new(:x, :y) synthetic class gen. Add CaseMatchNode/InNode compilation for case/in pattern matching. Pattern matching with type dispatch deferred to Phase 8 (poly).
Tests passing: bm_mutable_str, bm_struct
Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]
Details
- Commit
- e0b31b172982
- Parent
- eae72ec81822
spinel_codegen.rbmodifiedView file
@@ -791,6 +791,23 @@
791791
end792792
return "void"793793
end794+
if t == "CaseMatchNode"795+
# Infer from first in branch796+
conds = parse_id_list(@nd_conditions[nid])797+
if conds.length > 0798+
inid = conds[0]799+
if @nd_type[inid] == "InNode"800+
ibody = @nd_body[inid]801+
if ibody >= 0802+
is = get_stmts(ibody)803+
if is.length > 0804+
return infer_type(is[is.length - 1])805+
end806+
end807+
end808+
end809+
return "int"810+
end794811
if t == "CaseNode"795812
# Infer from first when branch796813
conds = parse_id_list(@nd_conditions[nid])@@ -1838,8 +1855,24 @@
18381855
end18391856
18401857
def collect_constant(nid)1841-
@const_names.push(@nd_name[nid])1858+
# Check for Struct.new(:x, :y)18421859
expr_id = @nd_expression[nid]1860+
if expr_id >= 01861+
if @nd_type[expr_id] == "CallNode"1862+
if @nd_name[expr_id] == "new"1863+
sr = @nd_receiver[expr_id]1864+
if sr >= 01865+
if @nd_type[sr] == "ConstantReadNode"1866+
if @nd_name[sr] == "Struct"1867+
collect_struct_class(@nd_name[nid], expr_id)1868+
return1869+
end1870+
end1871+
end1872+
end1873+
end1874+
end1875+
@const_names.push(@nd_name[nid])18431876
ct = "int"18441877
if expr_id >= 018451878
ct = infer_type(expr_id)@@ -1848,6 +1881,74 @@
18481881
@const_expr_ids.push(expr_id)18491882
end18501883
1884+
def collect_struct_class(cname, call_nid)1885+
# Generate a synthetic class from Struct.new(:field1, :field2, ...)1886+
ci = @cls_names.length1887+
@cls_names.push(cname)1888+
@cls_parents.push("")1889+
@cls_ivar_names.push("")1890+
@cls_ivar_types.push("")1891+
@cls_meth_names.push("")1892+
@cls_meth_params.push("")1893+
@cls_meth_ptypes.push("")1894+
@cls_meth_returns.push("")1895+
@cls_meth_bodies.push("")1896+
@cls_meth_defaults.push("")1897+
@cls_attr_readers.push("")1898+
@cls_attr_writers.push("")1899+
@cls_cmeth_names.push("")1900+
@cls_cmeth_params.push("")1901+
@cls_cmeth_ptypes.push("")1902+
@cls_cmeth_returns.push("")1903+
@cls_cmeth_bodies.push("")1904+
@cls_meth_has_yield.push("")1905+
@needs_gc = 11906+
1907+
# Get field names from symbol args1908+
args_id = @nd_arguments[call_nid]1909+
field_names = "".split(",")1910+
if args_id >= 01911+
aids = get_args(args_id)1912+
k = 01913+
while k < aids.length1914+
fname = @nd_content[aids[k]]1915+
field_names.push(fname)1916+
# Add ivar1917+
iname = "@" + fname1918+
add_ivar(ci, iname, "int")1919+
# Add reader/writer1920+
append_attr_reader(ci, fname)1921+
append_attr_writer(ci, fname)1922+
k = k + 11923+
end1924+
end1925+
1926+
# Generate initialize method with params matching fields1927+
init_params = join_sep(field_names, ",")1928+
init_ptypes = ""1929+
k = 01930+
while k < field_names.length1931+
if k > 01932+
init_ptypes = init_ptypes + ","1933+
end1934+
init_ptypes = init_ptypes + "int"1935+
k = k + 11936+
end1937+
# For struct, we don't have a body node - the constructor is synthetic1938+
# We'll handle this specially in emit_constructor1939+
append_cls_meth(ci, "initialize", init_params, init_ptypes, "void", -1, "")1940+
# Mark yield info1941+
@cls_meth_has_yield[ci] = "0"1942+
1943+
# Store struct info for synthetic constructor generation1944+
# We'll use a special marker in the body id (-2 = synthetic struct)1945+
bodies = @cls_meth_bodies[ci].split(";")1946+
if bodies.length > 01947+
bodies[0] = "-2"1948+
@cls_meth_bodies[ci] = join_sep(bodies, ";")1949+
end1950+
end1951+
18511952
# ---- Yield detection ----18521953
def body_has_yield(nid)18531954
if nid < 0@@ -2409,6 +2510,22 @@
24092510
return scan_return_type_list(stmts)24102511
end24112512
end2513+
if @nd_type[nid] == "CaseMatchNode"2514+
conds = parse_id_list(@nd_conditions[nid])2515+
if conds.length > 02516+
inid = conds[0]2517+
if @nd_type[inid] == "InNode"2518+
ibody = @nd_body[inid]2519+
if ibody >= 02520+
is = get_stmts(ibody)2521+
rt = scan_return_type_list(is)2522+
if rt != ""2523+
return rt2524+
end2525+
end2526+
end2527+
end2528+
end24122529
""24132530
end24142531
@@ -2878,6 +2995,8 @@
28782995
emit_raw("static mrb_int sp_str_index(const char*s,const char*sub){const char*f=strstr(s,sub);if(!f)return -1;return(mrb_int)(f-s);}")28792996
emit_raw("static const char*sp_str_sub_range(const char*s,mrb_int start,mrb_int len){mrb_int sl=(mrb_int)strlen(s);if(start<0)start+=sl;if(start<0)start=0;if(start>=sl)return\"\";if(len<0)len=0;if(start+len>sl)len=sl-start;char*r=(char*)malloc(len+1);memcpy(r,s+start,len);r[len]=0;return r;}")28802997
emit_raw("static const char*sp_sprintf(const char*fmt,...){char*b=(char*)malloc(4096);va_list ap;va_start(ap,fmt);vsnprintf(b,4096,fmt,ap);va_end(ap);return b;}")2998+
emit_raw("static const char*sp_str_reverse(const char*s){size_t l=strlen(s);char*r=(char*)malloc(l+1);for(size_t i=0;i<l;i++)r[i]=s[l-1-i];r[l]=0;return r;}")2999+
emit_raw("static const char*sp_str_sub(const char*s,const char*pat,const char*rep){const char*f=strstr(s,pat);if(!f)return s;size_t pl=strlen(pat),rl=strlen(rep),sl=strlen(s);char*r=(char*)malloc(sl-pl+rl+1);size_t n=f-s;memcpy(r,s,n);memcpy(r+n,rep,rl);memcpy(r+n+rl,f+pl,sl-n-pl+1);return r;}")28813000
emit_raw("")28823001
end28833002
@@ -3351,6 +3470,19 @@
33513470
if init_idx < bodies.length33523471
bid = bodies[init_idx].to_i33533472
end3473+
if bid == -23474+
# Synthetic struct constructor3475+
all_params = @cls_meth_params[ci].split("|")3476+
pnames2 = []3477+
if init_idx < all_params.length3478+
pnames2 = all_params[init_idx].split(",")3479+
end3480+
sk = 03481+
while sk < pnames2.length3482+
emit_raw(" self->" + pnames2[sk] + " = lv_" + pnames2[sk] + ";")3483+
sk = sk + 13484+
end3485+
end33543486
if bid >= 033553487
@current_class_idx = ci33563488
all_params = @cls_meth_params[ci].split("|")@@ -3378,7 +3510,6 @@
33783510
while k < stmts.length33793511
sid = stmts[k]33803512
if @nd_type[sid] == "SuperNode"3381-
# Call parent initialize33823513
if @cls_parents[ci] != ""33833514
pi = find_class_idx(@cls_parents[ci])33843515
if pi >= 0@@ -4401,6 +4532,11 @@
44014532
return "(!" + compile_expr(recv) + ")"44024533
end44034534
if mname == "<<"4535+
lt = infer_type(recv)4536+
if lt == "string"4537+
@needs_string_helpers = 14538+
return "sp_str_concat(" + compile_expr(recv) + ", " + compile_arg0(nid) + ")"4539+
end44044540
return "(" + compile_expr(recv) + " << " + compile_arg0(nid) + ")"44054541
end44064542
if mname == ">>"@@ -4487,6 +4623,10 @@
44874623
if mname == "[]"44884624
return "sp_str_sub_range(" + rc + ", " + compile_arg0(nid) + ", 1)"44894625
end4626+
if mname == "reverse"4627+
@needs_string_helpers = 14628+
return "sp_str_reverse(" + rc + ")"4629+
end44904630
if mname == "freeze"44914631
return rc44924632
end@@ -5058,6 +5198,10 @@
50585198
compile_case_stmt(nid)50595199
return50605200
end5201+
if t == "CaseMatchNode"5202+
compile_case_match_stmt(nid)5203+
return5204+
end50615205
if t == "ReturnNode"50625206
compile_return_stmt(nid)50635207
return@@ -5287,6 +5431,95 @@
52875431
result52885432
end52895433
5434+
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 patterns5438+
pred = @nd_predicate[nid]5439+
pred_type = infer_type(pred)5440+
pred_val = compile_expr(pred)5441+
tmp = new_temp5442+
if pred_type == "string"5443+
emit(" const char *" + tmp + " = " + pred_val + ";")5444+
else5445+
if pred_type == "float"5446+
emit(" mrb_float " + tmp + " = " + pred_val + ";")5447+
else5448+
emit(" mrb_int " + tmp + " = " + pred_val + ";")5449+
end5450+
end5451+
conds = parse_id_list(@nd_conditions[nid])5452+
k = 05453+
while k < conds.length5454+
inid = conds[k]5455+
if @nd_type[inid] == "InNode"5456+
kw = "if"5457+
if k > 05458+
kw = "} else if"5459+
end5460+
pat = @nd_pattern[inid]5461+
cond_str = compile_in_pattern(pat, tmp, pred_type)5462+
emit(" " + kw + " (" + cond_str + ") {")5463+
@indent = @indent + 15464+
compile_stmts_body(@nd_body[inid])5465+
@indent = @indent - 15466+
end5467+
k = k + 15468+
end5469+
ec = @nd_else_clause[nid]5470+
if ec >= 05471+
emit(" } else {")5472+
@indent = @indent + 15473+
compile_stmts_body(@nd_body[ec])5474+
@indent = @indent - 15475+
end5476+
if conds.length > 05477+
emit(" }")5478+
end5479+
end5480+
5481+
def compile_in_pattern(pat_id, tmp, pred_type)5482+
if pat_id < 05483+
return "1"5484+
end5485+
pt = @nd_type[pat_id]5486+
if pt == "ConstantReadNode"5487+
cname = @nd_name[pat_id]5488+
if cname == "Integer"5489+
return "1" # For monomorphic int, always true5490+
end5491+
if cname == "String"5492+
return "1" # For monomorphic string, always true5493+
end5494+
if cname == "Float"5495+
return "1" # For monomorphic float, always true5496+
end5497+
return "0"5498+
end5499+
if pt == "IntegerNode"5500+
return tmp + " == " + @nd_value[pat_id].to_s5501+
end5502+
if pt == "StringNode"5503+
return "strcmp(" + tmp + ", " + c_string_literal(@nd_content[pat_id]) + ") == 0"5504+
end5505+
if pt == "NilNode"5506+
return tmp + " == 0"5507+
end5508+
if pt == "TrueNode"5509+
return tmp + " != 0"5510+
end5511+
if pt == "FalseNode"5512+
return tmp + " == 0"5513+
end5514+
if pt == "AlternationPatternNode"5515+
# true | false pattern5516+
left = compile_in_pattern(@nd_left[pat_id], tmp, pred_type)5517+
right = compile_in_pattern(@nd_right[pat_id], tmp, pred_type)5518+
return "(" + left + " || " + right + ")"5519+
end5520+
"1"5521+
end5522+
52905523
def compile_return_stmt(nid)52915524
args_id = @nd_arguments[nid]52925525
if args_id >= 0@@ -5348,6 +5581,27 @@
53485581
end53495582
end53505583
5584+
# << on string (mutating append)5585+
if mname == "<<"5586+
if recv >= 05587+
rt = infer_type(recv)5588+
if rt == "string"5589+
@needs_string_helpers = 15590+
rc = compile_expr(recv)5591+
val = compile_arg0(nid)5592+
# If receiver is a local variable, reassign5593+
if @nd_type[recv] == "LocalVariableReadNode"5594+
emit(" lv_" + @nd_name[recv] + " = sp_str_concat(lv_" + @nd_name[recv] + ", " + val + ");")5595+
return5596+
end5597+
if @nd_type[recv] == "InstanceVariableReadNode"5598+
emit(" self->" + sanitize_ivar(@nd_name[recv]) + " = sp_str_concat(self->" + sanitize_ivar(@nd_name[recv]) + ", " + val + ");")5599+
return5600+
end5601+
end5602+
end5603+
end5604+
53515605
# push53525606
if mname == "push"53535607
if recv >= 0@@ -7002,6 +7256,10 @@
70027256
end70037257
return70047258
end7259+
if @nd_type[last] == "CaseMatchNode"7260+
compile_case_match_return(last, return_type)7261+
return7262+
end70057263
# If last statement is a CallNode with a block, handle map/select as expressions70067264
if @nd_type[last] == "CallNode"70077265
if @nd_block[last] >= 0@@ -7076,6 +7334,50 @@
70767334
emit(" }")70777335
end70787336
7337+
def compile_case_match_return(nid, rt)7338+
pred = @nd_predicate[nid]7339+
pred_type = infer_type(pred)7340+
pred_val = compile_expr(pred)7341+
tmp = new_temp7342+
if pred_type == "string"7343+
emit(" const char *" + tmp + " = " + pred_val + ";")7344+
else7345+
if pred_type == "float"7346+
emit(" mrb_float " + tmp + " = " + pred_val + ";")7347+
else7348+
emit(" mrb_int " + tmp + " = " + pred_val + ";")7349+
end7350+
end7351+
conds = parse_id_list(@nd_conditions[nid])7352+
k = 07353+
while k < conds.length7354+
inid = conds[k]7355+
if @nd_type[inid] == "InNode"7356+
kw = "if"7357+
if k > 07358+
kw = "} else if"7359+
end7360+
pat = @nd_pattern[inid]7361+
cond_str = compile_in_pattern(pat, tmp, pred_type)7362+
emit(" " + kw + " (" + cond_str + ") {")7363+
@indent = @indent + 17364+
compile_body_return(@nd_body[inid], rt)7365+
@indent = @indent - 17366+
end7367+
k = k + 17368+
end7369+
ec = @nd_else_clause[nid]7370+
if ec >= 07371+
emit(" } else {")7372+
@indent = @indent + 17373+
compile_body_return(@nd_body[ec], rt)7374+
@indent = @indent - 17375+
end7376+
if conds.length > 07377+
emit(" }")7378+
end7379+
end7380+
70797381
def compile_case_return(nid, rt)70807382
pred = @nd_predicate[nid]70817383
if pred >= 0