Commit f7416c07

f7416c07b180Merged

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

Description

runtime,codegen: Kernel#Float() raises ArgumentError on invalid input

Float("abc") used to silently return 0.0 (strtod). Match MRI: raise ArgumentError (catchable via begin/rescue) when the input has no parseable digits or has trailing junk after the number. Whitespace flanking the number is fine.

Refs #888

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

Details

Commit
f7416c07b180
Parent
e7b577b37307

lib/sp_runtime.hmodifiedView file

@@ -334,6 +334,23 @@
334334 if (*endptr != '\0') sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Integer(): \"%s\"", s));
335335 return (mrb_int)v;
336336 }
337+
338+/* Kernel#Float() raises ArgumentError on unparseable input. strtod
339+ on its own would silently return 0.0 for "abc" or empty input;
340+ match MRI semantics by validating at-least-one-digit + no-trailing-
341+ junk. Whitespace flanking is fine. Issue #888. */
342+static mrb_float sp_str_to_f_strict(const char *s) {
343+ if (!s) sp_raise_cls("ArgumentError", "invalid value for Float(): nil");
344+ const char *p = s;
345+ while (isspace((unsigned char)*p)) p++;
346+ if (*p == '\0') sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Float(): \"%s\"", s));
347+ char *endptr;
348+ double v = strtod(p, &endptr);
349+ if (endptr == p) sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Float(): \"%s\"", s));
350+ while (isspace((unsigned char)*endptr)) endptr++;
351+ if (*endptr != '\0') sp_raise_cls("ArgumentError", sp_sprintf("invalid value for Float(): \"%s\"", s));
352+ return (mrb_float)v;
353+}
337354 typedef struct{mrb_int first;mrb_int last;}sp_Range;
338355 static sp_Range sp_range_new(mrb_int f,mrb_int l){sp_Range r;r.first=f;r.last=l;return r;}
339356 /* Inclusive-form `Range#include?`/`#cover?` on the boxed (SP_TAG_OBJ