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')