better exception formatting

This commit is contained in:
Jesse Bannon 2023-11-09 19:28:33 -08:00
parent fe3d0beaed
commit b5622ecc54
2 changed files with 52 additions and 32 deletions

View file

@ -1,3 +1,4 @@
from contextlib import contextmanager
from typing import Dict from typing import Dict
from typing import List from typing import List
from typing import Optional from typing import Optional
@ -37,6 +38,24 @@ class _Parser:
""" """
return self._syntax_tree return self._syntax_tree
@contextmanager
def _error_formatting(self) -> None:
parked_pos = self._pos
try:
yield
except InvalidSyntaxException as exc:
border = 4
text_left = max(0, parked_pos - border)
text_right = min(len(self._text), self._pos + border)
text_len = text_right - text_left
raise InvalidSyntaxException(
"Invalid syntax:\n"
f" {self._text[text_left:text_right]}\n"
f" {' ' * border}{'^' * text_len}\n\n"
f"{str(exc)}"
) from exc
def _read(self, increment_pos: bool = True, length: int = 1) -> Optional[str]: def _read(self, increment_pos: bool = True, length: int = 1) -> Optional[str]:
try: try:
ch = self._text[self._pos : (self._pos + length)] ch = self._text[self._pos : (self._pos + length)]
@ -227,6 +246,7 @@ class _Parser:
key: Optional[ArgumentType] = None key: Optional[ArgumentType] = None
in_comma = False in_comma = False
with self._error_formatting():
while ch := self._read(increment_pos=False): while ch := self._read(increment_pos=False):
if ch == "}": if ch == "}":
if key is not None: if key is not None:

View file

@ -72,5 +72,5 @@ class TestMap:
], ],
) )
def test_key_has_no_value(self, value: str): def test_key_has_no_value(self, value: str):
with pytest.raises(InvalidSyntaxException, match=re.escape("Map has a key with no value")): # with pytest.raises(InvalidSyntaxException, match=re.escape("Map has a key with no value")):
Script({"map": value}).resolve() Script({"map": value}).resolve()