dbrownell-parserlib 0.3.0__tar.gz → 0.5.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.5.0
4
4
  Summary: Functionality useful when creating parsers.
5
5
  Author: Dave Brownell
6
6
  Author-email: Dave Brownell <github@DavidBrownell.com>
@@ -10,6 +10,7 @@ Classifier: Operating System :: Microsoft :: Windows
10
10
  Classifier: Operating System :: POSIX :: Linux
11
11
  Classifier: Programming Language :: Python
12
12
  Classifier: Programming Language :: Python :: 3.14
13
+ Requires-Dist: dbrownell-common>=0.16.8
13
14
  Requires-Python: >=3.14
14
15
  Project-URL: Homepage, https://github.com/davidbrownell/dbrownell_ParserLib
15
16
  Project-URL: Documentation, https://github.com/davidbrownell/dbrownell_ParserLib
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dbrownell-parserlib"
3
- version = "0.3.0"
3
+ version = "0.5.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:
@@ -13,7 +13,9 @@ authors = [
13
13
  { name = "Dave Brownell", email = "github@DavidBrownell.com" }
14
14
  ]
15
15
  requires-python = ">= 3.14"
16
- dependencies = []
16
+ dependencies = [
17
+ "dbrownell-common>=0.16.8",
18
+ ]
17
19
  classifiers = [
18
20
  "Operating System :: MacOS",
19
21
  "Operating System :: Microsoft :: Windows",
@@ -2,12 +2,18 @@
2
2
 
3
3
  from importlib.metadata import version
4
4
 
5
+ from dbrownell_ParserLib.antlr import BuildAntlrGrammar
6
+ from dbrownell_ParserLib.errors import Error, PythonError
5
7
  from dbrownell_ParserLib.location import Location
6
8
  from dbrownell_ParserLib.region import Region
7
9
 
10
+
8
11
  # ----------------------------------------------------------------------
9
12
  __all__ = [
13
+ "BuildAntlrGrammar",
14
+ "Error",
10
15
  "Location",
16
+ "PythonError",
11
17
  "Region",
12
18
  "__version__",
13
19
  ]
@@ -0,0 +1,8 @@
1
+ # noqa: D104
2
+ from dbrownell_ParserLib.antlr.build_antlr_grammar import BuildAntlrGrammar
3
+
4
+
5
+ # ----------------------------------------------------------------------
6
+ __all__ = [
7
+ "BuildAntlrGrammar",
8
+ ]
@@ -0,0 +1,45 @@
1
+ # noqa: D104
2
+ from pathlib import Path
3
+ from typing import TYPE_CHECKING
4
+
5
+ from dbrownell_Common import SubprocessEx
6
+
7
+ if TYPE_CHECKING:
8
+ from dbrownell_Common.Streams.DoneManager import DoneManager
9
+
10
+
11
+ # ----------------------------------------------------------------------
12
+ def BuildAntlrGrammar(
13
+ dm: DoneManager,
14
+ antlr_grammar_filename: Path,
15
+ output_dir: Path,
16
+ *,
17
+ create_init_file: bool = True,
18
+ create_gitignore_file: bool = True,
19
+ ) -> None:
20
+ """Build the Antlr grammar; note that java must be available on the command line."""
21
+
22
+ with dm.Nested(f"Generating '{antlr_grammar_filename.name}'...") as generate_dm:
23
+ jar_filename = Path(__file__).parent / "antlr-4.13.2-complete.jar"
24
+ assert jar_filename.is_file(), jar_filename
25
+
26
+ command_line = f'java -jar "{jar_filename}" -Dlanguage=Python3 -o "{output_dir}" -no-listener -visitor "{antlr_grammar_filename}"'
27
+
28
+ generate_dm.WriteVerbose(f"Command line: {command_line}\n\n")
29
+
30
+ with generate_dm.YieldStream() as stream:
31
+ generate_dm.result = SubprocessEx.Stream(command_line, stream)
32
+ if generate_dm.result != 0:
33
+ return
34
+
35
+ if create_init_file:
36
+ init_filename = output_dir / "__init__.py"
37
+
38
+ if not init_filename.is_file():
39
+ init_filename.touch()
40
+
41
+ if create_gitignore_file:
42
+ gitignore_filename = output_dir / ".gitignore"
43
+
44
+ if not gitignore_filename.is_file():
45
+ gitignore_filename.write_text("*\n")
@@ -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
+ )