Merge pull request #38 from idle-org/features/context

Added a better context to error
This commit is contained in:
Maximilien Rigaut 2022-06-16 03:39:34 +02:00 committed by GitHub
commit 4bfd730616
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 58 additions and 6 deletions

View File

@ -208,7 +208,7 @@ class BaseContainer:
:rtype : str
"""
return '{} ({})'.format(", ".join(map(str, self.content)),
", ".join(map(str, self.get_optionals())) if self.get_optionals() else "")
", ".join(map(str, self.get_optionals().content)) if self.get_optionals() else "")
def __repr__(self):
"""
@ -551,6 +551,7 @@ class ContextManager:
while index < len(self.parsed_list):
token = self.parsed_list[index]
token.line_number = line_number
token.index = index
token.file_name = self.name
token.ident = self.ident
self.pile.append(token)
@ -583,16 +584,17 @@ class ContextManager:
# Error if closing token does not have a start
elif isinstance(token, syntax.ClosedSemanticType):
raise MismatchedContainerError(token)
raise MismatchedContainerError(token, self.parsed_list)
# Starting token by default (can cause unintended behaviours on bad implementations)
elif isinstance(token, syntax.TokensToMatch):
self._add_matched(token.label, index)
else:
raise MismatchedContainerError(token)
raise MismatchedContainerError(token, self.parsed_list)
except MismatchedContainerError as e:
error_mngr.log_message(f"In context: {e.get_context()}", level="CRITICAL")
error_mngr.log_exception(e, level="CRITICAL") # FUTURE: Try to guess some hints.
index += 1

View File

@ -95,6 +95,54 @@ class BootstraparseError(Exception):
pass
class BootstraparseTokenError(BootstraparseError):
"""
Error on a token, provides if possible the line and column number of the error,
the file name and the message of the error
and if possible a context for the error
"""
def __init__(self, token, pile, message):
self.token = token
self.pile = pile
if token is not None:
self.line = token.line_number
self.index = token.index
self.label = token.label
self.name = token.file_name
else:
self.line = None
self.index = None
self.label = None
self.name = None
self.context = self.get_context()
super().__init__(message+"\n"+self.context_multiline())
def get_context(self, context_size=5):
"""
Returns the context of the error
:return: The context of the error
:rtype: str
"""
if self.pile:
st = max(0, self.index - context_size)
en = min(len(self.pile), self.index + context_size)
return self.pile[st:en]
return []
def context_multiline(self, context_size=10):
"""
Returns the context of the error as a multiline string
:return: The context of the error
:rtype: str
"""
if self.pile:
return "\n".join([
f"{' ' if i!=context_size else '> '}{i-context_size:2d}: {j}"
for i, j in enumerate(self.get_context(context_size)) if j.label != "linebreak"
])
return ""
class ParsingError(Exception):
"""
Exception class for parsing errors
@ -133,17 +181,18 @@ class ParsingError(Exception):
return str(self.message)
class MismatchedContainerError(BootstraparseError):
class MismatchedContainerError(BootstraparseTokenError):
"""
The token is not final and cannot be contained. Indicative of a mismatched token.
"""
def __init__(self, token):
def __init__(self, token, pile=None):
"""
Initializes the MismatchedContainerError class with the token that was not final
:param token: The token that is not final
:type token: syntax.SemanticType
"""
self.token = token
self.pile = pile
if token:
self.line = token.line_number
self.label = token.label
@ -152,7 +201,7 @@ class MismatchedContainerError(BootstraparseError):
self.line = None
self.label = None
self.name = None
super().__init__(f"Could not process {self.label} at line {self.line} in file {self.name}.")
super().__init__(token, pile, f"Could not process {self.label} at line {self.line} in file {self.name}.")
class LonelyOptionalError(BootstraparseError):

View File

@ -47,6 +47,7 @@ def test_counterpart_container(type_n, expected_counterpart, expected_container,
try:
token = type_n(["test"]) # noqa
token.line_number = 1
token.index = 1
assert token.counterpart() == expected_counterpart
if expected_container == "error":
with pytest.raises(error_mngr.MismatchedContainerError):