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 end
792792 return "void"
793793 end
794+ if t == "CaseMatchNode"
795+ # Infer from first in branch
796+ conds = parse_id_list(@nd_conditions[nid])
797+ if conds.length > 0
798+ inid = conds[0]
799+ if @nd_type[inid] == "InNode"
800+ ibody = @nd_body[inid]
801+ if ibody >= 0
802+ is = get_stmts(ibody)
803+ if is.length > 0
804+ return infer_type(is[is.length - 1])
805+ end
806+ end
807+ end
808+ end
809+ return "int"
810+ end
794811 if t == "CaseNode"
795812 # Infer from first when branch
796813 conds = parse_id_list(@nd_conditions[nid])
@@ -1838,8 +1855,24 @@
18381855 end
18391856
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 >= 0
1861+ if @nd_type[expr_id] == "CallNode"
1862+ if @nd_name[expr_id] == "new"
1863+ sr = @nd_receiver[expr_id]
1864+ if sr >= 0
1865+ if @nd_type[sr] == "ConstantReadNode"
1866+ if @nd_name[sr] == "Struct"
1867+ collect_struct_class(@nd_name[nid], expr_id)
1868+ return
1869+ end
1870+ end
1871+ end
1872+ end
1873+ end
1874+ end
1875+ @const_names.push(@nd_name[nid])
18431876 ct = "int"
18441877 if expr_id >= 0
18451878 ct = infer_type(expr_id)
@@ -1848,6 +1881,74 @@
18481881 @const_expr_ids.push(expr_id)
18491882 end
18501883
1884+ def collect_struct_class(cname, call_nid)
1885+ # Generate a synthetic class from Struct.new(:field1, :field2, ...)
1886+ ci = @cls_names.length
1887+ @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 = 1
1906+
1907+ # Get field names from symbol args
1908+ args_id = @nd_arguments[call_nid]
1909+ field_names = "".split(",")
1910+ if args_id >= 0
1911+ aids = get_args(args_id)
1912+ k = 0
1913+ while k < aids.length
1914+ fname = @nd_content[aids[k]]
1915+ field_names.push(fname)
1916+ # Add ivar
1917+ iname = "@" + fname
1918+ add_ivar(ci, iname, "int")
1919+ # Add reader/writer
1920+ append_attr_reader(ci, fname)
1921+ append_attr_writer(ci, fname)
1922+ k = k + 1
1923+ end
1924+ end
1925+
1926+ # Generate initialize method with params matching fields
1927+ init_params = join_sep(field_names, ",")
1928+ init_ptypes = ""
1929+ k = 0
1930+ while k < field_names.length
1931+ if k > 0
1932+ init_ptypes = init_ptypes + ","
1933+ end
1934+ init_ptypes = init_ptypes + "int"
1935+ k = k + 1
1936+ end
1937+ # For struct, we don't have a body node - the constructor is synthetic
1938+ # We'll handle this specially in emit_constructor
1939+ append_cls_meth(ci, "initialize", init_params, init_ptypes, "void", -1, "")
1940+ # Mark yield info
1941+ @cls_meth_has_yield[ci] = "0"
1942+
1943+ # Store struct info for synthetic constructor generation
1944+ # We'll use a special marker in the body id (-2 = synthetic struct)
1945+ bodies = @cls_meth_bodies[ci].split(";")
1946+ if bodies.length > 0
1947+ bodies[0] = "-2"
1948+ @cls_meth_bodies[ci] = join_sep(bodies, ";")
1949+ end
1950+ end
1951+
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 end
24112512 end
2513+ if @nd_type[nid] == "CaseMatchNode"
2514+ conds = parse_id_list(@nd_conditions[nid])
2515+ if conds.length > 0
2516+ inid = conds[0]
2517+ if @nd_type[inid] == "InNode"
2518+ ibody = @nd_body[inid]
2519+ if ibody >= 0
2520+ is = get_stmts(ibody)
2521+ rt = scan_return_type_list(is)
2522+ if rt != ""
2523+ return rt
2524+ end
2525+ end
2526+ end
2527+ end
2528+ end
24122529 ""
24132530 end
24142531
@@ -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 end
28833002
@@ -3351,6 +3470,19 @@
33513470 if init_idx < bodies.length
33523471 bid = bodies[init_idx].to_i
33533472 end
3473+ if bid == -2
3474+ # Synthetic struct constructor
3475+ all_params = @cls_meth_params[ci].split("|")
3476+ pnames2 = []
3477+ if init_idx < all_params.length
3478+ pnames2 = all_params[init_idx].split(",")
3479+ end
3480+ sk = 0
3481+ while sk < pnames2.length
3482+ emit_raw(" self->" + pnames2[sk] + " = lv_" + pnames2[sk] + ";")
3483+ sk = sk + 1
3484+ end
3485+ end
33543486 if bid >= 0
33553487 @current_class_idx = ci
33563488 all_params = @cls_meth_params[ci].split("|")
@@ -3378,7 +3510,6 @@
33783510 while k < stmts.length
33793511 sid = stmts[k]
33803512 if @nd_type[sid] == "SuperNode"
3381- # Call parent initialize
33823513 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 end
44034534 if mname == "<<"
4535+ lt = infer_type(recv)
4536+ if lt == "string"
4537+ @needs_string_helpers = 1
4538+ return "sp_str_concat(" + compile_expr(recv) + ", " + compile_arg0(nid) + ")"
4539+ end
44044540 return "(" + compile_expr(recv) + " << " + compile_arg0(nid) + ")"
44054541 end
44064542 if mname == ">>"
@@ -4487,6 +4623,10 @@
44874623 if mname == "[]"
44884624 return "sp_str_sub_range(" + rc + ", " + compile_arg0(nid) + ", 1)"
44894625 end
4626+ if mname == "reverse"
4627+ @needs_string_helpers = 1
4628+ return "sp_str_reverse(" + rc + ")"
4629+ end
44904630 if mname == "freeze"
44914631 return rc
44924632 end
@@ -5058,6 +5198,10 @@
50585198 compile_case_stmt(nid)
50595199 return
50605200 end
5201+ if t == "CaseMatchNode"
5202+ compile_case_match_stmt(nid)
5203+ return
5204+ end
50615205 if t == "ReturnNode"
50625206 compile_return_stmt(nid)
50635207 return
@@ -5287,6 +5431,95 @@
52875431 result
52885432 end
52895433
5434+ 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
5438+ pred = @nd_predicate[nid]
5439+ pred_type = infer_type(pred)
5440+ pred_val = compile_expr(pred)
5441+ tmp = new_temp
5442+ if pred_type == "string"
5443+ emit(" const char *" + tmp + " = " + pred_val + ";")
5444+ else
5445+ if pred_type == "float"
5446+ emit(" mrb_float " + tmp + " = " + pred_val + ";")
5447+ else
5448+ emit(" mrb_int " + tmp + " = " + pred_val + ";")
5449+ end
5450+ end
5451+ conds = parse_id_list(@nd_conditions[nid])
5452+ k = 0
5453+ while k < conds.length
5454+ inid = conds[k]
5455+ if @nd_type[inid] == "InNode"
5456+ kw = "if"
5457+ if k > 0
5458+ kw = "} else if"
5459+ end
5460+ pat = @nd_pattern[inid]
5461+ cond_str = compile_in_pattern(pat, tmp, pred_type)
5462+ emit(" " + kw + " (" + cond_str + ") {")
5463+ @indent = @indent + 1
5464+ compile_stmts_body(@nd_body[inid])
5465+ @indent = @indent - 1
5466+ end
5467+ k = k + 1
5468+ end
5469+ ec = @nd_else_clause[nid]
5470+ if ec >= 0
5471+ emit(" } else {")
5472+ @indent = @indent + 1
5473+ compile_stmts_body(@nd_body[ec])
5474+ @indent = @indent - 1
5475+ end
5476+ if conds.length > 0
5477+ emit(" }")
5478+ end
5479+ end
5480+
5481+ def compile_in_pattern(pat_id, tmp, pred_type)
5482+ if pat_id < 0
5483+ return "1"
5484+ end
5485+ 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 true
5490+ end
5491+ if cname == "String"
5492+ return "1" # For monomorphic string, always true
5493+ end
5494+ if cname == "Float"
5495+ return "1" # For monomorphic float, always true
5496+ end
5497+ return "0"
5498+ end
5499+ if pt == "IntegerNode"
5500+ return tmp + " == " + @nd_value[pat_id].to_s
5501+ end
5502+ if pt == "StringNode"
5503+ return "strcmp(" + tmp + ", " + c_string_literal(@nd_content[pat_id]) + ") == 0"
5504+ end
5505+ if pt == "NilNode"
5506+ return tmp + " == 0"
5507+ end
5508+ if pt == "TrueNode"
5509+ return tmp + " != 0"
5510+ end
5511+ if pt == "FalseNode"
5512+ return tmp + " == 0"
5513+ end
5514+ if pt == "AlternationPatternNode"
5515+ # true | false pattern
5516+ 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+ end
5520+ "1"
5521+ end
5522+
52905523 def compile_return_stmt(nid)
52915524 args_id = @nd_arguments[nid]
52925525 if args_id >= 0
@@ -5348,6 +5581,27 @@
53485581 end
53495582 end
53505583
5584+ # << on string (mutating append)
5585+ if mname == "<<"
5586+ if recv >= 0
5587+ rt = infer_type(recv)
5588+ if rt == "string"
5589+ @needs_string_helpers = 1
5590+ rc = compile_expr(recv)
5591+ val = compile_arg0(nid)
5592+ # If receiver is a local variable, reassign
5593+ if @nd_type[recv] == "LocalVariableReadNode"
5594+ emit(" lv_" + @nd_name[recv] + " = sp_str_concat(lv_" + @nd_name[recv] + ", " + val + ");")
5595+ return
5596+ end
5597+ if @nd_type[recv] == "InstanceVariableReadNode"
5598+ emit(" self->" + sanitize_ivar(@nd_name[recv]) + " = sp_str_concat(self->" + sanitize_ivar(@nd_name[recv]) + ", " + val + ");")
5599+ return
5600+ end
5601+ end
5602+ end
5603+ end
5604+
53515605 # push
53525606 if mname == "push"
53535607 if recv >= 0
@@ -7002,6 +7256,10 @@
70027256 end
70037257 return
70047258 end
7259+ if @nd_type[last] == "CaseMatchNode"
7260+ compile_case_match_return(last, return_type)
7261+ return
7262+ end
70057263 # If last statement is a CallNode with a block, handle map/select as expressions
70067264 if @nd_type[last] == "CallNode"
70077265 if @nd_block[last] >= 0
@@ -7076,6 +7334,50 @@
70767334 emit(" }")
70777335 end
70787336
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_temp
7342+ if pred_type == "string"
7343+ emit(" const char *" + tmp + " = " + pred_val + ";")
7344+ else
7345+ if pred_type == "float"
7346+ emit(" mrb_float " + tmp + " = " + pred_val + ";")
7347+ else
7348+ emit(" mrb_int " + tmp + " = " + pred_val + ";")
7349+ end
7350+ end
7351+ conds = parse_id_list(@nd_conditions[nid])
7352+ k = 0
7353+ while k < conds.length
7354+ inid = conds[k]
7355+ if @nd_type[inid] == "InNode"
7356+ kw = "if"
7357+ if k > 0
7358+ kw = "} else if"
7359+ end
7360+ pat = @nd_pattern[inid]
7361+ cond_str = compile_in_pattern(pat, tmp, pred_type)
7362+ emit(" " + kw + " (" + cond_str + ") {")
7363+ @indent = @indent + 1
7364+ compile_body_return(@nd_body[inid], rt)
7365+ @indent = @indent - 1
7366+ end
7367+ k = k + 1
7368+ end
7369+ ec = @nd_else_clause[nid]
7370+ if ec >= 0
7371+ emit(" } else {")
7372+ @indent = @indent + 1
7373+ compile_body_return(@nd_body[ec], rt)
7374+ @indent = @indent - 1
7375+ end
7376+ if conds.length > 0
7377+ emit(" }")
7378+ end
7379+ end
7380+
70797381 def compile_case_return(nid, rt)
70807382 pred = @nd_predicate[nid]
70817383 if pred >= 0