Fix bytearray repr escaping for apostrophes - #8316
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthrough
ChangesBytearray representation escaping
Estimated code review effort: 2 (Simple) | ~10 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
📦 Library DependenciesThe following Lib/ modules were modified. Here are their dependencies: [ ] test: cpython/Lib/test/test_bytes.py (TODO: 20) dependencies: dependent tests: (no tests depend on bytes) Legend:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@crates/vm/src/bytes_inner.rs`:
- Around line 231-255: Update bytearray_repr_char_len and
write_bytearray_repr_char in crates/vm/src/bytes_inner.rs (231-255) to accept
the selected quote and escape quote bytes only when ch matches that quote, while
always escaping backslashes; then update the callers in
crates/vm/src/bytes_inner.rs (279-305) to pass quote as u8 to both helpers.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 4555f649-61e9-4353-a86f-ba148d6288e5
⛔ Files ignored due to path filters (1)
Lib/test/test_bytes.pyis excluded by!Lib/**
📒 Files selected for processing (1)
crates/vm/src/bytes_inner.rs
There was a problem hiding this comment.
♻️ Duplicate comments (1)
crates/vm/src/bytes_inner.rs (1)
231-255: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winConditionally escape the selected quote character.
The current implementation unconditionally escapes
b'\''even when"is chosen as the enclosing quote (which producesbytearray(b"\'")). Python's_Py_bytes_reprlogic dynamically checks if a byte matches the chosen quote character, successfully avoiding escaping the single quote if double quotes are selected (producingbytearray(b"'")).
crates/vm/src/bytes_inner.rs#L231-L255: Update the helper functions to accept thequoteparameter and only escapechif it matchesquote(orb'\\').crates/vm/src/bytes_inner.rs#L279-L305: Passquote as u8when callingbytearray_repr_char_lenandwrite_bytearray_repr_char.🐛 Proposed fixes
crates/vm/src/bytes_inner.rs#L231-L255
-fn bytearray_repr_char_len(ch: u8) -> usize { +fn bytearray_repr_char_len(ch: u8, quote: u8) -> usize { match ch { - b'\'' | b'\\' | b'\t' | b'\r' | b'\n' => 2, + b'\\' | b'\t' | b'\r' | b'\n' => 2, + c if c == quote => 2, 0x20..=0x7e => 1, _ => 4, // \xHH } } -fn write_bytearray_repr_char(ch: u8, buf: &mut String) { +fn write_bytearray_repr_char(ch: u8, quote: u8, buf: &mut String) { match ch { - b'\'' => buf.push_str("\\'"), b'\\' => buf.push_str("\\\\"), b'\t' => buf.push_str("\\t"), b'\n' => buf.push_str("\\n"), b'\r' => buf.push_str("\\r"), + c if c == quote => { + buf.push('\\'); + buf.push(c as char); + } 0x20..=0x7e => buf.push(ch as char), ch => {crates/vm/src/bytes_inner.rs#L279-L305
let body_len = self .elements .iter() .try_fold(0usize, |len, &ch| { - len.checked_add(bytearray_repr_char_len(ch)) + len.checked_add(bytearray_repr_char_len(ch, quote as u8)) }) .ok_or_else(|| Self::new_repr_overflow_error(vm))?; let len = class_name .len() .checked_add(DECORATION_LEN) .and_then(|len| len.checked_add(body_len)) .ok_or_else(|| Self::new_repr_overflow_error(vm))?; let mut buf = String::with_capacity(len); buf.push_str(class_name); buf.push('('); buf.push('b'); buf.push(quote); for &ch in &self.elements { - write_bytearray_repr_char(ch, &mut buf); + write_bytearray_repr_char(ch, quote as u8, &mut buf); }Run the following script to verify CPython's behavior for
bytearrayrepresentations when apostrophes are present:#!/bin/bash # Description: Check CPython's bytearray representations to verify conditional escaping. python3 -c "print(repr(bytearray(b\"'\")))" python3 -c "print(repr(bytearray(b'\"')))" python3 -c "print(repr(bytearray(b\"'\\\"\")))"🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@crates/vm/src/bytes_inner.rs` around lines 231 - 255, Update bytearray_repr_char_len and write_bytearray_repr_char in crates/vm/src/bytes_inner.rs:231-255 to accept the selected quote and escape it only when ch matches that quote or is a backslash; update the callers in crates/vm/src/bytes_inner.rs:279-305 to pass quote as u8 to both helpers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@crates/vm/src/bytes_inner.rs`:
- Around line 231-255: Update bytearray_repr_char_len and
write_bytearray_repr_char in crates/vm/src/bytes_inner.rs:231-255 to accept the
selected quote and escape it only when ch matches that quote or is a backslash;
update the callers in crates/vm/src/bytes_inner.rs:279-305 to pass quote as u8
to both helpers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 8af9828d-b2e7-45f8-8aef-53c611a1c7d7
⛔ Files ignored due to path filters (1)
Lib/test/test_bytes.pyis excluded by!Lib/**
📒 Files selected for processing (1)
crates/vm/src/bytes_inner.rs
youknowone
left a comment
There was a problem hiding this comment.
Thank you so much! and welcome to RustPython project.
You actually fixed more than test_bytearray_repr. Could you please also remove expectedFailure markers from other tests?
UNEXPECTED SUCCESS: test_bytearray_str (test.test_bytes.AssortedBytesTest.test_bytearray_str)
You can check it yourself by opening CI result
Signed-off-by: cuishuang <[email protected]>
Signed-off-by: cuishuang <[email protected]>
bytearray.__repr__#8311Summary
Fix
bytearray.__repr__to match CPython when the underlying bytes contain apostrophes.Previously, RustPython reused the generic bytes repr escaping logic for
bytearray, which producedbytearray(b"'")forrepr(bytearray(b"'")).CPython escapes apostrophes inside
bytearrayrepr output, including when the bytes literal uses double quotes. This PR adds bytearray-specific repr escaping while keepingbytesrepr behavior unchanged.Fixes #8311.
Tests
test_bytearray_reprCPython test by removing the RustPython expected failure.cargo fmt --check.Summary by CodeRabbit