Commit d5454297

d54542978b35Merged

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

Description

codegen: Comparable#clamp on string + Range arg form for Integer/String

Range-arg shape: extract literal lo/hi (`n.clamp(1..10)` / `s.clamp("a".."z")`). For Integer the exclusive-range form collapses to `hi - 1`. String had a 2-arg form already; the Range arg shape now compiles via the same strcmp clamp.

Fixes #962

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
d54542978b35
Parent
708fbb9df0bd

spinel_codegen.rbmodifiedView file

@@ -19713,6 +19713,15 @@
1971319713 args_id_clp = @nd_arguments[nid]
1971419714 if args_id_clp >= 0
1971519715 a_clp = get_args(args_id_clp)
19716+ # Range arg: extract literal lo/hi. Half-open forms not handled.
19717+ if a_clp.length == 1 && @nd_type[a_clp[0]] == "RangeNode"
19718+ rlo_sc = @nd_left[a_clp[0]]
19719+ rhi_sc = @nd_right[a_clp[0]]
19720+ if rlo_sc >= 0 && rhi_sc >= 0
19721+ tmp_clp_r = new_temp
19722+ return "({ const char *" + tmp_clp_r + " = " + rc + "; const char *_lo = " + compile_expr(rlo_sc) + "; const char *_hi = " + compile_expr(rhi_sc) + "; strcmp(" + tmp_clp_r + ", _lo) < 0 ? _lo : (strcmp(" + tmp_clp_r + ", _hi) > 0 ? _hi : " + tmp_clp_r + "); })"
19723+ end
19724+ end
1971619725 if a_clp.length >= 2
1971719726 lo = compile_expr(a_clp[0])
1971819727 hi = compile_expr(a_clp[1])
@@ -21053,6 +21062,19 @@
2105321062 if a.length >= 2
2105421063 return "sp_int_clamp(" + rc + ", " + compile_expr(a[0]) + ", " + compile_expr(a[1]) + ")"
2105521064 end
21065+ # Range arg: `n.clamp(lo..hi)` — extract literal range bounds.
21066+ # `..hi` / `lo..` half-open forms aren't handled here.
21067+ if a.length == 1 && @nd_type[a[0]] == "RangeNode"
21068+ rlo = @nd_left[a[0]]
21069+ rhi = @nd_right[a[0]]
21070+ if rlo >= 0 && rhi >= 0
21071+ hi_expr = compile_expr(rhi)
21072+ if range_excl_end(a[0]) == 1
21073+ hi_expr = "(" + hi_expr + ") - 1"
21074+ end
21075+ return "sp_int_clamp(" + rc + ", " + compile_expr(rlo) + ", " + hi_expr + ")"
21076+ end
21077+ end
2105621078 end
2105721079 end
2105821080 if mname == "frozen?"