parser: Tweak parsing during error conditions

When an explicit parsing error is encountered and a CompileError raised,
apply the changes to the context state. This way, the rule that catches
the exception (e.g. Statement or Until) knows where the error occurred.

Also, changed "Expected" errors to be reported at the end of the
previous non-whitespace token.
This commit is contained in:
James Westman 2025-05-03 10:10:06 -05:00
parent e5d6910626
commit 8f3ae9a626
No known key found for this signature in database
GPG key ID: CE2DBA0ADB654EA6
10 changed files with 69 additions and 37 deletions

View file

@ -92,29 +92,38 @@ class CompileError(PrintableError):
def pretty_print(self, filename: str, code: str, stream=sys.stdout) -> None:
assert self.range is not None
line_num, col_num = utils.idx_to_pos(self.range.start + 1, code)
end_line_num, end_col_num = utils.idx_to_pos(self.range.end + 1, code)
line = code.splitlines(True)[line_num] if code != "" else ""
def format_line(range: Range):
line_num, col_num = utils.idx_to_pos(range.start, code)
end_line_num, end_col_num = utils.idx_to_pos(range.end, code)
line = code.splitlines(True)[line_num] if code != "" else ""
# Display 1-based line numbers
line_num += 1
end_line_num += 1
# Display 1-based line numbers
line_num += 1
end_line_num += 1
col_num += 1
end_col_num += 1
n_spaces = col_num - 1
n_carets = (
(end_col_num - col_num)
if line_num == end_line_num
else (len(line) - n_spaces - 1)
)
n_spaces = col_num - 1
n_carets = (
(end_col_num - col_num)
if line_num == end_line_num
else (len(line) - n_spaces - 1)
)
n_spaces += line.count("\t", 0, col_num)
n_carets += line.count("\t", col_num, col_num + n_carets)
line = line.replace("\t", " ")
n_spaces += line.count("\t", 0, col_num)
n_carets += line.count("\t", col_num, col_num + n_carets)
line = line.replace("\t", " ")
n_carets = max(n_carets, 1)
return line_num, col_num, line.rstrip(), (" " * n_spaces) + ("^" * n_carets)
line_num, col_num, line, carets = format_line(self.range)
stream.write(
f"""{self.color}{Colors.BOLD}{self.category}: {self.message}{Colors.CLEAR}
at {filename} line {line_num} column {col_num}:
{Colors.FAINT}{line_num :>4} |{Colors.CLEAR}{line.rstrip()}\n {Colors.FAINT}|{" "*n_spaces}{"^"*n_carets}{Colors.CLEAR}\n"""
{Colors.FAINT}{line_num :>4} |{Colors.CLEAR}{line}\n {Colors.FAINT}|{carets}{Colors.CLEAR}\n"""
)
for hint in self.hints:
@ -139,14 +148,12 @@ at {filename} line {line_num} column {col_num}:
)
for ref in self.references:
line_num, col_num = utils.idx_to_pos(ref.range.start + 1, code)
line = code.splitlines(True)[line_num]
line_num += 1
line_num, col_num, line, carets = format_line(ref.range)
stream.write(
f"""{Colors.FAINT}note: {ref.message}:
at {filename} line {line_num} column {col_num}:
{Colors.FAINT}{line_num :>4} |{line.rstrip()}\n {Colors.FAINT}|{" "*(col_num-1)}^{Colors.CLEAR}\n"""
{Colors.FAINT}{line_num :>4} |{line}\n {Colors.FAINT}|{carets}{Colors.CLEAR}\n"""
)
stream.write("\n")