From 42704765ffda6367425270cc382820bbbfb87f41 Mon Sep 17 00:00:00 2001 From: Rahul Ranjan Date: Fri, 13 Nov 2026 04:10:53 +0000 Subject: [PATCH] fix: report invalid number tokens as DatafileError instead of ValueError The datafile grammar's 'exp' rule allows an exponent marker with no digits (e.g. '2.5e', '2e', '1e+'), so those strings tokenize as number tokens. parse_number() then calls float() on the token text and the raw ValueError escapes loads(), violating the documented contract that invalid documents raise DatafileError (or DatafileParseError). Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com> --- src/pyfloyd/datafile/api.py | 5 ++++- tests/datafile/decode_test.py | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/pyfloyd/datafile/api.py b/src/pyfloyd/datafile/api.py index 0430494..f12af4c 100644 --- a/src/pyfloyd/datafile/api.py +++ b/src/pyfloyd/datafile/api.py @@ -393,7 +393,10 @@ def parse_number(self, val: str) -> Any: if s.startswith('0o'): return int(s, base=8) if '.' in s or 'e' in s or 'E' in s: - return float(s) + try: + return float(s) + except ValueError: + raise DatafileError(f'Invalid number "{val}"') from None return int(s) def parse_numword(self, val: str, as_key: bool) -> Any: diff --git a/tests/datafile/decode_test.py b/tests/datafile/decode_test.py index ef12a75..b765e67 100644 --- a/tests/datafile/decode_test.py +++ b/tests/datafile/decode_test.py @@ -185,6 +185,16 @@ def test_long_str(self): self.check("L'=='foo'=='", 'foo') self.check("L'=='f'='o'=='", "f'='o") + def test_invalid_number(self): + # The grammar's `exp` rule allows an exponent with no digits (e.g., + # "2.5e"), so a number token can reach the float() conversion and + # fail there. That should be reported as a DatafileError, like any + # other invalid document, not escape as a raw ValueError. + for s in ('2.5e', '2e', '1e+', '2.5e+', '[2.5e]', '{k: 2.5e}'): + with self.assertRaises(datafile.DatafileError) as cm: + datafile.loads(s) + self.assertIn('Invalid number', str(cm.exception)) + def test_bare_word(self): self.check('foo', 'foo') self.check('@foo', '@foo')