Commit fd048815
fd0488153408Merged
Ryan Seys <[email protected]> · 6 months ago · 3 files · ~3 modified
Description
fix(codegen): Float() coerces strings + type-infer as float
Float("3.14") previously emitted (mrb_float)("3.14") — a cast
that the C compiler accepted but produced garbage at runtime
(reinterpreting the string pointer as a double). Adds string
coercion via strtod, mirroring the existing Integer("123") →
strtoll handling.
Two arms:
- infer_call_type: when there's no receiver,
mname == "Integer"→ "int" andmname == "Float"→ "float". Without these, both would fall through to the user-class lookup and miss bool / arithmetic flow at use sites. - compile_kernel_call: Float() peeks at arg type. string/argv →
(mrb_float)strtod(s, NULL); int → cast to mrb_float explicitly so a literal int doesn't go through the pointer-cast fallback. Default arm still handles float / poly.
Test: extends test/float.rb with a "Kernel#Float coerces ..." section covering string ("3.14", "0", "-2.5", "1e2"), int (1, 42), and float (2.71) inputs.
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- fd0488153408
- Parent
- 8ff9aa915a30
spinel_codegen.rbmodifiedView file
@@ -2997,6 +2997,16 @@
29972997
if mname == "to_f"29982998
return "float"29992999
end3000+
# Kernel coercion methods: Integer(x) / Float(x) return their class.3001+
# Only treat as a Kernel call when there's no explicit receiver — with3002+
# a receiver, "Integer" / "Float" would be ConstantReadNode lookups,3003+
# not method calls, and wouldn't reach this name dispatch anyway.3004+
if recv < 0 && mname == "Integer"3005+
return "int"3006+
end3007+
if recv < 0 && mname == "Float"3008+
return "float"3009+
end30003010
# Float#ceil(n)/floor(n)/round(n)/truncate(n) with n given return30013011
# Float; zero-arg / Integer#ceil etc. return Integer. (truncate's arm30023012
# used to live next to nan?/infinite? — folded in here for one place@@ -20694,6 +20704,29 @@
2069420704
return "(mrb_int)(" + compile_arg0(nid) + ")"2069520705
end2069620706
if mname == "Float"20707+
args_id = @nd_arguments[nid]20708+
if args_id >= 020709+
arg_ids = get_args(args_id)20710+
if arg_ids.length > 020711+
a0 = arg_ids[0]20712+
at = infer_type(a0)20713+
if at == "string" || at == "argv"20714+
return "(mrb_float)strtod(" + compile_expr(a0) + ", NULL)"20715+
end20716+
if at == "int"20717+
return "(mrb_float)(" + compile_expr(a0) + ")"20718+
end20719+
if at == "float"20720+
return compile_expr(a0)20721+
end20722+
if at == "poly"20723+
# Polymorphic — string / int / float branches resolve at20724+
# runtime via sp_poly_to_f, which already handles each tag.20725+
@needs_rb_value = 120726+
return "sp_poly_to_f(" + compile_expr(a0) + ")"20727+
end20728+
end20729+
end2069720730
return "(mrb_float)(" + compile_arg0(nid) + ")"2069820731
end2069920732
if mname == "proc"test/float.rbmodifiedView file
Loading diff…
test/float.rb.expectedmodifiedView file
Loading diff…