parse-errors 0.5.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.
@@ -0,0 +1,13 @@
1
+ """re-raise parse errors with filename and line number."""
2
+
3
+ from .context import ParseContext, ParseError
4
+
5
+ try:
6
+ from ._version import __version__
7
+ except ImportError: # pragma: no cover
8
+ __version__ = "dev"
9
+
10
+ __all__ = [
11
+ "ParseContext",
12
+ "ParseError",
13
+ ]
@@ -0,0 +1,70 @@
1
+ """Convert JSONPath expressions to JSON Pointer (RFC 6901)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+
8
+ # Matches a single step in a JSONPath: .key or [index] or ['key'] or ["key"]
9
+ _STEP = re.compile(
10
+ r"\.(?P<name>[^.\[]+)" # .key
11
+ r"|\[(?P<idx>\d+)\]" # [0]
12
+ r"|\[\'(?P<sq>[^\']*)\'\]" # ['key']
13
+ r'|\["(?P<dq>[^"]*)"\]' # ["key"]
14
+ )
15
+
16
+ # Pattern to extract JSONPath from msgspec-style error messages: "... - at `$.foo.bar`"
17
+ _AT_PATH = re.compile(r" - at `(\$[^`]*)`")
18
+
19
+
20
+ def jsonpath_to_pointer(jsonpath: str) -> str:
21
+ """Convert a JSONPath string like ``$.foo[0].bar`` to a JSON Pointer like ``/foo/0/bar``.
22
+
23
+ Only supports simple dot-notation and bracket-index forms as produced by
24
+ msgspec. Does not support filter expressions or wildcards.
25
+
26
+ Args:
27
+ jsonpath: A JSONPath string starting with ``$``.
28
+
29
+ Returns:
30
+ A JSON Pointer string (RFC 6901), e.g. ``/foo/0/bar``.
31
+ """
32
+ if jsonpath == "$":
33
+ return ""
34
+ if not jsonpath.startswith("$"):
35
+ raise ValueError(f"JSONPath must start with '$', got: {jsonpath!r}")
36
+
37
+ tail = jsonpath[1:] # strip leading $
38
+ parts: list[str] = []
39
+
40
+ pos = 0
41
+ while pos < len(tail):
42
+ m = _STEP.match(tail, pos)
43
+ if m is None:
44
+ raise ValueError(
45
+ f"Cannot parse JSONPath step at position {pos}: {tail[pos:]!r}"
46
+ )
47
+ name = m.group("name") or m.group("sq") or m.group("dq") or m.group("idx")
48
+ parts.append(_escape(name))
49
+ pos = m.end()
50
+
51
+ return "/" + "/".join(parts) if parts else ""
52
+
53
+
54
+ def extract_jsonpath(message: str) -> str | None:
55
+ """Extract a JSONPath expression from an error message.
56
+
57
+ Looks for the pattern ``- at `$.path``` as used by msgspec.
58
+
59
+ Args:
60
+ message: The exception message string.
61
+
62
+ Returns:
63
+ The JSONPath string if found, otherwise ``None``.
64
+ """
65
+ m = _AT_PATH.search(message)
66
+ return m.group(1) if m else None
67
+
68
+
69
+ def _escape(segment: str) -> str:
70
+ return segment.replace("~", "~0").replace("/", "~1")
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.5.0'
32
+ __version_tuple__ = version_tuple = (0, 5, 0)
33
+
34
+ __commit_id__ = commit_id = None
@@ -0,0 +1,83 @@
1
+ """Context manager for better parse error messages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import contextlib
7
+ from pathlib import Path
8
+ from typing import Iterator
9
+
10
+ from .source_map import detect_format, build_source_map, closest_entry
11
+ from ._jsonpath import extract_jsonpath, jsonpath_to_pointer
12
+
13
+ __all__ = ["ParseError", "ParseContext"]
14
+
15
+
16
+ class ParseError(Exception):
17
+ """A parse or validation error augmented with filename and line number."""
18
+
19
+ def __init__(
20
+ self, message: str, filename: str | os.PathLike[str], line: int, column: int = 0
21
+ ):
22
+ self.filename = str(filename)
23
+ self.line = line
24
+ self.column = column
25
+ super().__init__(message)
26
+
27
+
28
+ @contextlib.contextmanager
29
+ def ParseContext(
30
+ filename: str | os.PathLike[str],
31
+ *,
32
+ data: str | bytes | None = None,
33
+ format: str | None = None,
34
+ ) -> Iterator[None]:
35
+ """Context manager that re-raises parse/validation errors with location info.
36
+
37
+ Catches exceptions whose message contains a JSONPath (e.g. as emitted by
38
+ msgspec) and re-raises a :class:`ParseError` with the filename and
39
+ 1-based line number derived from the file's source map.
40
+
41
+ Args:
42
+ filename: Path to the file being parsed.
43
+ data: The file contents as a string or bytes (UTF-8). If provided, the
44
+ file is not read from disk. Regardless of type, reported
45
+ locations (line, column) are always in characters, not bytes.
46
+ format: One of ``"json"``, ``"yaml"``, or ``"toml"``. If omitted the
47
+ format is inferred from the file extension.
48
+ """
49
+ try:
50
+ yield
51
+ except Exception as exc:
52
+ message = str(exc)
53
+ # This is focused on msgspec-style exceptions, which use JSONPath for
54
+ # some reason. If there are other formats we know can be raised,
55
+ # adjust this.
56
+ jsonpath = extract_jsonpath(message)
57
+ if jsonpath is None:
58
+ raise
59
+
60
+ try:
61
+ pointer = jsonpath_to_pointer(jsonpath)
62
+ except ValueError: # pragma: no cover
63
+ raise exc
64
+
65
+ path = Path(filename)
66
+ fmt = format or detect_format(path)
67
+ assert fmt is not None
68
+
69
+ source = data if data is not None else path.read_bytes()
70
+ source_map = build_source_map(source, fmt)
71
+
72
+ entry = closest_entry(source_map, pointer)
73
+ if entry is None: # pragma: no cover
74
+ raise exc
75
+
76
+ loc = entry.value_start
77
+ # Lines are 0-based in source maps; convert to 1-based for humans.
78
+ raise ParseError(
79
+ f"{path}:{loc.line + 1}:{loc.column + 1}: {message}",
80
+ filename=path,
81
+ line=loc.line + 1,
82
+ column=loc.column + 1,
83
+ ) from exc
@@ -0,0 +1,25 @@
1
+ """Thin wrapper around the json-source-map package that returns our own types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json_source_map as _ext
6
+
7
+ from ..source_map import Entry, Location, TSourceMap
8
+
9
+
10
+ def calculate(source: str) -> TSourceMap:
11
+ """Calculate the source map for a JSON document."""
12
+ return {
13
+ pointer: Entry(
14
+ value_start=_loc(e.value_start),
15
+ value_end=_loc(e.value_end),
16
+ key_start=_loc(e.key_start) if e.key_start is not None else None,
17
+ key_end=_loc(e.key_end) if e.key_end is not None else None,
18
+ )
19
+ for pointer, e in _ext.calculate(source).items()
20
+ }
21
+
22
+
23
+ def _loc(ext: _ext.Location) -> Location:
24
+ """Translate to our internal structure."""
25
+ return Location(line=ext.line, column=ext.column, position=ext.position)
@@ -0,0 +1,7 @@
1
+ if __name__ == "__main__": # pragma: no cover
2
+ import sys
3
+ from . import calculate
4
+
5
+ source = open(sys.argv[1]).read()
6
+ for pointer, entry in calculate(source).items():
7
+ print(f"{pointer!r:40s} {entry}")
parse_errors/py.typed ADDED
File without changes
@@ -0,0 +1,77 @@
1
+ """Source map types and utilities for parse_errors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ from pathlib import Path
7
+ from typing import Dict, Optional
8
+
9
+
10
+ # These are identical to the ones in json-source-map, but I feel icky exporting
11
+ # some other project's types because they may change.
12
+
13
+
14
+ @dataclasses.dataclass
15
+ class Location:
16
+ line: int # 0-based line number
17
+ column: int # 0-based character offset within the line (not bytes)
18
+ position: int # 0-based character offset from start of document (not bytes)
19
+
20
+
21
+ @dataclasses.dataclass
22
+ class Entry:
23
+ value_start: Location
24
+ value_end: Location
25
+ key_start: Optional[Location] = None
26
+ key_end: Optional[Location] = None
27
+
28
+
29
+ TSourceMap = Dict[str, Entry]
30
+
31
+
32
+ def detect_format(path: Path) -> str | None:
33
+ """Detect the format of a file based on its extension."""
34
+ suffix = path.suffix.lower()
35
+ return {
36
+ ".json": "json",
37
+ ".toml": "toml",
38
+ ".yaml": "yaml",
39
+ ".yml": "yaml",
40
+ }.get(suffix)
41
+
42
+
43
+ def build_source_map(source: str | bytes, fmt: str) -> TSourceMap:
44
+ """Build a source map for the given source in the given format."""
45
+ if fmt == "toml":
46
+ from . import toml_source_map
47
+
48
+ return toml_source_map.calculate(source)
49
+ elif fmt in ("yaml", "yml"):
50
+ from . import yaml_source_map
51
+
52
+ return yaml_source_map.calculate(
53
+ source.decode("utf-8") if isinstance(source, bytes) else source
54
+ )
55
+ elif fmt == "json":
56
+ from . import json_source_map
57
+
58
+ return json_source_map.calculate(
59
+ source.decode("utf-8") if isinstance(source, bytes) else source
60
+ )
61
+ else:
62
+ raise ValueError(f"Unknown format: {fmt!r}")
63
+
64
+
65
+ def closest_entry(source_map: TSourceMap, pointer: str) -> Entry | None:
66
+ """Return the source map entry for ``pointer``, falling back to the longest prefix."""
67
+ if pointer in source_map:
68
+ return source_map[pointer]
69
+
70
+ # Walk up the pointer path until we find a match.
71
+ parts = pointer.split("/") # e.g. ['', 'foo', 'bar']
72
+ for length in range(len(parts) - 1, 0, -1):
73
+ candidate = "/".join(parts[:length])
74
+ if candidate in source_map:
75
+ return source_map[candidate]
76
+
77
+ return None
@@ -0,0 +1,194 @@
1
+ """Calculate the source map for a TOML document using tree-sitter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tree_sitter_toml
6
+ import tree_sitter as ts
7
+ from ..source_map import Entry, Location, TSourceMap
8
+ from .._jsonpath import _escape
9
+
10
+
11
+ def calculate(source: str | bytes) -> TSourceMap:
12
+ """Calculate the source map for a TOML document.
13
+
14
+ Args:
15
+ source: The TOML document as a string or bytes.
16
+
17
+ Returns:
18
+ A dict mapping JSON Pointer paths to Entry objects with location info.
19
+ """
20
+ src_bytes = source if isinstance(source, bytes) else source.encode("utf-8")
21
+ parser = ts.Parser(ts.Language(tree_sitter_toml.language()))
22
+ root = parser.parse(src_bytes).root_node
23
+
24
+ result: TSourceMap = {}
25
+ aot_counts: dict[str, int] = {}
26
+
27
+ result[""] = Entry(
28
+ value_start=_loc(root.start_point, src_bytes),
29
+ value_end=_loc(root.end_point, src_bytes),
30
+ )
31
+
32
+ for child in root.children:
33
+ if child.type == "pair":
34
+ _process_pair(child, [], result, src_bytes)
35
+ elif child.type == "table":
36
+ _process_table(child, result, aot_counts, src_bytes)
37
+ elif child.type == "table_array_element":
38
+ _process_aot(child, result, aot_counts, src_bytes)
39
+
40
+ return result
41
+
42
+
43
+ def _process_pair(
44
+ node: ts.Node,
45
+ prefix: list[str],
46
+ result: TSourceMap,
47
+ src: bytes,
48
+ ) -> None:
49
+ key_node, value_node = _pair_key_value(node)
50
+ segments = prefix + _key_segments(key_node)
51
+ pointer = _to_pointer(segments)
52
+
53
+ if value_node.type == "inline_table":
54
+ result[pointer] = Entry(
55
+ value_start=_loc(value_node.start_point, src),
56
+ value_end=_loc(value_node.end_point, src),
57
+ key_start=_loc(key_node.start_point, src),
58
+ key_end=_loc(key_node.end_point, src),
59
+ )
60
+ for child in value_node.children:
61
+ if child.type == "pair":
62
+ _process_pair(child, segments, result, src)
63
+ else:
64
+ result[pointer] = Entry(
65
+ value_start=_loc(value_node.start_point, src),
66
+ value_end=_loc(value_node.end_point, src),
67
+ key_start=_loc(key_node.start_point, src),
68
+ key_end=_loc(key_node.end_point, src),
69
+ )
70
+
71
+
72
+ def _process_table(
73
+ node: ts.Node,
74
+ result: TSourceMap,
75
+ aot_counts: dict[str, int],
76
+ src: bytes,
77
+ ) -> None:
78
+ key_node = _table_key(node)
79
+ segments = _expand_aot_segments(_key_segments(key_node), aot_counts)
80
+ pointer = _to_pointer(segments)
81
+
82
+ result[pointer] = Entry(
83
+ value_start=_loc(node.start_point, src),
84
+ value_end=_loc(node.end_point, src),
85
+ )
86
+
87
+ for child in node.children:
88
+ if child.type == "pair":
89
+ _process_pair(child, segments, result, src)
90
+
91
+
92
+ def _process_aot(
93
+ node: ts.Node,
94
+ result: TSourceMap,
95
+ aot_counts: dict[str, int],
96
+ src: bytes,
97
+ ) -> None:
98
+ key_node = _table_key(node)
99
+ segments = _key_segments(key_node)
100
+ array_pointer = _to_pointer(segments)
101
+
102
+ idx = aot_counts.get(array_pointer, 0)
103
+ aot_counts[array_pointer] = idx + 1
104
+
105
+ item_segments = segments + [str(idx)]
106
+ item_pointer = _to_pointer(item_segments)
107
+
108
+ entry_loc = _loc(node.start_point, src)
109
+ result.setdefault(array_pointer, Entry(value_start=entry_loc, value_end=entry_loc))
110
+ result[item_pointer] = Entry(
111
+ value_start=entry_loc,
112
+ value_end=_loc(node.end_point, src),
113
+ )
114
+
115
+ for child in node.children:
116
+ if child.type == "pair":
117
+ _process_pair(child, item_segments, result, src)
118
+
119
+
120
+ def _pair_key_value(node: ts.Node) -> tuple[ts.Node, ts.Node]:
121
+ """Return (key_node, value_node) from a pair node."""
122
+ key_node = value_node = None
123
+ for child in node.children:
124
+ if child.type in ("bare_key", "quoted_key", "dotted_key"):
125
+ key_node = child
126
+ elif child.type not in ("=", "comment"):
127
+ value_node = child
128
+
129
+ assert key_node is not None
130
+ assert value_node is not None
131
+ return key_node, value_node
132
+
133
+
134
+ def _table_key(node: ts.Node) -> ts.Node:
135
+ """Return the key node from a table or table_array_element node."""
136
+ for child in node.children:
137
+ if child.type in ("bare_key", "quoted_key", "dotted_key"):
138
+ return child
139
+ raise ValueError(f"No key found in {node.type}") # pragma: no cover
140
+
141
+
142
+ def _key_segments(node: ts.Node) -> list[str]:
143
+ """Extract key path segments from a key node."""
144
+ if node.type == "bare_key":
145
+ assert node.text is not None
146
+ return [node.text.decode()]
147
+ elif node.type == "quoted_key":
148
+ assert node.text is not None
149
+ return [_unquote(node.text.decode())]
150
+ elif node.type == "dotted_key":
151
+ return sum((_key_segments(child) for child in node.children), [])
152
+ return []
153
+
154
+
155
+ def _unquote(s: str) -> str:
156
+ """Strip surrounding quotes from a TOML quoted key."""
157
+ if s.startswith('"') and s.endswith('"'):
158
+ # Basic string: full TOML escape sequences via unicode_escape codec.
159
+ # Encode to latin-1 first to preserve non-ASCII literals, then decode escapes.
160
+ return s[1:-1].encode("raw_unicode_escape").decode("unicode_escape")
161
+ elif s.startswith("'") and s.endswith("'"):
162
+ # Literal string: no escaping
163
+ return s[1:-1]
164
+ return s # pragma: no cover
165
+
166
+
167
+ def _expand_aot_segments(segments: list[str], aot_counts: dict[str, int]) -> list[str]:
168
+ """If a prefix of segments matches a known AoT, splice in its current index.
169
+
170
+ e.g. segments=[fruits, details] with aot_counts={/fruits: 1}
171
+ → [fruits, 0, details]
172
+ """
173
+ for i in range(1, len(segments)):
174
+ prefix_pointer = _to_pointer(segments[:i])
175
+ if prefix_pointer in aot_counts:
176
+ idx = aot_counts[prefix_pointer] - 1
177
+ return segments[:i] + [str(idx)] + segments[i:]
178
+ return segments
179
+
180
+
181
+ def _to_pointer(segments: list[str]) -> str:
182
+ return "/" + "/".join(_escape(s) for s in segments) if segments else ""
183
+
184
+
185
+ def _loc(point: ts.Point, src: bytes) -> Location:
186
+ # tree-sitter gives byte-based row/column; convert to char-based for consistency
187
+ # with json-source-map and yaml-source-map.
188
+ # Append b"" so end_point row (one past final newline) is always a valid index.
189
+ lines = src.splitlines(True) + [b""]
190
+ char_column = len(lines[point.row][: point.column].decode("utf-8"))
191
+ position = (
192
+ sum(len(line.decode("utf-8")) for line in lines[: point.row]) + char_column
193
+ )
194
+ return Location(line=point.row, column=char_column, position=position)
@@ -0,0 +1,7 @@
1
+ if __name__ == "__main__": # pragma: no cover
2
+ import sys
3
+ from . import calculate
4
+
5
+ source = open(sys.argv[1]).read()
6
+ for pointer, entry in calculate(source).items():
7
+ print(f"{pointer!r:40s} {entry}")
@@ -0,0 +1,62 @@
1
+ """Calculate the source map for a YAML document."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import yaml
6
+ from ..source_map import Entry, Location, TSourceMap
7
+
8
+
9
+ def calculate(source: str) -> TSourceMap:
10
+ """Calculate the source map for a YAML document.
11
+
12
+ Args:
13
+ source: The YAML document as a string.
14
+
15
+ Returns:
16
+ A dict mapping JSON Pointer paths to Entry objects with location info.
17
+ """
18
+ loader = yaml.SafeLoader(source)
19
+ node = loader.get_single_node()
20
+ if node is None:
21
+ return {}
22
+ result: TSourceMap = {}
23
+ _walk(node, "", result, loader)
24
+ return result
25
+
26
+
27
+ def _location(mark: yaml.Mark) -> Location:
28
+ return Location(line=mark.line, column=mark.column, position=mark.index)
29
+
30
+
31
+ def _walk(
32
+ node: yaml.Node, path: str, result: TSourceMap, loader: yaml.SafeLoader
33
+ ) -> None:
34
+ value_start = _location(node.start_mark)
35
+ value_end = _location(node.end_mark)
36
+
37
+ if isinstance(node, yaml.MappingNode):
38
+ result[path] = Entry(value_start=value_start, value_end=value_end)
39
+ for key_node, value_node in node.value:
40
+ key = loader.construct_scalar(key_node)
41
+ child_path = f"{path}/{_escape(str(key))}"
42
+ key_start = _location(key_node.start_mark)
43
+ key_end = _location(key_node.end_mark)
44
+ _walk(value_node, child_path, result, loader)
45
+ existing = result[child_path]
46
+ result[child_path] = Entry(
47
+ value_start=existing.value_start,
48
+ value_end=existing.value_end,
49
+ key_start=key_start,
50
+ key_end=key_end,
51
+ )
52
+ elif isinstance(node, yaml.SequenceNode):
53
+ result[path] = Entry(value_start=value_start, value_end=value_end)
54
+ for i, item_node in enumerate(node.value):
55
+ _walk(item_node, f"{path}/{i}", result, loader)
56
+ else:
57
+ result[path] = Entry(value_start=value_start, value_end=value_end)
58
+
59
+
60
+ def _escape(key: str) -> str:
61
+ """Escape a key for use in a JSON Pointer (RFC 6901)."""
62
+ return key.replace("~", "~0").replace("/", "~1")
@@ -0,0 +1,7 @@
1
+ if __name__ == "__main__": # pragma: no cover
2
+ import sys
3
+ from . import calculate
4
+
5
+ source = open(sys.argv[1]).read()
6
+ for pointer, entry in calculate(source).items():
7
+ print(f"{pointer!r:40s} {entry}")
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: parse-errors
3
+ Version: 0.5.0
4
+ Summary: re-raise parse errors with filename and line number
5
+ Home-page: https://github.com/advice-animal/parse-errors/
6
+ Author: Tim Hatch
7
+ Author-email: tim@timhatch.com
8
+ License: MIT
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: json-source-map
13
+ Requires-Dist: pyyaml
14
+ Requires-Dist: tree-sitter
15
+ Requires-Dist: tree-sitter-toml
16
+ Provides-Extra: dev
17
+ Requires-Dist: checkdeps==0.9.0; extra == "dev"
18
+ Requires-Dist: mypy==1.19.1; extra == "dev"
19
+ Requires-Dist: ruff==0.15.6; extra == "dev"
20
+ Requires-Dist: tox==4.50.0; extra == "dev"
21
+ Requires-Dist: tox-uv==1.33.4; extra == "dev"
22
+ Requires-Dist: types-pyyaml; extra == "dev"
23
+ Provides-Extra: test
24
+ Requires-Dist: coverage>=6; extra == "test"
25
+ Requires-Dist: pytest>=8; extra == "test"
26
+ Requires-Dist: msgspec; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # parse-errors
30
+
31
+
32
+ # Version Compat
33
+
34
+ This library is compatile with Python 3.10+, but should be linted under the
35
+ newest stable version.
36
+
37
+ # Versioning
38
+
39
+ This library follows [meanver](https://meanver.org/) which basically means
40
+ [semver](https://semver.org/) along with a promise to rename when the major
41
+ version changes.
42
+
43
+ # License
44
+
45
+ parse-errors is copyright [Tim Hatch](https://timhatch.com/), and licensed under
46
+ the MIT license. See the `LICENSE` file for details.
@@ -0,0 +1,24 @@
1
+ parse_errors/__init__.py,sha256=CvFERGkB_kPTZaNm2OOhN_oWk8GoyuPG9QCbOlWk8FE,267
2
+ parse_errors/_jsonpath.py,sha256=rZtKCyd6Pq5w32CHtTXwfA8uiX9-s4MxA1-iB0BJTyc,2047
3
+ parse_errors/_version.py,sha256=fvHpBU3KZKRinkriKdtAt3crenOyysELF-M9y3ozg3U,704
4
+ parse_errors/context.py,sha256=u4uw6tL_Y4KZiRXBmZqC3c6bWqRsZVLvmBLyL66tT6c,2741
5
+ parse_errors/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ parse_errors/source_map.py,sha256=rql45F9NY2NkVwVd3AigVdvT9gokB4194b0DB9V_wjI,2244
7
+ parse_errors/json_source_map/__init__.py,sha256=ikxzrIV5Slr6vk5lAEi_hypNxZF5osLNHEpBM8WKsfA,818
8
+ parse_errors/json_source_map/__main__.py,sha256=TDNK26EbxF0WMS-AODOCNtI1mOaB1LR7LJleSAH4b_8,224
9
+ parse_errors/toml_source_map/__init__.py,sha256=fsYKzIFF9htEwrnAiEAddT9RM_HEVB7ClXu-OUfssrs,6493
10
+ parse_errors/toml_source_map/__main__.py,sha256=TDNK26EbxF0WMS-AODOCNtI1mOaB1LR7LJleSAH4b_8,224
11
+ parse_errors/yaml_source_map/__init__.py,sha256=roVnYYF9d9ySFywGE-Gmtc_mD3U5vsv_nd6lQWd9JMc,2076
12
+ parse_errors/yaml_source_map/__main__.py,sha256=TDNK26EbxF0WMS-AODOCNtI1mOaB1LR7LJleSAH4b_8,224
13
+ parse_errors-0.5.0.dist-info/licenses/LICENSE,sha256=VmipWWASETlYtNqZa5usLdDsB3mgyEZfkXaTqq5N06Y,1066
14
+ tests/__init__.py,sha256=RIdYaeATLR1IDVfU2zKSFmQIDNAwcrVfu3_sbiVgi0w,68
15
+ tests/_types.py,sha256=QPnMThM4g-waEXDPGrbUYeYIuNpmKgX-JqgX2GKut4E,126
16
+ tests/conftest.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ tests/test_parse_context_json.py,sha256=ZH16fSvufoC8vvRM9axweqDICi5B4TuF6oHnlKXjB8w,2211
18
+ tests/test_parse_context_toml.py,sha256=Ea5a0_uRtMG-eWoNFT6MRlehVNBEAVQESgnTc6Hheq0,2230
19
+ tests/test_parse_context_yaml.py,sha256=2HiYdw7S-hYsxEF1yjHTBpbRP5WMpjJLlvdFyVGXvpA,1317
20
+ tests/test_source_map.py,sha256=JAqp0TnvjwIh9IbVMOBIYIhp_jXB0O01s2QN4CcxUPM,1574
21
+ parse_errors-0.5.0.dist-info/METADATA,sha256=HSZgwUQuJUhwru-4DdGPndfo2lipguo_jXE3dEbH4rM,1358
22
+ parse_errors-0.5.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
23
+ parse_errors-0.5.0.dist-info/top_level.txt,sha256=JcC-dKRhzVdseLnfdPfRa9lIdyNmKn0WiRFNHgI1lCU,19
24
+ parse_errors-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tim Hatch
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.
@@ -0,0 +1,2 @@
1
+ parse_errors
2
+ tests
tests/__init__.py ADDED
@@ -0,0 +1 @@
1
+ # Needed so pytest considers this a package -- PEP 420 isn't enough
tests/_types.py ADDED
@@ -0,0 +1,10 @@
1
+ import msgspec
2
+
3
+
4
+ class Config(msgspec.Struct):
5
+ host: str
6
+ port: int
7
+
8
+
9
+ class Nested(msgspec.Struct):
10
+ server: Config
tests/conftest.py ADDED
File without changes
@@ -0,0 +1,79 @@
1
+ import pytest
2
+ import msgspec
3
+
4
+ from parse_errors import ParseContext, ParseError
5
+
6
+ from ._types import Config, Nested
7
+
8
+
9
+ JSON_GOOD = b'{"host": "localhost", "port": 8080}'
10
+ JSON_BAD = b'{"host": "localhost", "port": "not-an-int"}'
11
+ JSON_NESTED_BAD = b'{"server": {"host": "localhost", "port": "not-an-int"}}'
12
+
13
+ JSON_SOURCE = """\
14
+ {
15
+ "host": "localhost",
16
+ "port": "not-an-int"
17
+ }
18
+ """
19
+
20
+ JSON_NESTED_SOURCE = """\
21
+ {
22
+ "server": {
23
+ "host": "localhost",
24
+ "port": "not-an-int"
25
+ }
26
+ }
27
+ """
28
+
29
+
30
+ def test_json_no_error():
31
+ with ParseContext("config.json", data=JSON_GOOD.decode()):
32
+ msgspec.json.decode(JSON_GOOD, type=Config)
33
+
34
+
35
+ def test_json_non_jsonpath_exception_passes_through():
36
+ with pytest.raises(ZeroDivisionError):
37
+ with ParseContext("config.json", data=JSON_SOURCE):
38
+ raise ZeroDivisionError("oops")
39
+
40
+
41
+ def test_json_raises_parse_error():
42
+ with pytest.raises(ParseError) as exc_info:
43
+ with ParseContext("config.json", data=JSON_SOURCE):
44
+ msgspec.json.decode(JSON_SOURCE.encode(), type=Config)
45
+
46
+ err = exc_info.value
47
+ assert err.filename == "config.json"
48
+ assert err.line == 3
49
+ assert str(err) == "config.json:3:11: Expected `int`, got `str` - at `$.port`"
50
+
51
+
52
+ def test_json_nested_raises_parse_error():
53
+ with pytest.raises(ParseError) as exc_info:
54
+ with ParseContext("config.json", data=JSON_NESTED_SOURCE):
55
+ msgspec.json.decode(JSON_NESTED_SOURCE.encode(), type=Nested)
56
+
57
+ err = exc_info.value
58
+ assert (
59
+ str(err) == "config.json:4:13: Expected `int`, got `str` - at `$.server.port`"
60
+ )
61
+
62
+
63
+ def test_json_bytes_data():
64
+ with pytest.raises(ParseError) as exc_info:
65
+ with ParseContext("config.json", data=JSON_SOURCE.encode()):
66
+ msgspec.json.decode(JSON_SOURCE.encode(), type=Config)
67
+
68
+ assert (
69
+ str(exc_info.value)
70
+ == "config.json:3:11: Expected `int`, got `str` - at `$.port`"
71
+ )
72
+
73
+
74
+ def test_json_original_exception_is_cause():
75
+ with pytest.raises(ParseError) as exc_info:
76
+ with ParseContext("config.json", data=JSON_SOURCE):
77
+ msgspec.json.decode(JSON_SOURCE.encode(), type=Config)
78
+
79
+ assert isinstance(exc_info.value.__cause__, msgspec.ValidationError)
@@ -0,0 +1,82 @@
1
+ try:
2
+ import tomllib
3
+ except ImportError:
4
+ import tomli as tomllib # type: ignore[no-redef]
5
+
6
+ import pytest
7
+ import msgspec
8
+
9
+ from parse_errors import ParseContext, ParseError
10
+
11
+ from ._types import Config, Nested
12
+
13
+
14
+ TOML_SOURCE = """\
15
+ host = "localhost"
16
+ port = "not-an-int"
17
+ """
18
+
19
+ TOML_NESTED_SOURCE = """\
20
+ [server]
21
+ host = "localhost"
22
+ port = "not-an-int"
23
+ """
24
+
25
+
26
+ def test_passthrough_non_jsonspec():
27
+ with pytest.raises(ValueError, match="^foo$"):
28
+ with ParseContext("config.toml", data=TOML_SOURCE):
29
+ raise ValueError("foo")
30
+
31
+
32
+ def test_toml_raises_parse_error():
33
+ with pytest.raises(ParseError) as exc_info:
34
+ with ParseContext("config.toml", data=TOML_SOURCE):
35
+ data = tomllib.loads(TOML_SOURCE)
36
+ msgspec.convert(data, Config)
37
+
38
+ err = exc_info.value
39
+ assert err.filename == "config.toml"
40
+ assert err.line == 2
41
+ assert str(err) == "config.toml:2:8: Expected `int`, got `str` - at `$.port`"
42
+
43
+
44
+ def test_toml_bytes_data():
45
+ with pytest.raises(ParseError) as exc_info:
46
+ with ParseContext("config.toml", data=TOML_SOURCE.encode()):
47
+ data = tomllib.loads(TOML_SOURCE)
48
+ msgspec.convert(data, Config)
49
+
50
+ assert (
51
+ str(exc_info.value)
52
+ == "config.toml:2:8: Expected `int`, got `str` - at `$.port`"
53
+ )
54
+
55
+
56
+ def test_toml_nested_raises_parse_error():
57
+ with pytest.raises(ParseError) as exc_info:
58
+ with ParseContext("config.toml", data=TOML_NESTED_SOURCE):
59
+ data = tomllib.loads(TOML_NESTED_SOURCE)
60
+ msgspec.convert(data, Nested)
61
+
62
+ err = exc_info.value
63
+ assert str(err) == "config.toml:3:8: Expected `int`, got `str` - at `$.server.port`"
64
+
65
+
66
+ # --- fallback to nearest parent pointer ---
67
+
68
+ FALLBACK_SOURCE = """\
69
+ [server]
70
+ port = 8080
71
+ """
72
+
73
+
74
+ def test_toml_fallback_to_parent():
75
+ # Inject a fake error at a path deeper than the source map tracks.
76
+ # /server/tls/cert doesn't exist; should fall back to /server (line 1).
77
+ with pytest.raises(ParseError) as exc_info:
78
+ with ParseContext("config.toml", data=FALLBACK_SOURCE):
79
+ raise msgspec.ValidationError(
80
+ "Expected `str`, got `int` - at `$.server.tls.cert`"
81
+ )
82
+ assert exc_info.value.line == 1
@@ -0,0 +1,48 @@
1
+ import pytest
2
+ import msgspec
3
+
4
+ from parse_errors import ParseContext, ParseError
5
+
6
+ from ._types import Config, Nested
7
+
8
+ YAML_SOURCE = """\
9
+ host: localhost
10
+ port: not-an-int
11
+ """
12
+
13
+ YAML_NESTED_SOURCE = """\
14
+ server:
15
+ host: localhost
16
+ port: not-an-int
17
+ """
18
+
19
+
20
+ def test_yaml_raises_parse_error():
21
+ with pytest.raises(ParseError) as exc_info:
22
+ with ParseContext("config.yaml", data=YAML_SOURCE):
23
+ msgspec.yaml.decode(YAML_SOURCE.encode(), type=Config)
24
+
25
+ err = exc_info.value
26
+ assert err.filename == "config.yaml"
27
+ assert err.line == 2
28
+ assert str(err) == "config.yaml:2:7: Expected `int`, got `str` - at `$.port`"
29
+
30
+
31
+ def test_yaml_bytes_data():
32
+ with pytest.raises(ParseError) as exc_info:
33
+ with ParseContext("config.yaml", data=YAML_SOURCE.encode()):
34
+ msgspec.yaml.decode(YAML_SOURCE.encode(), type=Config)
35
+
36
+ assert (
37
+ str(exc_info.value)
38
+ == "config.yaml:2:7: Expected `int`, got `str` - at `$.port`"
39
+ )
40
+
41
+
42
+ def test_yaml_nested_raises_parse_error():
43
+ with pytest.raises(ParseError) as exc_info:
44
+ with ParseContext("config.yaml", data=YAML_NESTED_SOURCE):
45
+ msgspec.yaml.decode(YAML_NESTED_SOURCE.encode(), type=Nested)
46
+
47
+ err = exc_info.value
48
+ assert str(err) == "config.yaml:3:9: Expected `int`, got `str` - at `$.server.port`"
@@ -0,0 +1,41 @@
1
+ from parse_errors.source_map import build_source_map, Location, Entry, closest_entry
2
+
3
+
4
+ def test_build_toml():
5
+ # This isn't an exhaustive test of the toml source mapper, just as something
6
+ # a minimal example that lets us exercise str/bytes
7
+ sm1 = build_source_map("x=1\nb='foo'\n", fmt="toml")
8
+ assert sm1 == {
9
+ "": Entry(
10
+ value_start=Location(line=0, column=0, position=0),
11
+ value_end=Location(line=2, column=0, position=12),
12
+ ),
13
+ "/x": Entry(
14
+ value_start=Location(line=0, column=2, position=2),
15
+ value_end=Location(line=0, column=3, position=3),
16
+ key_start=Location(line=0, column=0, position=0),
17
+ key_end=Location(line=0, column=1, position=1),
18
+ ),
19
+ "/b": Entry(
20
+ value_start=Location(line=1, column=2, position=6),
21
+ value_end=Location(line=1, column=7, position=11),
22
+ key_start=Location(line=1, column=0, position=4),
23
+ key_end=Location(line=1, column=1, position=5),
24
+ ),
25
+ }
26
+ sm2 = build_source_map(b"x=1\nb='foo'\n", fmt="toml")
27
+ # Only ASCII, so str vs bytes should be the same
28
+ assert sm1 == sm2
29
+
30
+
31
+ def test_closest_entry():
32
+ sm = {"": "root", "/foo": "foo", "/foo/1": "idx 1", "/foo/1/bar": "bar"}
33
+ assert closest_entry(sm, "/baz") == "root"
34
+ assert closest_entry(sm, "/foo") == "foo"
35
+ assert closest_entry(sm, "/foo/0") == "foo"
36
+ assert closest_entry(sm, "/foo/1") == "idx 1"
37
+
38
+
39
+ def test_closest_entry_fallthrough():
40
+ sm = {}
41
+ assert closest_entry(sm, "/baz") is None