From 76984f884e5e959074de42953488a79bd22a9965 Mon Sep 17 00:00:00 2001 From: zimri-leisher Date: Tue, 8 Sep 2026 10:24:55 -0400 Subject: [PATCH] Report a diagnostic instead of crashing when a non-finite float constant is cast to an integer (#229) Co-Authored-By: Claude Opus 5 (1M context) --- src/fpy/semantics.py | 3 ++- test/fpy/test_arithmetic.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/fpy/semantics.py b/src/fpy/semantics.py index c8f19a6..e8a7c97 100644 --- a/src/fpy/semantics.py +++ b/src/fpy/semantics.py @@ -2421,7 +2421,8 @@ def const_convert_type( return FpyValue(to_type, raw_val) assert False, (from_val, from_type, to_type) - except (ValueError, struct.error) as e: + except (ValueError, OverflowError, struct.error) as e: + # OverflowError is int(inf); ValueError is int(nan) state.err(f"For type {from_type.display_name}: {e}", node) return None diff --git a/test/fpy/test_arithmetic.py b/test/fpy/test_arithmetic.py index d3c176b..e534328 100644 --- a/test/fpy/test_arithmetic.py +++ b/test/fpy/test_arithmetic.py @@ -56,6 +56,34 @@ def test_const_complex_pow(self, fprime_test_api): assert_compile_failure(fprime_test_api, seq) + def test_const_infinity_to_int(self, fprime_test_api): + """An infinite float constant cast to an integer type is a compile + error, not an uncaught OverflowError.""" + seq = """ +x: I64 = I64(F64(1e308) * F64(10.0)) +exit(0) +""" + + assert_compile_failure(fprime_test_api, seq, match="infinity") + + def test_const_negative_infinity_to_int(self, fprime_test_api): + """The same holds for a negative infinity and an unsigned target.""" + seq = """ +x: U8 = U8(F64(-1e308) + F64(-1e308)) +exit(0) +""" + + assert_compile_failure(fprime_test_api, seq, match="infinity") + + def test_const_nan_to_int(self, fprime_test_api): + """The NaN counterpart reports a diagnostic too.""" + seq = """ +x: I64 = I64(F64(1e308) * F64(10.0) - F64(1e308) * F64(10.0)) +exit(0) +""" + + assert_compile_failure(fprime_test_api, seq, match="NaN") + def test_very_large_const_pow(self, fprime_test_api): seq = """ 10.0 ** 1000