-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Fix int respect sys.set_int_max_str_digits
value
#6094
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Fix int respect sys.set_int_max_str_digits
value
#6094
Conversation
WalkthroughCentralizes bytes-to-int parsing and error handling: adds a BytesToIntError type and digit-limit enforcement in common::int::bytes_to_int, changes it to return Result, and wires a new handle_bytes_to_int_err mapper into the VM int conversion path and public protocol exports. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant try_int_radix
participant bytes_to_int
participant handle_err
participant VMState
Caller->>try_int_radix: int(x, base?)
try_int_radix->>VMState: read int_max_str_digits
try_int_radix->>bytes_to_int: bytes_to_int(buf, base, digit_limit)
alt bytes_to_int Ok
bytes_to_int-->>try_int_radix: BigInt
try_int_radix-->>Caller: PyInt
else bytes_to_int Err(BytesToIntError)
bytes_to_int-->>handle_err: BytesToIntError
handle_err-->>try_int_radix: PyBaseExceptionRef
try_int_radix-->>Caller: raise exception
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (1)
vm/src/protocol/number.rs (1)
79-88
: Add tests to lock in semantics (sign, underscores, bytes-like, boundary conditions).Please add/update tests to cover:
- Exactly at the limit vs. exceeding by 1 (positive and negative).
- Underscores are ignored in the count (e.g., "1_234_567" with limit 7 passes; with 6 fails).
- Leading/trailing whitespace (str and bytes-like).
- bytes, bytearray, and other bytes-like objects enforce the same limit.
- Limit disabled (set to 0) allows arbitrarily long inputs.
- Mixed inputs that would be invalid literals (e.g., "9"*N + "x"); verify limit vs. invalid-literal precedence matches CPython.
Example Python-level cases (pseudo):
- set_int_max_str_digits(5); int("+" + "1"*5) ok; int("-" + "1"*6) ValueError; int("1_2_3_4_5") ok; int(b" 123456 ") ValueError.
I can draft these tests if helpful.
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
Lib/test/test_int.py
is excluded by!Lib/**
Lib/test/test_json/test_decode.py
is excluded by!Lib/**
📒 Files selected for processing (1)
vm/src/protocol/number.rs
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)
**/*.rs
: Follow the default rustfmt code style (cargo fmt
to format)
Always run clippy to lint code (cargo clippy
) before completing tasks. Fix any warnings or lints that are introduced by your changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass
,pymodule
,pyfunction
, etc.) when implementing Python functionality in Rust
Files:
vm/src/protocol/number.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
- GitHub Check: Run snippets and cpython tests (macos-latest)
- GitHub Check: Run snippets and cpython tests (windows-latest)
- GitHub Check: Run rust tests (windows-latest)
- GitHub Check: Run snippets and cpython tests (ubuntu-latest)
- GitHub Check: Check the WASM package and demo
- GitHub Check: Run rust tests (ubuntu-latest)
- GitHub Check: Check Rust code with rustfmt and clippy
- GitHub Check: Ensure compilation on various targets
- GitHub Check: Run tests under miri
- GitHub Check: Run snippets and cpython tests on wasm-wasi
166ac41
to
e3b894b
Compare
7044f6d
to
cf834d1
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🔭 Outside diff range comments (1)
vm/src/protocol/number.rs (1)
75-84
: Bug: Passing PyBytes where &[u8] is expected will not compileIn the PyBytes branch, try_convert expects a byte slice, but bytes is a PyBytes reference. Use .as_bytes().
Apply this fix:
- } else if let Some(bytes) = self.downcast_ref::<PyBytes>() { - try_convert(self, bytes, vm) + } else if let Some(bytes) = self.downcast_ref::<PyBytes>() { + try_convert(self, bytes.as_bytes(), vm)
🧹 Nitpick comments (1)
common/src/int.rs (1)
153-208
: Good tests; consider adding a few more edge cases
- Ensure digit-limit does not shadow InvalidLiteral: e.g., ("1a...a", 10) where a’s exceed the limit should still be InvalidLiteral.
- Verify underscore parsing across bases, including 0 auto-base: e.g., ("0_0", 0) and reject ("0x__10", 0).
- Confirm that power-of-two bases are exempt from the limit, but non-powers like base 3 are limited.
I can draft these if helpful.
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
⛔ Files ignored due to path filters (2)
Lib/test/test_int.py
is excluded by!Lib/**
Lib/test/test_json/test_decode.py
is excluded by!Lib/**
📒 Files selected for processing (4)
common/src/int.rs
(2 hunks)vm/src/builtins/int.rs
(2 hunks)vm/src/protocol/mod.rs
(1 hunks)vm/src/protocol/number.rs
(3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs
📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)
**/*.rs
: Follow the default rustfmt code style (cargo fmt
to format)
Always run clippy to lint code (cargo clippy
) before completing tasks. Fix any warnings or lints that are introduced by your changes
Follow Rust best practices for error handling and memory management
Use the macro system (pyclass
,pymodule
,pyfunction
, etc.) when implementing Python functionality in Rust
Files:
vm/src/protocol/mod.rs
vm/src/builtins/int.rs
common/src/int.rs
vm/src/protocol/number.rs
🧬 Code Graph Analysis (4)
vm/src/protocol/mod.rs (1)
vm/src/protocol/number.rs (1)
handle_bytes_to_int_err
(560-580)
vm/src/builtins/int.rs (3)
vm/src/protocol/number.rs (3)
handle_bytes_to_int_err
(560-580)obj
(440-442)obj
(450-450)common/src/int.rs (1)
bytes_to_int
(41-145)vm/src/builtins/bytearray.rs (2)
inner
(196-198)borrow_buf
(88-90)
common/src/int.rs (1)
compiler/literal/src/float.rs (1)
parse_bytes
(9-11)
vm/src/protocol/number.rs (1)
common/src/int.rs (1)
bytes_to_int
(41-145)
🔇 Additional comments (10)
common/src/int.rs (4)
32-37
: Public error type looks good and is future-proofClear, minimal variants that map well to Python exceptions. Deriving Eq/PartialEq aids testing. No issues.
46-48
: Early base validation is correctRejecting non-zero bases outside 2..=36 matches CPython. Good placement before any heavy work.
64-77
: Base autodetection and “old octal” path mirror CPython semanticsThe error_if_nonzero flow aligns with longobject.c behavior. Nicely handled edge cases.
89-103
: Prefix handling and single underscore after prefix match PEP 515Stripping 0x/0o/0b and allowing exactly one underscore after the prefix is correct and matches CPython acceptance of literals like 0x_10.
vm/src/protocol/mod.rs (1)
15-16
: Re-exporting handle_bytes_to_int_err is appropriateKeeps error mapping centralized and available to builtins and other callers.
vm/src/builtins/int.rs (2)
18-19
: Importing handle_bytes_to_int_err here keeps error mapping consistentThis avoids duplicating error message strings and ensures parity with protocol paths.
831-849
: Digit-limit now enforced for str/bytes/bytearray with consistent error mappingThis addresses the earlier concern about bytes-like inputs bypassing sys.set_int_max_str_digits. The TypeError for non-string with explicit base matches CPython.
vm/src/protocol/number.rs (3)
8-12
: New imports are correct and minimalBrings in BytesToIntError and PyBaseExceptionRef for centralized error mapping. No issues.
50-54
: Applying sys.set_int_max_str_digits inside try_int() is the right placeLoading the limit once and passing into bytes_to_int centralizes the guard. Good.
560-580
: Centralized error mapping matches CPython messages
- InvalidLiteral includes repr(obj)
- InvalidBase wording matches CPython
- DigitLimit message matches docs and includes both got and limit
Nice consolidation.
// Leading underscore not allowed | ||
if prev == b'_' || !prev.is_ascii_alphanumeric() { | ||
return Err(BytesToIntError::InvalidLiteral { base }); | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Count only valid digits for the given base and strip underscores before parsing
Two issues here:
- The digit counter treats any ASCII alphanumeric as a “digit”, regardless of base. This can raise DigitLimit for inputs that are actually invalid for the base (e.g., many non-decimal letters in base 10), diverging from CPython which counts only valid digits.
- BigUint::parse_bytes typically does not accept underscores. You validate underscores but don’t strip them before parsing. This can cause valid literals with underscores (e.g., "0_0_0") to parse as InvalidLiteral on backends that don’t ignore underscores.
Recommend:
- Validate and count only digits that are valid in the resolved base.
- Remove underscores before calling BigUint::parse_bytes.
Proposed patch:
@@
- // Leading underscore not allowed
- if prev == b'_' || !prev.is_ascii_alphanumeric() {
- return Err(BytesToIntError::InvalidLiteral { base });
- }
-
- // Verify all characters are digits and underscores
- let mut digits = 1;
- for &cur in buf.iter().skip(1) {
- if cur == b'_' {
- // Double underscore not allowed
- if prev == b'_' {
- return Err(BytesToIntError::InvalidLiteral { base });
- }
- } else if cur.is_ascii_alphanumeric() {
- digits += 1;
- } else {
- return Err(BytesToIntError::InvalidLiteral { base });
- }
-
- prev = cur;
- }
+ // Leading underscore not allowed; also first char must be a valid digit for the base
+ #[inline]
+ fn to_digit(b: u8) -> Option<u32> {
+ match b {
+ b'0'..=b'9' => Some((b - b'0') as u32),
+ b'a'..=b'z' => Some((b - b'a' + 10) as u32),
+ b'A'..=b'Z' => Some((b - b'A' + 10) as u32),
+ _ => None,
+ }
+ }
+ if prev == b'_' || to_digit(prev).map_or(true, |v| v >= base) {
+ return Err(BytesToIntError::InvalidLiteral { base });
+ }
+
+ // Verify all characters are valid digits (for base) or underscores; count only valid digits
+ let mut digits = 1;
+ let mut saw_underscore = false;
+ for &cur in buf.iter().skip(1) {
+ if cur == b'_' {
+ // Double underscore not allowed
+ if prev == b'_' {
+ return Err(BytesToIntError::InvalidLiteral { base });
+ }
+ saw_underscore = true;
+ } else if let Some(v) = to_digit(cur) {
+ if v >= base {
+ return Err(BytesToIntError::InvalidLiteral { base });
+ }
+ digits += 1;
+ } else {
+ return Err(BytesToIntError::InvalidLiteral { base });
+ }
+
+ prev = cur;
+ }
@@
- if digit_limit > 0 && !base.is_power_of_two() && digits > digit_limit {
+ if digit_limit > 0 && !base.is_power_of_two() && digits > digit_limit {
return Err(BytesToIntError::DigitLimit {
got: digits,
limit: digit_limit,
});
}
- let uint = BigUint::parse_bytes(buf, base).ok_or(BytesToIntError::InvalidLiteral { base })?;
+ // Strip underscores before parsing
+ let uint = if saw_underscore {
+ let stripped: Vec<u8> = buf.iter().copied().filter(|&b| b != b'_').collect();
+ BigUint::parse_bytes(&stripped, base)
+ } else {
+ BigUint::parse_bytes(buf, base)
+ }
+ .ok_or(BytesToIntError::InvalidLiteral { base })?;
Ok(BigInt::from_biguint(sign.unwrap_or(Sign::Plus), uint))
This keeps the same validation rules but ensures:
- Digit limit uses only base-valid digits.
- Parsing succeeds for valid literals with underscores.
Also applies to: 114-129, 131-135, 136-142, 143-145
🤖 Prompt for AI Agents
In common/src/int.rs around lines 109-113 (and similarly 114-129, 131-135,
136-142, 143-145), the code currently treats any ASCII alphanumeric as a digit
and passes the raw string (with underscores) to BigUint::parse_bytes; change the
logic to (1) validate characters against the resolved base so only characters
that are valid digits for that base increment the digit counter and any other
alphanumeric character causes InvalidLiteral, and (2) build a new digit-only
byte buffer that strips underscores (but preserves digit characters) and pass
that cleaned buffer to BigUint::parse_bytes; keep existing checks for
leading/trailing/misplaced underscores but ensure underscores are removed before
parsing so literals like "0_0_0" parse correctly.
Summary by CodeRabbit