Skip to content

Commit 0acdf25

Browse files
authored
[3.10] bpo-43933: Force RETURN_VALUE bytecodes to have line numbers (GH-26061)
* Guarantee that line number is set for returns.
1 parent 2d972b8 commit 0acdf25

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

Lib/test/test_sys_settrace.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -976,6 +976,26 @@ class A:
976976
(3, 'return'),
977977
(1, 'return')])
978978

979+
def test_try_in_try(self):
980+
def func():
981+
try:
982+
try:
983+
pass
984+
except Exception as ex:
985+
pass
986+
except Exception:
987+
pass
988+
989+
# This doesn't conform to PEP 626
990+
self.run_and_compare(func,
991+
[(0, 'call'),
992+
(1, 'line'),
993+
(2, 'line'),
994+
(3, 'line'),
995+
(5, 'line'),
996+
(5, 'return')])
997+
998+
979999
class SkipLineEventsTraceTestCase(TraceTestCase):
9801000
"""Repeat the trace tests, but with per-line events skipped"""
9811001

@@ -1647,6 +1667,7 @@ async def test_no_jump_forwards_into_async_for_block(output):
16471667
output.append(1)
16481668
async for i in asynciter([1, 2]):
16491669
output.append(3)
1670+
pass
16501671

16511672
@jump_test(3, 2, [2, 2], (ValueError, 'into'))
16521673
def test_no_jump_backwards_into_for_block(output):

Python/compile.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6960,6 +6960,34 @@ insert_generator_prefix(struct compiler *c, basicblock *entryblock) {
69606960
return 0;
69616961
}
69626962

6963+
/* Make sure that all returns have a line number, even if early passes
6964+
* have failed to propagate a correct line number.
6965+
* The resulting line number may not be correct according to PEP 626,
6966+
* but should be "good enough", and no worse than in older versions. */
6967+
static void
6968+
guarantee_lineno_for_exits(struct assembler *a, int firstlineno) {
6969+
int lineno = firstlineno;
6970+
assert(lineno > 0);
6971+
for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6972+
if (b->b_iused == 0) {
6973+
continue;
6974+
}
6975+
struct instr *last = &b->b_instr[b->b_iused-1];
6976+
if (last->i_lineno < 0) {
6977+
if (last->i_opcode == RETURN_VALUE)
6978+
{
6979+
for (int i = 0; i < b->b_iused; i++) {
6980+
assert(b->b_instr[i].i_lineno < 0);
6981+
b->b_instr[i].i_lineno = lineno;
6982+
}
6983+
}
6984+
}
6985+
else {
6986+
lineno = last->i_lineno;
6987+
}
6988+
}
6989+
}
6990+
69636991
static PyCodeObject *
69646992
assemble(struct compiler *c, int addNone)
69656993
{
@@ -7022,6 +7050,7 @@ assemble(struct compiler *c, int addNone)
70227050
if (optimize_cfg(c, &a, consts)) {
70237051
goto error;
70247052
}
7053+
guarantee_lineno_for_exits(&a, c->u->u_firstlineno);
70257054

70267055
/* Can't modify the bytecode after computing jump offsets. */
70277056
assemble_jump_offsets(&a, c);

0 commit comments

Comments
 (0)