edit icon indicating copy to clipboard operation
edit copied to clipboard

JSON parser rejects 0e400 because parse_f64_approx returns NaN for a zero mantissa with a large exponent

Open sebxt opened this issue 1 month ago • 2 comments

What happens

edit::float::parse_f64_approx returns NaN for a zero written with a large positive exponent, for example 0e400 or 0.0e999. f64::from_str returns 0.0 for the same input, and the module doc says the parser accepts the same grammar and differs by at most a few ULP.

Because json::Parser::parse_number rejects non finite numbers, the JSON value 0e400 (valid JSON, value zero) is reported as Invalid JSON when it appears in a settings file.

Separately, an exponent near i32::MAX (for example 1e2147483645) panics with attempt to add with overflow in debug and test builds.

What should happen

0e400 parses to 0.0 (and -0e400 to -0.0), and very large exponents return infinity or zero without panicking, matching f64::from_str.

Repro

use edit::float::parse_f64_approx;

assert_eq!("0e400".parse::<f64>().unwrap(), 0.0);
assert_eq!(parse_f64_approx(b"0e400"), Some(0.0)); // fails: Some(NaN)

let arena = edit::arena::scratch_arena(None);
edit::json::parse(&arena, "0e400").unwrap(); // Err: 1:6: Invalid JSON

parse_f64_approx(b"1e2147483645"); // debug build: attempt to add with overflow

Root cause

In crates/edit/src/float.rs the mantissa is scaled by 10f64.powi(exponent) whenever exponent != 0. For a zero mantissa and an exponent above about 308, powi returns infinity and 0.0 * inf is NaN.

The exponent is accumulated with saturating arithmetic, but the table lookup then computes exponent + 3 with a plain add, which overflows when the exponent saturated at i32::MAX.

sebxt avatar Oct 18 '26 01:10 sebxt

Huh. I am unclear on where we use float parsing in the settings file for Edit.

DHowett avatar Oct 19 '26 15:10 DHowett

Fair point, the settings code never reads a number. The only link is that Settings loads the whole file through json::parse (settings.rs line 60), and every number token in the file goes through parse_f64_approx. So a settings.json containing 0e400 anywhere fails to load as a whole, even in a key Edit ignores. That is an unlikely input in practice. The more concrete part is the overflow panic on a huge exponent in debug builds. Happy to narrow the PR to that, or close it if neither is worth the change.

sebxt avatar Oct 19 '26 16:10 sebxt