parse-toml 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
parse_toml/__init__.py ADDED
@@ -0,0 +1,14 @@
1
+ """A bounded, source-aware TOML 1.0 parser with no runtime dependencies."""
2
+
3
+ from .nodes import Document, SourceSpan, TomlValue
4
+ from .parser import ParseError, ParseOptions, loads, parse
5
+
6
+ __all__ = [
7
+ "Document",
8
+ "ParseError",
9
+ "ParseOptions",
10
+ "SourceSpan",
11
+ "TomlValue",
12
+ "loads",
13
+ "parse",
14
+ ]
parse_toml/nodes.py ADDED
@@ -0,0 +1,42 @@
1
+ """Public result types for TOML parsing."""
2
+
3
+ from dataclasses import dataclass
4
+ from datetime import date, datetime, time
5
+ from typing import TypeAlias
6
+
7
+ TomlValue: TypeAlias = (
8
+ str
9
+ | int
10
+ | float
11
+ | bool
12
+ | date
13
+ | datetime
14
+ | time
15
+ | list["TomlValue"]
16
+ | dict[str, "TomlValue"]
17
+ )
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class SourceSpan:
22
+ """A half-open range in the original source, measured in code points."""
23
+
24
+ start: int
25
+ end: int
26
+ line: int
27
+ column: int
28
+ end_line: int
29
+ end_column: int
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Document:
34
+ """Parsed value together with the exact source that produced it."""
35
+
36
+ value: dict[str, TomlValue]
37
+ source: str
38
+ span: SourceSpan
39
+
40
+ def to_toml(self) -> str:
41
+ """Return the original source without normalizing or re-serializing it."""
42
+ return self.source
parse_toml/parser.py ADDED
@@ -0,0 +1,237 @@
1
+ """Bounded TOML 1.0 parsing backed by Python's standard-library tomllib."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from dataclasses import dataclass
7
+ from typing import NoReturn
8
+
9
+ from .nodes import Document, SourceSpan, TomlValue
10
+
11
+
12
+ class ParseError(ValueError):
13
+ """Invalid TOML or an exceeded resource limit with a source location."""
14
+
15
+ def __init__(
16
+ self,
17
+ message: str,
18
+ line: int,
19
+ column: int,
20
+ code: str = "invalid-toml",
21
+ position: int | None = None,
22
+ ) -> None:
23
+ self.message = message
24
+ self.line = line
25
+ self.column = column
26
+ self.code = code
27
+ self.position = position
28
+ super().__init__(f"{message} at line {line}, column {column}")
29
+
30
+
31
+ @dataclass(frozen=True, slots=True)
32
+ class ParseOptions:
33
+ """Resource limits applied to one parse operation."""
34
+
35
+ max_characters: int = 1_000_000
36
+ max_nodes: int = 100_000
37
+ max_depth: int = 64
38
+
39
+ def __post_init__(self) -> None:
40
+ if self.max_characters < 1:
41
+ raise ValueError("max_characters must be at least 1")
42
+ if self.max_nodes < 1:
43
+ raise ValueError("max_nodes must be at least 1")
44
+ if self.max_depth < 1:
45
+ raise ValueError("max_depth must be at least 1")
46
+
47
+
48
+ def parse(source: str, *, options: ParseOptions = ParseOptions()) -> Document:
49
+ """Parse TOML 1.0 *source* and retain it exactly on the returned document."""
50
+ if not isinstance(source, str):
51
+ raise TypeError("source must be str")
52
+ if len(source) > options.max_characters:
53
+ _raise_limit(
54
+ source,
55
+ 0,
56
+ f"source exceeds the {options.max_characters}-character limit",
57
+ )
58
+
59
+ _check_container_depth(source, options.max_depth)
60
+ try:
61
+ value = tomllib.loads(source)
62
+ except tomllib.TOMLDecodeError as error:
63
+ position = getattr(error, "pos", None)
64
+ line = getattr(error, "lineno", None)
65
+ column = getattr(error, "colno", None)
66
+ if position is None:
67
+ position = 0
68
+ if line is None or column is None:
69
+ line, column = _line_column(source, position)
70
+ message = str(error)
71
+ if message.endswith(")") and " (at " in message:
72
+ message = message.rsplit(" (at ", 1)[0]
73
+ raise ParseError(message, line, column, position=position) from error
74
+ except RecursionError:
75
+ _raise_limit(source, 0, "document exceeds the parser nesting limit")
76
+
77
+ _check_value_limits(source, value, options)
78
+ end_line, end_column = _end_location(source)
79
+ return Document(
80
+ value=value,
81
+ source=source,
82
+ span=SourceSpan(0, len(source), 1, 1, end_line, end_column),
83
+ )
84
+
85
+
86
+ def loads(source: str, *, options: ParseOptions = ParseOptions()) -> dict[str, TomlValue]:
87
+ """Parse *source* and return its Python value."""
88
+ return parse(source, options=options).value
89
+
90
+
91
+ def _check_value_limits(
92
+ source: str,
93
+ value: dict[str, TomlValue],
94
+ options: ParseOptions,
95
+ ) -> None:
96
+ nodes = 0
97
+ pending: list[tuple[TomlValue, int]] = [(value, 0)]
98
+ while pending:
99
+ current, depth = pending.pop()
100
+ nodes += 1
101
+ if nodes > options.max_nodes:
102
+ _raise_limit(
103
+ source,
104
+ 0,
105
+ f"document exceeds the {options.max_nodes}-node limit",
106
+ )
107
+ if isinstance(current, dict):
108
+ if depth > options.max_depth:
109
+ _raise_limit(
110
+ source,
111
+ 0,
112
+ f"document exceeds the {options.max_depth}-level nesting limit",
113
+ )
114
+ pending.extend((child, depth + 1) for child in current.values())
115
+ elif isinstance(current, list):
116
+ if depth > options.max_depth:
117
+ _raise_limit(
118
+ source,
119
+ 0,
120
+ f"document exceeds the {options.max_depth}-level nesting limit",
121
+ )
122
+ pending.extend((child, depth + 1) for child in current)
123
+
124
+
125
+ def _check_container_depth(source: str, max_depth: int) -> None:
126
+ depth = 0
127
+ quote: str | None = None
128
+ at_line_start = True
129
+ index = 0
130
+
131
+ while index < len(source):
132
+ char = source[index]
133
+ if quote is not None:
134
+ if quote in {'"""', "'''"}:
135
+ if quote == '"""' and char == "\\":
136
+ index += 2
137
+ continue
138
+ if source.startswith(quote, index):
139
+ quote = None
140
+ index += 3
141
+ continue
142
+ else:
143
+ if quote == '"' and char == "\\":
144
+ index += 2
145
+ continue
146
+ if char == quote:
147
+ quote = None
148
+ at_line_start = char in "\r\n"
149
+ index += 1
150
+ continue
151
+
152
+ if char in " \t" and at_line_start:
153
+ index += 1
154
+ continue
155
+ if char in "\r\n":
156
+ at_line_start = True
157
+ index += 1
158
+ continue
159
+ if at_line_start and char == "[" and depth == 0:
160
+ header_end = _table_header_end(source, index)
161
+ if header_end is not None:
162
+ index = header_end
163
+ at_line_start = False
164
+ continue
165
+ at_line_start = False
166
+
167
+ if char == "#":
168
+ newline = min(
169
+ (position for position in (source.find("\n", index), source.find("\r", index)) if position >= 0),
170
+ default=len(source),
171
+ )
172
+ index = newline
173
+ continue
174
+ if char in "\"'":
175
+ delimiter = char * 3
176
+ if source.startswith(delimiter, index):
177
+ quote = delimiter
178
+ index += 3
179
+ else:
180
+ quote = char
181
+ index += 1
182
+ continue
183
+ if char in "[{":
184
+ depth += 1
185
+ if depth > max_depth:
186
+ _raise_limit(
187
+ source,
188
+ index,
189
+ f"document exceeds the {max_depth}-level nesting limit",
190
+ )
191
+ elif char in "]}" and depth:
192
+ depth -= 1
193
+ index += 1
194
+
195
+
196
+ def _table_header_end(source: str, start: int) -> int | None:
197
+ double = source.startswith("[[", start)
198
+ closing = "]]" if double else "]"
199
+ index = start + (2 if double else 1)
200
+ quote: str | None = None
201
+ while index < len(source) and source[index] not in "\r\n":
202
+ char = source[index]
203
+ if quote is not None:
204
+ if quote == '"' and char == "\\":
205
+ index += 2
206
+ continue
207
+ if char == quote:
208
+ quote = None
209
+ elif char in "\"'":
210
+ quote = char
211
+ elif source.startswith(closing, index):
212
+ end = index + len(closing)
213
+ line_end = min(
214
+ (position for position in (source.find("\n", end), source.find("\r", end)) if position >= 0),
215
+ default=len(source),
216
+ )
217
+ tail = source[end:line_end]
218
+ if tail.strip() == "" or tail.lstrip().startswith("#"):
219
+ return end
220
+ return None
221
+ index += 1
222
+ return None
223
+
224
+
225
+ def _raise_limit(source: str, position: int, message: str) -> NoReturn:
226
+ line, column = _line_column(source, position)
227
+ raise ParseError(message, line, column, "limit-exceeded", position)
228
+
229
+
230
+ def _line_column(source: str, position: int) -> tuple[int, int]:
231
+ prefix = source[:position]
232
+ last_newline = max(prefix.rfind("\n"), prefix.rfind("\r"))
233
+ return prefix.count("\n") + prefix.count("\r") - prefix.count("\r\n") + 1, position - last_newline
234
+
235
+
236
+ def _end_location(source: str) -> tuple[int, int]:
237
+ return _line_column(source, len(source))
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: parse-toml
3
+ Version: 0.1.0
4
+ Summary: Bounded, source-aware TOML 1.0 parsing for Python
5
+ Author: wispsy
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Programming Language :: Python :: 3.14
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.14
12
+ Project-URL: Repository, https://github.com/wispsy/parse-toml
13
+ Project-URL: Issues, https://github.com/wispsy/parse-toml/issues
14
+ Description-Content-Type: text/markdown
15
+
16
+ # parse-toml
17
+
18
+ `parse-toml` is a typed, bounded TOML 1.0 parser for Python 3.14 and newer.
19
+ It uses Python's standard-library `tomllib`, has no runtime dependencies, and
20
+ preserves the original source alongside the parsed value.
21
+
22
+ ```python
23
+ from parse_toml import parse
24
+
25
+ document = parse('name = "Ada"\nactive = true\n')
26
+ print(document.value["name"]) # Ada
27
+ print(document.to_toml()) # the original source
28
+ ```
29
+
30
+ Use `loads(source)` when only the converted Python value is needed. Invalid
31
+ input raises `ParseError` with a message, line, column, and error code. Resource
32
+ limits can be adjusted with `ParseOptions`; inputs that exceed a limit do not
33
+ produce a partial result.
34
+
35
+ See [the API and supported syntax](docs/api.md) for TOML value types, resource
36
+ limits, and error behavior.
37
+
38
+ See [the release guide](docs/releasing.md) for PyPI Trusted Publishing setup
39
+ and release instructions.
40
+
41
+ ## Development
42
+
43
+ ```sh
44
+ uv sync --locked
45
+ uv run --frozen python -m pytest
46
+ uv run --frozen python scripts/check_distribution.py --output-dir dist
47
+ ```
48
+
49
+ The test and distribution checks also run in GitHub Actions on Python 3.14.
@@ -0,0 +1,7 @@
1
+ parse_toml/__init__.py,sha256=3othNT5xeBVgRCOeIqz_ChG1SQqpEhN_u47kuf8cyCc,317
2
+ parse_toml/nodes.py,sha256=Y37FRTJefuDNIvH9SaBGrsALzTJpEdLBEtsb7BSLmz0,876
3
+ parse_toml/parser.py,sha256=dcRVwgqmJJLJi4EiGR51VVH1au0juJAXr-MNhS_6hyE,7780
4
+ parse_toml-0.1.0.dist-info/licenses/LICENSE,sha256=dJjxPlUliHO6iuJiKxsIn0HSnRRb-dp_8lpVtAunRj8,1063
5
+ parse_toml-0.1.0.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
6
+ parse_toml-0.1.0.dist-info/METADATA,sha256=WDd1E6-1hJiU0hcx1c1ptkLJJLky9re22Bu1pc7GGmo,1599
7
+ parse_toml-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.6
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 wispsy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.