From 86891e9e8638268bfc234ab2f78a74daec00ddd3 Mon Sep 17 00:00:00 2001 From: Maximilien Rigaut Date: Thu, 16 Jun 2022 03:38:27 +0200 Subject: [PATCH] Added a better context to error --- src/bootstraparse/modules/context_mngr.py | 8 ++-- src/bootstraparse/modules/error_mngr.py | 55 +++++++++++++++++++++-- tests/modules/test_syntax_context.py | 1 + 3 files changed, 58 insertions(+), 6 deletions(-) diff --git a/src/bootstraparse/modules/context_mngr.py b/src/bootstraparse/modules/context_mngr.py index 47e661b..fa787bc 100644 --- a/src/bootstraparse/modules/context_mngr.py +++ b/src/bootstraparse/modules/context_mngr.py @@ -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 diff --git a/src/bootstraparse/modules/error_mngr.py b/src/bootstraparse/modules/error_mngr.py index 501e59a..3f08ce4 100644 --- a/src/bootstraparse/modules/error_mngr.py +++ b/src/bootstraparse/modules/error_mngr.py @@ -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): diff --git a/tests/modules/test_syntax_context.py b/tests/modules/test_syntax_context.py index 928308c..21e1d75 100644 --- a/tests/modules/test_syntax_context.py +++ b/tests/modules/test_syntax_context.py @@ -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):