Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Lib/test/test_ast/test_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ def test_negative_locations_for_compile(self):
# This also must not crash:
ast.parse(tree, optimize=2)

def test_compile_after_docstring_removal(self):
tree = ast.parse('"""doc"""')
compile(tree, '<string>', 'exec', optimize=2)

def test_slice(self):
slc = ast.parse("x[::]").body[0].value.slice
self.assertIsNone(slc.upper)
Expand Down
2 changes: 2 additions & 0 deletions Misc/NEWS.d/next/Core_and_Builtins/2024-06-01-ast-pass.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Ensure ``compile()`` succeeds when docstring stripping leaves an empty body
by inserting a ``pass`` statement during AST preprocessing.
11 changes: 11 additions & 0 deletions Python/ast_preprocess.c
Original file line number Diff line number Diff line change
Expand Up @@ -441,9 +441,20 @@ astfold_body(asdl_stmt_seq *stmts, PyArena *ctx_, _PyASTPreprocessState *state)
int docstring = _PyAST_GetDocString(stmts) != NULL;
if (docstring && (state->optimize >= 2)) {
/* remove the docstring */
stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
if (!stmt_seq_remove_item(stmts, 0)) {
return 0;
}
if (asdl_seq_LEN(stmts) == 0) {
stmt_ty pass_stmt = _PyAST_Pass(st->lineno, st->col_offset,
st->end_lineno, st->end_col_offset,
ctx_);
if (!pass_stmt) {
return 0;
}
stmts->size++;
asdl_seq_SET(stmts, stmts->size - 1, pass_stmt);
}
docstring = 0;
}
CALL_SEQ(astfold_stmt, stmt, stmts);
Expand Down
Loading