diff --git a/src/pyfloyd/datafile/api.py b/src/pyfloyd/datafile/api.py index 0430494..17d9778 100644 --- a/src/pyfloyd/datafile/api.py +++ b/src/pyfloyd/datafile/api.py @@ -55,7 +55,25 @@ class DatafileParseError(DatafileError): quote_tokens = ('```', '"""', "'''", '`', '"', "'") -_bare_word_re = re.compile(r'^[^\\\s\[\]\(\)\{\}:\'"`]+$') +# A word that the datafile grammar would tokenize as a bareword, i.e., a +# non-empty run of characters that are neither punctuation nor whitespace +# (see the `punct` rule in grammars/datafile.g) and that is not exactly +# `true`, `false`, or `null` and does not begin with a number. +_bare_word_re = re.compile( + r"^(?!(?:true|false|null)$)(?![+-]?[0-9])" + r"[^\\/#'\"`\[\](){}:=,\s]+$" +) + +# A word that the datafile grammar would tokenize as a numword (a number +# followed by one or more bareword characters), mirroring the `number` +# rule in grammars/datafile.g. +_numword_re = re.compile( + r"[-+]?(?:0b[01](?:_?[01])*|0o[0-7](?:_?[0-7])*" + r"|0x[0-9a-fA-F](?:_?[0-9a-fA-F])*" + r"|(?:0|[1-9](?:_?[0-9])*)(?:\.[0-9]?(?:_?[0-9])*)?" + r"(?:[eE][+-]?[0-9]?(?:_?[0-9])*)?)" + r"[^\\/#'\"`\[\](){}:=,\s]+" +) _long_str_re = re.compile(r"^l'=+'") @@ -696,6 +714,7 @@ def __init__( separators: Optional[Tuple[str, str]] = None, default: Optional[Callable[[Any], Any]] = None, sort_keys: bool = False, + allow_numwords: bool = False, **kw, ): """Provides a class that may be overridden to customize the behavior @@ -710,6 +729,7 @@ def __init__( self.item_separator, self.kv_separator = separators self.default_fn = default or _raise_type_error self.sort_keys = sort_keys + self.allow_numwords = allow_numwords def default(self, obj: Any) -> Any: """Provides a last-ditch option to encode a value that the encoder @@ -753,7 +773,7 @@ def encode( return s if as_key: - raise TypeError(f'Invalid key f{obj}') + raise TypeError(f'Invalid key: {obj!r}') return self._encode_non_basic_type(obj, seen, level) def _encode_basic_type(self, obj: Any, *, as_key: bool) -> Optional[str]: @@ -790,9 +810,10 @@ def _encode_float(self, obj: float, *, as_key: bool) -> str: return f'"{repr(obj)}"' if as_key else repr(obj) def _encode_str(self, obj: str, *, as_key: bool) -> str: - if as_key: - return obj - return encode_string(obj, self.ensure_ascii) + del as_key + return encode_string( + obj, self.ensure_ascii, allow_numwords=self.allow_numwords + ) def _encode_non_basic_type(self, obj, seen: Set, level: int) -> str: # Basic types can't be recursive so we only check for circularity @@ -927,10 +948,12 @@ def _spacers(self, level: int, oneline: bool) -> Tuple[str, str]: def encode_string( - obj: str, ensure_ascii: bool = True, escape_newlines=False + obj: str, ensure_ascii: bool = True, escape_newlines=False, + allow_numwords: bool = False, ) -> str: - m = _bare_word_re.match(obj) - if m: + if allow_numwords and _numword_re.fullmatch(obj): + return obj + if _bare_word_re.match(obj): return obj return encode_quoted_string(obj, ensure_ascii, escape_newlines) @@ -959,6 +982,10 @@ def encode_quoted_string( continue ch = s[i] + if ch == '\\': + ret.append('\\\\') + i += 1 + continue o = ord(ch) if o < 32: ret.append(escape_char(ch)) diff --git a/tests/datafile/encode_test.py b/tests/datafile/encode_test.py index 8a825ca..1e2955a 100644 --- a/tests/datafile/encode_test.py +++ b/tests/datafile/encode_test.py @@ -63,6 +63,75 @@ def test_str(self): def test_str_quote_escapes(self): self.check('\'"`', "''''\"`'''") + def test_str_backslash_is_escaped(self): + # A backslash must be escaped on the way out, or the output + # re-parses to a different string (e.g., 'a\\b' would come back + # as 'a\x08b' once \b is interpreted as an escape). + self.check('a\\b', "'a\\\\b'") + self.check('\\1', "'\\\\1'") + + def test_barewords_that_reparse_as_other_types_are_quoted(self): + # The datafile spec only allows a string to be written unquoted if + # it cannot be interpreted as a boolean, null, or a number. + self.check('true', "'true'") + self.check('false', "'false'") + self.check('null', "'null'") + self.check('2', "'2'") + self.check('-3', "'-3'") + self.check('2.5', "'2.5'") + self.check('2.5e', "'2.5e'") + # A numword stays unquoted when numwords are allowed ... + self.check('123foo', '123foo', allow_numwords=True) + # ... but is quoted otherwise, so that it still parses back to the + # same string. + self.check('123foo', "'123foo'") + + def test_barewords_with_punctuation_are_quoted(self): + # ',' separates values, '#' starts a comment, and '/', '=', quotes, + # brackets and so on are punctuation per the grammar's `punct` rule, + # so words containing them cannot be written unquoted. + self.check('1,2', "'1,2'") + self.check('#c', "'#c'") + self.check('a=b', "'a=b'") + self.check('a/b', "'a/b'") + self.check('a b', "'a b'") + + def test_keys_that_are_not_barewords_are_quoted(self): + self.check({' b': 1}, "{' b': 1}") + self.check({'a b': 1}, "{'a b': 1}") + self.check({'"q"': 1}, "{'\"q\"': 1}") + self.check({'1': 1}, "{'1': 1}") + self.check({'': 1}, "{'': 1}") + self.check({'true': 1}, "{'true': 1}") + self.check({'#c': 1}, "{'#c': 1}") + + def test_roundtrip(self): + # Anything dumps() emits should load back to the same object. + objs = [ + 'foo', 'true', 'false', 'null', '2', '2.5', '-3', '2.5e', + '1,2', '#c', 'a b', ' b', 'v ', 'a=b', 'a/b', 'a\\b', '\\1', + 'a"b', "'x'", '+', '-abc', '.5', '1abc', + {' b': 1}, {'a b': 1}, {'"q"': 1}, {'a"b': 1}, {'1': 1}, + {'': 1}, {'true': 1}, {'null': 1}, {'#c': 1}, {'1,2': 1}, + {'a=b': 1}, {'a/b': 1}, {'a\\b': 1}, + {'k': ['true', '2', 'a\\b']}, + [{' b': 1}, {"'q'": [1, 'null']}], + ] + for obj in objs: + s = datafile.dumps(obj) + self.assertEqual(obj, datafile.loads(s), msg=f'{obj!r} -> {s!r}') + + for obj in ('123foo', '2.5ex'): + s = datafile.dumps(obj, allow_numwords=True) + self.assertEqual( + obj, datafile.loads(s, allow_numwords=True), msg=s + ) + + def test_invalid_key_error_message(self): + with self.assertRaises(TypeError) as cm: + datafile.dumps({(1, 2): 3}) + self.assertEqual(str(cm.exception), 'Invalid key: (1, 2)') + if __name__ == '__main__': # pragma: no cover unittest.main()