dbrownell-parserlib 0.3.0__tar.gz → 0.4.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: dbrownell-parserlib
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Functionality useful when creating parsers.
5
5
  Author: Dave Brownell
6
6
  Author-email: Dave Brownell <github@DavidBrownell.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dbrownell-parserlib"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  # ^^^^^
5
5
  # Wheel names will be generated according to this value. Do not manually modify this value; instead
6
6
  # update it according to committed changes by running this command from the root of the repository:
@@ -2,12 +2,15 @@
2
2
 
3
3
  from importlib.metadata import version
4
4
 
5
+ from dbrownell_ParserLib.errors import Error, PythonError
5
6
  from dbrownell_ParserLib.location import Location
6
7
  from dbrownell_ParserLib.region import Region
7
8
 
8
9
  # ----------------------------------------------------------------------
9
10
  __all__ = [
11
+ "Error",
10
12
  "Location",
13
+ "PythonError",
11
14
  "Region",
12
15
  "__version__",
13
16
  ]
@@ -0,0 +1,112 @@
1
+ """Contains functionality associated with errors and exceptions."""
2
+
3
+ import re
4
+ import textwrap
5
+ import traceback
6
+
7
+ from dataclasses import dataclass, field, InitVar
8
+ from functools import cached_property
9
+ from io import StringIO
10
+ from pathlib import Path
11
+ from typing import Self
12
+
13
+ from dbrownell_ParserLib.region import Location, Region
14
+
15
+
16
+ # ----------------------------------------------------------------------
17
+ @dataclass(frozen=True)
18
+ class Error:
19
+ """Base class for all errors generated by this library."""
20
+
21
+ # ----------------------------------------------------------------------
22
+ message: str
23
+
24
+ region_or_regions: InitVar[Region | list[Region]]
25
+ regions: list[Region] = field(init=False)
26
+
27
+ # ----------------------------------------------------------------------
28
+ def __post_init__(self, region_or_regions: Region | list[Region]) -> None:
29
+ regions = [region_or_regions] if isinstance(region_or_regions, Region) else region_or_regions
30
+
31
+ if not regions:
32
+ msg = "At least one region must be provided"
33
+ raise ValueError(msg)
34
+
35
+ object.__setattr__(self, "regions", regions)
36
+
37
+ # ----------------------------------------------------------------------
38
+ def __str__(self) -> str:
39
+ return self._string
40
+
41
+ # ----------------------------------------------------------------------
42
+ # ----------------------------------------------------------------------
43
+ # ----------------------------------------------------------------------
44
+ @cached_property
45
+ def _string(self) -> str:
46
+ if len(self.regions) == 1 and "\n" not in self.message:
47
+ return f"{self.message} ({self.regions[0]})"
48
+
49
+ return textwrap.dedent(
50
+ """\
51
+ {}
52
+
53
+ {}
54
+ """,
55
+ ).format(self.message.rstrip(), "\n".join(f" - {region}" for region in self.regions))
56
+
57
+
58
+ # ----------------------------------------------------------------------
59
+ @dataclass(frozen=True)
60
+ class PythonError(Error):
61
+ """An `Error` based on a Python exception."""
62
+
63
+ # ----------------------------------------------------------------------
64
+ ex: Exception
65
+
66
+ # ----------------------------------------------------------------------
67
+ @classmethod
68
+ def Create(
69
+ cls,
70
+ ex: Exception,
71
+ ) -> Self:
72
+ """Create a `PythonError` from a Python exception."""
73
+
74
+ regions: list[Region] = []
75
+
76
+ # I haven't been able to find a reliable way to get the exception's callstack so it is being
77
+ # parsed manually here. There has got to be a better way to do this.
78
+ sink = StringIO()
79
+
80
+ traceback.print_exception(ex, file=sink)
81
+ sink_str = sink.getvalue()
82
+
83
+ regex = re.compile(r"^\s*File \"(?P<filename>.+?)\", line (?P<line>\d+),.+$", re.MULTILINE)
84
+
85
+ for line in sink_str.splitlines():
86
+ match = regex.match(line)
87
+ if not match:
88
+ continue
89
+
90
+ line_number = int(match.group("line"))
91
+
92
+ regions.append(
93
+ Region(
94
+ Path(match.group("filename")),
95
+ Location(line_number, 1),
96
+ Location(line_number, 1),
97
+ ),
98
+ )
99
+
100
+ regions.reverse()
101
+
102
+ return cls(
103
+ textwrap.dedent(
104
+ """\
105
+ Python Exception
106
+ ----------------
107
+ {}
108
+ """,
109
+ ).format(str(ex)),
110
+ regions,
111
+ ex,
112
+ )