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" and mname == "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 end
3000+ # Kernel coercion methods: Integer(x) / Float(x) return their class.
3001+ # Only treat as a Kernel call when there's no explicit receiver — with
3002+ # 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+ end
3007+ if recv < 0 && mname == "Float"
3008+ return "float"
3009+ end
30003010 # Float#ceil(n)/floor(n)/round(n)/truncate(n) with n given return
30013011 # Float; zero-arg / Integer#ceil etc. return Integer. (truncate's arm
30023012 # 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 end
2069620706 if mname == "Float"
20707+ args_id = @nd_arguments[nid]
20708+ if args_id >= 0
20709+ arg_ids = get_args(args_id)
20710+ if arg_ids.length > 0
20711+ 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+ end
20716+ if at == "int"
20717+ return "(mrb_float)(" + compile_expr(a0) + ")"
20718+ end
20719+ if at == "float"
20720+ return compile_expr(a0)
20721+ end
20722+ if at == "poly"
20723+ # Polymorphic — string / int / float branches resolve at
20724+ # runtime via sp_poly_to_f, which already handles each tag.
20725+ @needs_rb_value = 1
20726+ return "sp_poly_to_f(" + compile_expr(a0) + ")"
20727+ end
20728+ end
20729+ end
2069720730 return "(mrb_float)(" + compile_arg0(nid) + ")"
2069820731 end
2069920732 if mname == "proc"