diff --git a/.github/workflows/doc.yml b/.github/workflows/doc.yml index 519884177f64ac..ca4476c5090129 100644 --- a/.github/workflows/doc.yml +++ b/.github/workflows/doc.yml @@ -40,7 +40,7 @@ jobs: - name: 'Build documentation' run: xvfb-run make -C Doc/ PYTHON=../python SPHINXOPTS="-q -W --keep-going -j4" doctest html - name: 'Upload' - uses: actions/upload-artifact@v2.2.3 + uses: actions/upload-artifact@v2.2.4 with: name: doc-html path: Doc/build/html diff --git a/Doc/c-api/code.rst b/Doc/c-api/code.rst index 6e18a4225e8f43..2b0cdf43243405 100644 --- a/Doc/c-api/code.rst +++ b/Doc/c-api/code.rst @@ -59,3 +59,11 @@ bound into a function. For efficiently iterating over the line numbers in a code object, use `the API described in PEP 626 `_. + +.. c:function:: int PyCode_Addr2Location(PyObject *co, int byte_offset, int *start_line, int *start_column, int *end_line, int *end_column) + + Sets the passed ``int`` pointers to the source code line and column numbers + for the instruction at ``byte_offset``. Sets the value to ``0`` when + information is not available for any particular element. + + Returns ``1`` if the function succeeds and 0 otherwise. diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index b2eb9eff914c69..a1b4bd0fcfd170 100644 --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -853,6 +853,8 @@ is available in ``argparse`` and adds support for boolean actions such as >>> parser.parse_args(['--no-foo']) Namespace(foo=False) +.. versionadded:: 3.9 + The recommended way to create a custom action is to extend :class:`Action`, overriding the ``__call__`` method and optionally the ``__init__`` and ``format_usage`` methods. diff --git a/Doc/library/importlib.metadata.rst b/Doc/library/importlib.metadata.rst index 9bedee5af28f69..c43457a3850678 100644 --- a/Doc/library/importlib.metadata.rst +++ b/Doc/library/importlib.metadata.rst @@ -8,13 +8,11 @@ :synopsis: The implementation of the importlib metadata. .. versionadded:: 3.8 +.. versionchanged:: 3.10 + ``importlib.metadata`` is no longer provisional. **Source code:** :source:`Lib/importlib/metadata.py` -.. note:: - This functionality is provisional and may deviate from the usual - version semantics of the standard library. - ``importlib.metadata`` is a library that provides for access to installed package metadata. Built in part on Python's import system, this library intends to replace similar functionality in the `entry point diff --git a/Doc/library/os.path.rst b/Doc/library/os.path.rst index d06d9ce8c9e3d7..e2f43424df15e1 100644 --- a/Doc/library/os.path.rst +++ b/Doc/library/os.path.rst @@ -340,6 +340,14 @@ the :mod:`glob` module.) that contains symbolic links. On Windows, it converts forward slashes to backward slashes. To normalize case, use :func:`normcase`. + .. note:: + On POSIX systems, in accordance with `IEEE Std 1003.1 2013 Edition; 4.13 + Pathname Resolution `_, + if a pathname begins with exactly two slashes, the first component + following the leading characters may be interpreted in an implementation-defined + manner, although more than two leading characters shall be treated as a + single character. + .. versionchanged:: 3.6 Accepts a :term:`path-like object`. diff --git a/Doc/library/traceback.rst b/Doc/library/traceback.rst index 1961b9a435bd35..be1f43ea953edb 100644 --- a/Doc/library/traceback.rst +++ b/Doc/library/traceback.rst @@ -473,7 +473,7 @@ The output for the example would look similar to this: ['Traceback (most recent call last):\n', ' File "", line 10, in \n lumberjack()\n ^^^^^^^^^^^^\n', ' File "", line 4, in lumberjack\n bright_side_of_death()\n ^^^^^^^^^^^^^^^^^^^^^^\n', - ' File "", line 7, in bright_side_of_death\n return tuple()[0]\n ^^^^^^^^^^\n', + ' File "", line 7, in bright_side_of_death\n return tuple()[0]\n ~~~~~~~^^^\n', 'IndexError: tuple index out of range\n'] *** extract_tb: [, line 10 in >, @@ -482,7 +482,7 @@ The output for the example would look similar to this: *** format_tb: [' File "", line 10, in \n lumberjack()\n ^^^^^^^^^^^^\n', ' File "", line 4, in lumberjack\n bright_side_of_death()\n ^^^^^^^^^^^^^^^^^^^^^^\n', - ' File "", line 7, in bright_side_of_death\n return tuple()[0]\n ^^^^^^^^^^\n'] + ' File "", line 7, in bright_side_of_death\n return tuple()[0]\n ~~~~~~~^^^\n'] *** tb_lineno: 10 diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index b6dae810d781b7..bb0b7e059f132d 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1015,6 +1015,39 @@ Internal types If a code object represents a function, the first item in :attr:`co_consts` is the documentation string of the function, or ``None`` if undefined. + .. method:: codeobject.co_positions() + + Returns an iterable over the source code positions of each bytecode + instruction in the code object. + + The iterator returns tuples containing the ``(start_line, end_line, + start_column, end_column)``. The *i-th* tuple corresponds to the + position of the source code that compiled to the *i-th* instruction. + Column information is 0-indexed utf-8 byte offsets on the given source + line. + + This positional information can be missing. A non-exhaustive lists of + cases where this may happen: + + - Running the interpreter with :option:`-X` ``no_debug_ranges``. + - Loading a pyc file compiled while using :option:`-X` ``no_debug_ranges``. + - Position tuples corresponding to artificial instructions. + - Line and column numbers that can't be represented due to + implementation specific limitations. + + When this occurs, some or all of the tuple elements can be + :const:`None`. + + .. versionadded:: 3.11 + + .. note:: + This feature requires storing column positions in code objects which may + result in a small increase of disk usage of compiled Python files or + interpreter memory usage. To avoid storing the extra information and/or + deactivate printing the extra traceback information, the + :option:`-X` ``no_debug_ranges`` command line flag or the :envvar:`PYTHONNODEBUGRANGES` + environment variable can be used. + .. _frame-objects: Frame objects diff --git a/Doc/whatsnew/3.11.rst b/Doc/whatsnew/3.11.rst index bfadda1a881f2e..57e9667c15776d 100644 --- a/Doc/whatsnew/3.11.rst +++ b/Doc/whatsnew/3.11.rst @@ -70,6 +70,83 @@ Summary -- Release highlights New Features ============ +.. _whatsnew311-pep657: + +Enhanced error locations in tracebacks +-------------------------------------- + +When printing tracebacks, the interpreter will now point to the exact expression +that caused the error instead of just the line. For example: + +.. code-block:: python + + Traceback (most recent call last): + File "distance.py", line 11, in + print(manhattan_distance(p1, p2)) + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + File "distance.py", line 6, in manhattan_distance + return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y) + ^^^^^^^^^ + AttributeError: 'NoneType' object has no attribute 'x' + +Previous versions of the interpreter would point to just the line making it +ambiguous which object was ``None``. These enhanced errors can also be helpful +when dealing with deeply nested dictionary objects and multiple function calls, + +.. code-block:: python + + Traceback (most recent call last): + File "query.py", line 37, in + magic_arithmetic('foo') + ^^^^^^^^^^^^^^^^^^^^^^^ + File "query.py", line 18, in magic_arithmetic + return add_counts(x) / 25 + ^^^^^^^^^^^^^ + File "query.py", line 24, in add_counts + return 25 + query_user(user1) + query_user(user2) + ^^^^^^^^^^^^^^^^^ + File "query.py", line 32, in query_user + return 1 + query_count(db, response['a']['b']['c']['user'], retry=True) + ~~~~~~~~~~~~~~~~~~^^^^^ + TypeError: 'NoneType' object is not subscriptable + +as well as complex arithmetic expressions: + +.. code-block:: python + + Traceback (most recent call last): + File "calculation.py", line 54, in + result = (x / y / z) * (a / b / c) + ~~~~~~^~~ + ZeroDivisionError: division by zero + +See :pep:`657` for more details. (Contributed by Pablo Galindo, Batuhan Taskaya +and Ammar Askar in :issue:`43950`.) + +.. note:: + This feature requires storing column positions in code objects which may + result in a small increase of disk usage of compiled Python files or + interpreter memory usage. To avoid storing the extra information and/or + deactivate printing the extra traceback information, the + :option:`-X` ``no_debug_ranges`` command line flag or the :envvar:`PYTHONNODEBUGRANGES` + environment variable can be used. + +Column information for code objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The information used by the enhanced traceback feature is made available as a +general API that can be used to correlate bytecode instructions with source +code. This information can be retrieved using: + +- The :meth:`codeobject.co_positions` method in Python. +- The :c:func:`PyCode_Addr2Location` function in the C-API. + +The :option:`-X` ``no_debug_ranges`` option and the environment variable +:envvar:`PYTHONNODEBUGRANGES` can be used to disable this feature. + +See :pep:`657` for more details. (Contributed by Pablo Galindo, Batuhan Taskaya +and Ammar Askar in :issue:`43950`.) + Other Language Changes diff --git a/Lib/posixpath.py b/Lib/posixpath.py index 259baa64b193b8..195374613a779f 100644 --- a/Lib/posixpath.py +++ b/Lib/posixpath.py @@ -352,6 +352,7 @@ def normpath(path): initial_slashes = path.startswith(sep) # POSIX allows one or two initial slashes, but treats three or more # as single slash. + # (see http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13) if (initial_slashes and path.startswith(sep*2) and not path.startswith(sep*3)): initial_slashes = 2 diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index 50ebccef82a3fa..8baf38c1afd5d6 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -12,9 +12,11 @@ requires_debug_ranges, has_no_debug_ranges) from test.support.os_helper import TESTFN, unlink from test.support.script_helper import assert_python_ok, assert_python_failure -import textwrap +import os +import textwrap import traceback +from functools import partial test_code = namedtuple('code', ['co_filename', 'co_name']) @@ -406,6 +408,82 @@ def f_with_multiline(): result_lines = self.get_exception(f_with_multiline) self.assertEqual(result_lines, expected_f.splitlines()) + def test_caret_for_binary_operators(self): + def f_with_binary_operator(): + divisor = 20 + return 10 + divisor / 0 + 30 + + lineno_f = f_with_binary_operator.__code__.co_firstlineno + expected_error = ( + 'Traceback (most recent call last):\n' + f' File "{__file__}", line {self.callable_line}, in get_exception\n' + ' callable()\n' + ' ^^^^^^^^^^\n' + f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n' + ' return 10 + divisor / 0 + 30\n' + ' ~~~~~~~~^~~\n' + ) + result_lines = self.get_exception(f_with_binary_operator) + self.assertEqual(result_lines, expected_error.splitlines()) + + def test_caret_for_binary_operators_two_char(self): + def f_with_binary_operator(): + divisor = 20 + return 10 + divisor // 0 + 30 + + lineno_f = f_with_binary_operator.__code__.co_firstlineno + expected_error = ( + 'Traceback (most recent call last):\n' + f' File "{__file__}", line {self.callable_line}, in get_exception\n' + ' callable()\n' + ' ^^^^^^^^^^\n' + f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n' + ' return 10 + divisor // 0 + 30\n' + ' ~~~~~~~~^^~~\n' + ) + result_lines = self.get_exception(f_with_binary_operator) + self.assertEqual(result_lines, expected_error.splitlines()) + + def test_caret_for_subscript(self): + def f_with_subscript(): + some_dict = {'x': {'y': None}} + return some_dict['x']['y']['z'] + + lineno_f = f_with_subscript.__code__.co_firstlineno + expected_error = ( + 'Traceback (most recent call last):\n' + f' File "{__file__}", line {self.callable_line}, in get_exception\n' + ' callable()\n' + ' ^^^^^^^^^^\n' + f' File "{__file__}", line {lineno_f+2}, in f_with_subscript\n' + " return some_dict['x']['y']['z']\n" + ' ~~~~~~~~~~~~~~~~~~~^^^^^\n' + ) + result_lines = self.get_exception(f_with_subscript) + self.assertEqual(result_lines, expected_error.splitlines()) + + def test_traceback_specialization_with_syntax_error(self): + bytecode = compile("1 / 0 / 1 / 2\n", TESTFN, "exec") + + with open(TESTFN, "w") as file: + # make the file's contents invalid + file.write("1 $ 0 / 1 / 2\n") + self.addCleanup(unlink, TESTFN) + + func = partial(exec, bytecode) + result_lines = self.get_exception(func) + + lineno_f = bytecode.co_firstlineno + expected_error = ( + 'Traceback (most recent call last):\n' + f' File "{__file__}", line {self.callable_line}, in get_exception\n' + ' callable()\n' + ' ^^^^^^^^^^\n' + f' File "{TESTFN}", line {lineno_f}, in \n' + " 1 $ 0 / 1 / 2\n" + ' ^^^^^\n' + ) + self.assertEqual(result_lines, expected_error.splitlines()) @cpython_only @requires_debug_ranges() @@ -1615,7 +1693,7 @@ def f(): self.assertEqual( output.getvalue().split('\n')[-5:], [' x/0', - ' ^^^', + ' ~^~', ' x = 12', 'ZeroDivisionError: division by zero', '']) diff --git a/Lib/traceback.py b/Lib/traceback.py index 7cb124188aca8a..ec5e20d431feb8 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -494,9 +494,23 @@ def format(self): colno = _byte_offset_to_character_offset(frame._original_line, frame.colno) end_colno = _byte_offset_to_character_offset(frame._original_line, frame.end_colno) + try: + anchors = _extract_caret_anchors_from_line_segment( + frame._original_line[colno - 1:end_colno] + ) + except Exception: + anchors = None + row.append(' ') row.append(' ' * (colno - stripped_characters)) - row.append('^' * (end_colno - colno)) + + if anchors: + row.append(anchors.primary_char * (anchors.left_end_offset)) + row.append(anchors.secondary_char * (anchors.right_start_offset - anchors.left_end_offset)) + row.append(anchors.primary_char * (end_colno - colno - anchors.right_start_offset)) + else: + row.append('^' * (end_colno - colno)) + row.append('\n') if frame.locals: @@ -520,6 +534,50 @@ def _byte_offset_to_character_offset(str, offset): return len(as_utf8[:offset + 1].decode("utf-8")) +_Anchors = collections.namedtuple( + "_Anchors", + [ + "left_end_offset", + "right_start_offset", + "primary_char", + "secondary_char", + ], + defaults=["~", "^"] +) + +def _extract_caret_anchors_from_line_segment(segment): + import ast + + try: + tree = ast.parse(segment) + except SyntaxError: + return None + + if len(tree.body) != 1: + return None + + statement = tree.body[0] + match statement: + case ast.Expr(expr): + match expr: + case ast.BinOp(): + operator_str = segment[expr.left.end_col_offset:expr.right.col_offset] + operator_offset = len(operator_str) - len(operator_str.lstrip()) + + left_anchor = expr.left.end_col_offset + operator_offset + right_anchor = left_anchor + 1 + if ( + operator_offset + 1 < len(operator_str) + and not operator_str[operator_offset + 1].isspace() + ): + right_anchor += 1 + return _Anchors(left_anchor, right_anchor) + case ast.Subscript(): + return _Anchors(expr.value.end_col_offset, expr.slice.end_col_offset + 1) + + return None + + class TracebackException: """An exception ready for rendering. diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-07-06-15-27-11.bpo-43950.LhL2-q.rst b/Misc/NEWS.d/next/Core and Builtins/2021-07-06-15-27-11.bpo-43950.LhL2-q.rst new file mode 100644 index 00000000000000..dde5399626b7ef --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2021-07-06-15-27-11.bpo-43950.LhL2-q.rst @@ -0,0 +1,6 @@ +Code objects can now provide the column information for instructions when +available. This is levaraged during traceback printing to show the +expressions responsible for errors. + +Contributed by Pablo Galindo, Batuhan Taskaya and Ammar Askar as part of +:pep:`657`. diff --git a/Misc/NEWS.d/next/Documentation/2021-07-12-11-39-20.bpo-44613.DIXNzc.rst b/Misc/NEWS.d/next/Documentation/2021-07-12-11-39-20.bpo-44613.DIXNzc.rst new file mode 100644 index 00000000000000..baf591073620c8 --- /dev/null +++ b/Misc/NEWS.d/next/Documentation/2021-07-12-11-39-20.bpo-44613.DIXNzc.rst @@ -0,0 +1 @@ +importlib.metadata is no longer provisional. diff --git a/Python/traceback.c b/Python/traceback.c index a60f9916424337..199d3ea7596bf8 100644 --- a/Python/traceback.c +++ b/Python/traceback.c @@ -7,6 +7,10 @@ #include "pycore_interp.h" // PyInterpreterState.gc #include "frameobject.h" // PyFrame_GetBack() #include "pycore_frame.h" // _PyFrame_GetCode() +#include "pycore_pyarena.h" // _PyArena_Free() +#include "pycore_ast.h" // asdl_seq_* +#include "pycore_compile.h" // _PyAST_Optimize +#include "pycore_parser.h" // _PyParser_ASTFromString #include "../Parser/pegen.h" // _PyPegen_byte_offset_to_character_offset() #include "structmember.h" // PyMemberDef #include "osdefs.h" // SEP @@ -512,8 +516,172 @@ _Py_DisplaySourceLine(PyObject *f, PyObject *filename, int lineno, int indent, i return err; } +/* AST based Traceback Specialization + * + * When displaying a new traceback line, for certain syntactical constructs + * (e.g a subscript, an arithmetic operation) we try to create a representation + * that separates the primary source of error from the rest. + * + * Example specialization of BinOp nodes: + * Traceback (most recent call last): + * File "/home/isidentical/cpython/cpython/t.py", line 10, in + * add_values(1, 2, 'x', 3, 4) + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * File "/home/isidentical/cpython/cpython/t.py", line 2, in add_values + * return a + b + c + d + e + * ~~~~~~^~~ + * TypeError: 'NoneType' object is not subscriptable + */ + +#define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\f')) + +static int +extract_anchors_from_expr(const char *segment_str, expr_ty expr, Py_ssize_t *left_anchor, Py_ssize_t *right_anchor, + char** primary_error_char, char** secondary_error_char) +{ + switch (expr->kind) { + case BinOp_kind: { + expr_ty left = expr->v.BinOp.left; + expr_ty right = expr->v.BinOp.right; + for (int i = left->end_col_offset + 1; i < right->col_offset; i++) { + if (IS_WHITESPACE(segment_str[i])) { + continue; + } + + *left_anchor = i; + *right_anchor = i + 1; + + // Check whether if this a two-character operator (e.g //) + if (i + 1 < right->col_offset && !IS_WHITESPACE(segment_str[i + 1])) { + ++*right_anchor; + } + + // Set the error characters + *primary_error_char = "~"; + *secondary_error_char = "^"; + break; + } + return 1; + } + case Subscript_kind: { + *left_anchor = expr->v.Subscript.value->end_col_offset; + *right_anchor = expr->v.Subscript.slice->end_col_offset + 1; + + // Set the error characters + *primary_error_char = "~"; + *secondary_error_char = "^"; + return 1; + } + default: + return 0; + } +} + +static int +extract_anchors_from_stmt(const char *segment_str, stmt_ty statement, Py_ssize_t *left_anchor, Py_ssize_t *right_anchor, + char** primary_error_char, char** secondary_error_char) +{ + switch (statement->kind) { + case Expr_kind: { + return extract_anchors_from_expr(segment_str, statement->v.Expr.value, left_anchor, right_anchor, + primary_error_char, secondary_error_char); + } + default: + return 0; + } +} + +static int +extract_anchors_from_line(PyObject *filename, PyObject *line, + Py_ssize_t start_offset, Py_ssize_t end_offset, + Py_ssize_t *left_anchor, Py_ssize_t *right_anchor, + char** primary_error_char, char** secondary_error_char) +{ + int res = -1; + PyArena *arena = NULL; + PyObject *segment = PyUnicode_Substring(line, start_offset, end_offset); + if (!segment) { + goto done; + } + + const char *segment_str = PyUnicode_AsUTF8(segment); + if (!segment) { + goto done; + } + + arena = _PyArena_New(); + if (!arena) { + goto done; + } + + PyCompilerFlags flags = _PyCompilerFlags_INIT; + + _PyASTOptimizeState state; + state.optimize = _Py_GetConfig()->optimization_level; + state.ff_features = 0; + + mod_ty module = _PyParser_ASTFromString(segment_str, filename, Py_file_input, + &flags, arena); + if (!module) { + goto done; + } + if (!_PyAST_Optimize(module, arena, &state)) { + goto done; + } + + assert(module->kind == Module_kind); + if (asdl_seq_LEN(module->v.Module.body) == 1) { + stmt_ty statement = asdl_seq_GET(module->v.Module.body, 0); + res = extract_anchors_from_stmt(segment_str, statement, left_anchor, right_anchor, + primary_error_char, secondary_error_char); + } else { + res = 0; + } + +done: + if (res > 0) { + *left_anchor += start_offset; + *right_anchor += start_offset; + } + Py_XDECREF(segment); + if (arena) { + _PyArena_Free(arena); + } + return res; +} + #define _TRACEBACK_SOURCE_LINE_INDENT 4 +static inline int +ignore_source_errors(void) { + if (PyErr_Occurred()) { + if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) { + return -1; + } + PyErr_Clear(); + } + return 0; +} + +static inline int +print_error_location_carets(PyObject *f, int offset, Py_ssize_t start_offset, Py_ssize_t end_offset, + Py_ssize_t right_start_offset, Py_ssize_t left_end_offset, + const char *primary, const char *secondary) { + int err = 0; + int special_chars = (left_end_offset != -1 || right_start_offset != -1); + while (++offset <= end_offset) { + if (offset <= start_offset || offset > end_offset) { + err = PyFile_WriteString(" ", f); + } else if (special_chars && left_end_offset < offset && offset <= right_start_offset) { + err = PyFile_WriteString(secondary, f); + } else { + err = PyFile_WriteString(primary, f); + } + } + err = PyFile_WriteString("\n", f); + return err; +} + static int tb_displayline(PyTracebackObject* tb, PyObject *f, PyObject *filename, int lineno, PyFrameObject *frame, PyObject *name) @@ -533,52 +701,68 @@ tb_displayline(PyTracebackObject* tb, PyObject *f, PyObject *filename, int linen return err; int truncation = _TRACEBACK_SOURCE_LINE_INDENT; PyObject* source_line = NULL; - /* ignore errors since we can't report them, can we? */ - if (!_Py_DisplaySourceLine(f, filename, lineno, _TRACEBACK_SOURCE_LINE_INDENT, - &truncation, &source_line)) { - int code_offset = tb->tb_lasti; - PyCodeObject* code = _PyFrame_GetCode(frame); - - int start_line; - int end_line; - int start_col_byte_offset; - int end_col_byte_offset; - if (!PyCode_Addr2Location(code, code_offset, &start_line, &start_col_byte_offset, - &end_line, &end_col_byte_offset)) { - goto done; - } - if (start_line != end_line) { - goto done; - } - if (start_col_byte_offset < 0 || end_col_byte_offset < 0) { - goto done; - } - // Convert the utf-8 byte offset to the actual character offset so we - // print the right number of carets. - Py_ssize_t start_offset = _PyPegen_byte_offset_to_character_offset(source_line, start_col_byte_offset); - Py_ssize_t end_offset = _PyPegen_byte_offset_to_character_offset(source_line, end_col_byte_offset); + if (_Py_DisplaySourceLine(f, filename, lineno, _TRACEBACK_SOURCE_LINE_INDENT, + &truncation, &source_line) != 0) { + /* ignore errors since we can't report them, can we? */ + err = ignore_source_errors(); + goto done; + } - char offset = truncation; - while (++offset <= start_offset) { - err = PyFile_WriteString(" ", f); - if (err < 0) { - goto done; - } - } - while (++offset <= end_offset + 1) { - err = PyFile_WriteString("^", f); - if (err < 0) { - goto done; - } - } - err = PyFile_WriteString("\n", f); + int code_offset = tb->tb_lasti; + PyCodeObject* code = _PyFrame_GetCode(frame); + + int start_line; + int end_line; + int start_col_byte_offset; + int end_col_byte_offset; + if (!PyCode_Addr2Location(code, code_offset, &start_line, &start_col_byte_offset, + &end_line, &end_col_byte_offset)) { + goto done; + } + if (start_line != end_line) { + goto done; } - else { - PyErr_Clear(); + if (start_col_byte_offset < 0 || end_col_byte_offset < 0) { + goto done; } - + + // When displaying errors, we will use the following generic structure: + // + // ERROR LINE ERROR LINE ERROR LINE ERROR LINE ERROR LINE ERROR LINE ERROR LINE + // ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^~~~~~~~~~~~~~~~~~~~ + // | |-> left_end_offset | |-> left_offset + // |-> start_offset |-> right_start_offset + // + // In general we will only have (start_offset, end_offset) but we can gather more information + // by analyzing the AST of the text between *start_offset* and *end_offset*. If this succeeds + // we could get *left_end_offset* and *right_start_offset* and some selection of characters for + // the different ranges (primary_error_char and secondary_error_char). If we cannot obtain the + // AST information or we cannot identify special ranges within it, then left_end_offset and + // right_end_offset will be set to -1. + + // Convert the utf-8 byte offset to the actual character offset so we print the right number of carets. + assert(source_line); + Py_ssize_t start_offset = _PyPegen_byte_offset_to_character_offset(source_line, start_col_byte_offset); + Py_ssize_t end_offset = _PyPegen_byte_offset_to_character_offset(source_line, end_col_byte_offset); + Py_ssize_t left_end_offset = -1; + Py_ssize_t right_start_offset = -1; + + char *primary_error_char = "^"; + char *secondary_error_char = primary_error_char; + + int res = extract_anchors_from_line(filename, source_line, start_offset, end_offset, + &left_end_offset, &right_start_offset, + &primary_error_char, &secondary_error_char); + if (res < 0 && ignore_source_errors() < 0) { + goto done; + } + + err = print_error_location_carets(f, truncation, start_offset, end_offset, + right_start_offset, left_end_offset, + primary_error_char, secondary_error_char); + done: Py_XDECREF(source_line); return err;