Skip to content
Merged
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
66 changes: 45 additions & 21 deletions crates/codegen/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13611,39 +13611,43 @@ impl EmitArg<bytecode::Label> for BlockIdx {
}
}

/// Strips leading whitespace from a docstring.
/// Strips ASCII indentation from a docstring after expanding tabs.
///
/// `inspect.cleandoc` is a good reference, but has a few incompatibilities.
// = _PyCompile_CleanDoc
fn clean_doc(doc: &str) -> String {
let doc = expandtabs(doc, 8);
// First pass: find minimum indentation of non-blank lines AFTER the first line.
// A "blank line" is one containing only spaces (or empty).
let margin = doc
.split('\n')
.skip(1) // skip first line
.filter(|line| line.chars().any(|c| c != ' ')) // non-blank lines only
.map(|line| line.chars().take_while(|c| *c == ' ').count())
let mut lines = doc.split('\n');
let first_line = lines.next().unwrap_or_default();

// Find the minimum indentation among non-blank lines after the first.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the still-valid indentation comments

The root AGENTS.md says “Do not delete or rewrite existing comments” unless they are factually wrong or contradict the new code. The removed explanation that a blank line contains only spaces (or is empty), along with the original first-pass and subsequent-line comments, remains accurate for this implementation. Preserve those comments instead of deleting or editorially rephrasing them as part of the indentation fix.

AGENTS.md reference: AGENTS.md:L99-L99

Useful? React with 👍 / 👎.

let margin = lines
.clone()
.filter_map(|line| {
let indent = line.bytes().take_while(|&byte| byte == b' ').count();
(indent < line.len()).then_some(indent)
})
.min()
.unwrap_or(0);

let mut cleaned = String::with_capacity(doc.len());
// Strip all leading spaces from the first line
if let Some(first_line) = doc.split('\n').next() {
let trimmed = first_line.trim_start();
// Early exit: no leading spaces on first line AND margin == 0
if trimmed.len() == first_line.len() && margin == 0 {
return doc.to_owned();
}
cleaned.push_str(trimmed);
// CPython removes ASCII spaces here, not general Unicode whitespace.
let first = first_line.trim_start_matches(' ');
if first.len() == first_line.len() && margin == 0 {
return doc;
}
// Subsequent lines: skip up to `margin` leading spaces
for line in doc.split('\n').skip(1) {
let mut cleaned = String::with_capacity(doc.len());
cleaned.push_str(first);

// Copy subsequent lines with up to margin ASCII spaces removed.
for line in lines {
let skip = line
.bytes()
.take(margin)
.take_while(|&byte| byte == b' ')
.count();
cleaned.push('\n');
let skip = line.chars().take(margin).take_while(|c| *c == ' ').count();
cleaned.push_str(&line[skip..]);
}

cleaned
}

Expand Down Expand Up @@ -13909,11 +13913,31 @@ mod ruff_tests {
#[cfg(test)]
mod tests {
use super::*;

use rustpython_compiler_core::{
SourceFileBuilder,
bytecode::{CO_FAST_ARG_KW, CO_FAST_ARG_POS, CodeUnit, OpArg, Opcode},
};

#[test]
fn clean_doc_only_removes_ascii_indentation() {
for (input, expected) in [
("ordinary", "ordinary"),
(" first", "first"),
(
" \u{2003}keep\n one\n two",
"\u{2003}keep\none\n two",
),
(" \u{a0}keep", "\u{a0}keep"),
(" \r\n next", "\r\nnext"),
(" \u{b}keep", "\u{b}keep"),
(" \tfirst\n\t second\n", "first\nsecond\n"),
(" \n\n content\n ", "\n\ncontent\n"),
] {
assert_eq!(clean_doc(input), expected);
}
}

fn assert_scope_exit_locations(code: &CodeObject) {
for (instr, (location, _)) in code.instructions.iter().zip(code.locations.iter()) {
if matches!(
Expand Down
9 changes: 9 additions & 0 deletions extra_tests/snippets/builtin_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,15 @@ def _expect_syntax(source, mode):
assert eval(r'"a\rb"') == "a\rb"
assert eval(r'r"a\rb"') == r"a\rb"

# Compiled docstrings strip ASCII indentation, not other whitespace.
for leading in ("\u2003", "\xa0", "\r", "\v"):
doc = f" {leading}first\n second\n third"
code = f"def f():\n {doc!r}"
for compile_input in (code, ast.parse(code)):
namespace = {}
exec(compile(compile_input, "<docstring>", "exec"), namespace)
assert namespace["f"].__doc__ == f"{leading}first\nsecond\n third"

# Warnings and SyntaxError text must use the same source as the parser.
import warnings

Expand Down
Loading