From 79b854f1bd2873ad7368a8b626829967e0b3f3b5 Mon Sep 17 00:00:00 2001 From: youknowdot Date: Fri, 4 Dec 2026 05:10:03 +0900 Subject: [PATCH] Match CPython docstring indentation cleanup Expand tabs before stripping ASCII spaces, use only non-blank lines after the first to derive the common margin, and preserve other leading whitespace. Reuse the expanded string when it is already clean. Refs: #9852 Assisted-by: Codex:GPT-6.2 --- crates/codegen/src/compile.rs | 66 +++++++++++++++++-------- extra_tests/snippets/builtin_compile.py | 9 ++++ 2 files changed, 54 insertions(+), 21 deletions(-) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index e709cbb5a1f..2a7e2ef011a 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -13611,39 +13611,43 @@ impl EmitArg 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. + 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 } @@ -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!( diff --git a/extra_tests/snippets/builtin_compile.py b/extra_tests/snippets/builtin_compile.py index 27946e48a0d..d51c1c12fdb 100644 --- a/extra_tests/snippets/builtin_compile.py +++ b/extra_tests/snippets/builtin_compile.py @@ -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, "", "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