Skip to content

Constify functions & General nitpicks #5858

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

Merged
merged 13 commits into from
Jun 28, 2025

Conversation

ShaharNaveh
Copy link
Contributor

@ShaharNaveh ShaharNaveh commented Jun 28, 2025

If this PR is too large I don't mind splitting it:)

Summary by CodeRabbit

  • New Features

    • Many methods and functions across core types, standard library modules, and utilities are now marked as const, allowing their use in compile-time constant contexts.
    • Added new method for IPv6 address tuple parsing in the socket module.
  • Refactor

    • Improved code readability with additional blank lines and minor formatting cleanups.
    • Simplified and modernized some error message constructions and pattern matching expressions.
  • Bug Fixes

    • Minor corrections to error message formatting and method annotations to ensure proper exposure as Python methods.
  • Style

    • Enhanced code clarity by reformatting string literals and restructuring some internal logic without changing behavior.

Copy link

coderabbitai bot commented Jun 28, 2025

"""

Walkthrough

This change set focuses on marking many functions and methods across the codebase as const fn, enabling their use in constant contexts and allowing compile-time evaluation where possible. Additionally, several files receive formatting improvements, such as added blank lines for readability and minor refactorings to error message construction and pattern matching. No core logic, error handling, or control flow is altered.

Changes

File(s) Change Summary
common/src/borrow.rs, .../encodings.rs, .../pymodule.rs, .../coroutine.rs, .../str.rs, .../object.rs, .../str.rs Added blank lines for formatting and readability; no logic or signature changes
common/src/boxvec.rs Marked several BoxVec<T> and CapacityError<T> methods as const fn; added blank lines in trait impls
common/src/cformat.rs Marked methods as const fn; replaced explicit type with Self:: in flag checks; added blank lines
common/src/fileutils.rs Marked attributes_to_mode as const fn; added blank line before another function
common/src/float_ops.rs Marked decompose_float and div as const fn
common/src/format.rs Marked FormatSpec::get_separator_interval and AsciiStr::new as const fn; formatting
common/src/hash.rs Marked several hashing functions as const fn; added blank line in trait impl
common/src/int.rs Marked detect_base as const fn
common/src/str.rs Marked several methods/functions as const fn in StrKind, StrData, and levenshtein; formatting
derive-impl/src/util.rs Added blank lines; improved string formatting in error messages; no logic changes
stdlib/src/mmap.rs Refactored FlushOptions::values to use match; added blank line in PyMmap::close
stdlib/src/pystruct.rs Marked PyStruct::size as const fn
stdlib/src/socket.rs Marked byte-order functions as const fn; added blank lines; added Address::from_tuple_ipv6 method
stdlib/src/zlib.rs Marked CompressInner::new as const fn; added blank lines; fixed missing return in maybe_set_dict
vm/src/builtins/builtin_func.rs Marked PyNativeFunction::as_func as const fn; added blank lines
vm/src/builtins/descriptor.rs Marked two getter methods as const fn
vm/src/builtins/dict.rs Marked iterator/view constructors as const fn; simplified error construction; formatting
vm/src/builtins/float.rs Marked several PyFloat methods as const fn; simplified error construction
vm/src/builtins/generator.rs Marked as_coro as const fn; added blank lines
vm/src/builtins/genericalias.rs Marked __unpacked__ as const fn
vm/src/builtins/int.rs Marked several methods as const fn; simplified error message construction
vm/src/builtins/mappingproxy.rs Added #[pymethod] to methods; changed error message string to raw string
vm/src/builtins/module.rs Marked constructors as const fn; formatting
vm/src/builtins/object.rs, .../range.rs, .../set.rs Simplified error construction; refactored pattern matching; no logic changes
vm/src/builtins/tuple.rs Marked several methods as const fn; formatting
vm/src/bytes_inner.rs Marked methods as const fn
vm/src/dict_inner.rs Marked several methods as const fn; added blank lines in trait impls
vm/src/frame.rs Refactored to reduce repeated calls and update panic formatting
vm/src/function/method.rs Marked several methods as const fn; formatting; improved error message formatting
vm/src/ospath.rs Marked IOErrorBuilder::new as const fn
wtf8/src/core_str_count.rs Marked unlikely as const fn
wtf8/src/lib.rs Marked many methods and functions as const fn across types; formatting improvements

Sequence Diagram(s)

No sequence diagrams are generated, as the changes are primarily about const-qualification and formatting, not control flow or feature additions.

Suggested reviewers

  • youknowone

Poem

In fields of code, the rabbits cheer,
For const fn magic now appears!
Compile-time bunnies leap with glee,
As blank lines hop in harmony.
With functions now both fast and neat,
This patch is truly quite a treat!
(∩`-´)⊃━☆゚.*・。゚
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc8fc74 and 172f299.

📒 Files selected for processing (2)
  • common/src/cformat.rs (10 hunks)
  • vm/src/function/method.rs (7 hunks)
✅ Files skipped from review due to trivial changes (1)
  • common/src/cformat.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • vm/src/function/method.rs
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run tests under miri
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a 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 (2)
stdlib/src/socket.rs (1)

1669-1688: IPv6 tuple parsing rejects 3- or 4-element tuples

from_tuple_ipv6 unconditionally forwards the whole tuple slice to Address::from_tuple, which itself requires len()==2.
Any valid IPv6 3- or 4-element address ( (host, port[, flowinfo[, scopeid]]) ) will therefore raise TypeError.

-        fn from_tuple_ipv6(
-            tuple: &[PyObjectRef],
-            vm: &VirtualMachine,
-        ) -> PyResult<(Self, u32, u32)> {
-            let addr = Address::from_tuple(tuple, vm)?;
+        fn from_tuple_ipv6(
+            tuple: &[PyObjectRef],
+            vm: &VirtualMachine,
+        ) -> PyResult<(Self, u32, u32)> {
+            // Only first two items belong to the host/port pair
+            let addr = Address::from_tuple(&tuple[..2], vm)?;

This fixes the length pre-condition while leaving the rest of the logic intact.

vm/src/dict_inner.rs (1)

150-158: Fix invalid const function signature

This const function signature is invalid. Const functions cannot:

  1. Take &mut self parameters
  2. Perform mutations (this function contains self.idx = ... and self.perturb >>= 5)

Remove the const qualifier:

-    const fn next(&mut self) -> usize {
+    fn next(&mut self) -> usize {
🧹 Nitpick comments (1)
vm/src/builtins/generator.rs (1)

31-31: LGTM: Valid const fn conversion.

The method simply returns a field reference, making it appropriate for compile-time evaluation. Consider applying similar const fn conversions to the equivalent as_coro methods in asyncgenerator.rs and coroutine.rs for consistency.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e41d7f5 and dc8fc74.

📒 Files selected for processing (39)
  • common/src/borrow.rs (3 hunks)
  • common/src/boxvec.rs (6 hunks)
  • common/src/cformat.rs (11 hunks)
  • common/src/encodings.rs (3 hunks)
  • common/src/fileutils.rs (2 hunks)
  • common/src/float_ops.rs (2 hunks)
  • common/src/format.rs (3 hunks)
  • common/src/hash.rs (3 hunks)
  • common/src/int.rs (1 hunks)
  • common/src/str.rs (6 hunks)
  • derive-impl/src/pymodule.rs (2 hunks)
  • derive-impl/src/util.rs (10 hunks)
  • stdlib/src/mmap.rs (2 hunks)
  • stdlib/src/pystruct.rs (1 hunks)
  • stdlib/src/socket.rs (6 hunks)
  • stdlib/src/zlib.rs (6 hunks)
  • vm/src/builtins/builtin_func.rs (4 hunks)
  • vm/src/builtins/descriptor.rs (1 hunks)
  • vm/src/builtins/dict.rs (6 hunks)
  • vm/src/builtins/float.rs (5 hunks)
  • vm/src/builtins/generator.rs (2 hunks)
  • vm/src/builtins/genericalias.rs (1 hunks)
  • vm/src/builtins/int.rs (4 hunks)
  • vm/src/builtins/mappingproxy.rs (2 hunks)
  • vm/src/builtins/module.rs (2 hunks)
  • vm/src/builtins/object.rs (1 hunks)
  • vm/src/builtins/range.rs (1 hunks)
  • vm/src/builtins/set.rs (1 hunks)
  • vm/src/builtins/str.rs (1 hunks)
  • vm/src/builtins/tuple.rs (5 hunks)
  • vm/src/bytes_inner.rs (1 hunks)
  • vm/src/coroutine.rs (2 hunks)
  • vm/src/dict_inner.rs (17 hunks)
  • vm/src/frame.rs (2 hunks)
  • vm/src/function/method.rs (7 hunks)
  • vm/src/object/core.rs (3 hunks)
  • vm/src/ospath.rs (1 hunks)
  • wtf8/src/core_str_count.rs (1 hunks)
  • wtf8/src/lib.rs (19 hunks)
🧰 Additional context used
🧠 Learnings (14)
📓 Common learnings
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: To find unimplemented methods and contribution opportunities, run './whats_left.py' in the RustPython repository.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory; bug fixes should be made through Rust code modifications whenever possible.
common/src/encodings.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Always run 'cargo clippy' to lint Rust code before completing tasks, and fix any warnings or lints introduced by your changes.
derive-impl/src/pymodule.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When implementing a Python module in Rust for RustPython, use the #[pymodule] attribute and expose functions and classes using #[pyfunction], #[pyclass], and #[pymethod] as appropriate.
vm/src/builtins/builtin_func.rs (4)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory; bug fixes should be made through Rust code modifications whenever possible.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When implementing a Python module in Rust for RustPython, use the #[pymodule] attribute and expose functions and classes using #[pyfunction], #[pyclass], and #[pymethod] as appropriate.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Use the macro system (such as 'pyclass', 'pymodule', 'pyfunction') when implementing Python functionality in Rust for RustPython.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: To add a Python module to the RustPython interpreter, use 'vm.add_native_module' with the module name and module factory.
stdlib/src/zlib.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Follow Rust best practices for error handling and memory management in all RustPython Rust code.
vm/src/builtins/mappingproxy.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When implementing a Python module in Rust for RustPython, use the #[pymodule] attribute and expose functions and classes using #[pyfunction], #[pyclass], and #[pymethod] as appropriate.
vm/src/builtins/module.rs (5)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When implementing a Python module in Rust for RustPython, use the #[pymodule] attribute and expose functions and classes using #[pyfunction], #[pyclass], and #[pymethod] as appropriate.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: To add a Python module to the RustPython interpreter, use 'vm.add_native_module' with the module name and module factory.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory; bug fixes should be made through Rust code modifications whenever possible.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Use the macro system (such as 'pyclass', 'pymodule', 'pyfunction') when implementing Python functionality in Rust for RustPython.
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.770Z
Learning: In RustPython's stat module implementation, platform-specific constants like SF_SUPPORTED and SF_SYNTHETIC should be conditionally declared only for the platforms where they're available (e.g., macOS), following CPython's approach of optional declaration using #ifdef checks rather than providing fallback values for other platforms.
common/src/hash.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory; bug fixes should be made through Rust code modifications whenever possible.
vm/src/object/core.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory; bug fixes should be made through Rust code modifications whenever possible.
vm/src/builtins/int.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory; bug fixes should be made through Rust code modifications whenever possible.
vm/src/function/method.rs (2)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Use the macro system (such as 'pyclass', 'pymodule', 'pyfunction') when implementing Python functionality in Rust for RustPython.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When implementing a Python module in Rust for RustPython, use the #[pymodule] attribute and expose functions and classes using #[pyfunction], #[pyclass], and #[pymethod] as appropriate.
common/src/cformat.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Always use 'cargo fmt' to format Rust code and follow the default rustfmt code style when contributing to RustPython.
vm/src/builtins/float.rs (3)
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.770Z
Learning: In RustPython's stat module implementation, platform-specific constants like SF_SUPPORTED and SF_SYNTHETIC should be conditionally declared only for the platforms where they're available (e.g., macOS), following CPython's approach of optional declaration using #ifdef checks rather than providing fallback values for other platforms.
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.770Z
Learning: In RustPython's stat module implementation, platform-specific constants like SF_SUPPORTED and SF_SYNTHETIC should be conditionally declared only for the platforms where they're available (e.g., macOS), following CPython's approach of optional declaration rather than providing fallback values for other platforms.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When implementing a Python module in Rust for RustPython, use the #[pymodule] attribute and expose functions and classes using #[pyfunction], #[pyclass], and #[pymethod] as appropriate.
stdlib/src/socket.rs (5)
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.770Z
Learning: In RustPython's stat module implementation, platform-specific constants like SF_SUPPORTED and SF_SYNTHETIC should be conditionally declared only for the platforms where they're available (e.g., macOS), following CPython's approach of optional declaration using #ifdef checks rather than providing fallback values for other platforms.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Minimize modifications to CPython standard library files in the Lib/ directory; bug fixes should be made through Rust code modifications whenever possible.
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.770Z
Learning: In RustPython's stat module implementation, platform-specific constants like SF_SUPPORTED and SF_SYNTHETIC should be conditionally declared only for the platforms where they're available (e.g., macOS), following CPython's approach of optional declaration rather than providing fallback values for other platforms.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: When implementing a Python module in Rust for RustPython, use the #[pymodule] attribute and expose functions and classes using #[pyfunction], #[pyclass], and #[pymethod] as appropriate.
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-26T12:52:11.109Z
Learning: Use the macro system (such as 'pyclass', 'pymodule', 'pyfunction') when implementing Python functionality in Rust for RustPython.
🧬 Code Graph Analysis (5)
stdlib/src/pystruct.rs (3)
vm/src/builtins/dict.rs (1)
  • size (157-159)
vm/src/dict_inner.rs (2)
  • size (226-233)
  • size (512-514)
vm/src/buffer.rs (1)
  • size (447-449)
vm/src/builtins/generator.rs (2)
vm/src/builtins/asyncgenerator.rs (1)
  • as_coro (32-34)
vm/src/builtins/coroutine.rs (1)
  • as_coro (28-30)
vm/src/builtins/descriptor.rs (7)
vm/src/builtins/builtin_func.rs (5)
  • __name__ (84-86)
  • __qualname__ (89-109)
  • __qualname__ (162-167)
  • __doc__ (112-114)
  • __text_signature__ (133-137)
vm/src/builtins/getset.rs (3)
  • __name__ (135-137)
  • __qualname__ (140-142)
  • __objclass__ (145-148)
vm/src/builtins/type.rs (7)
  • __name__ (574-589)
  • __qualname__ (592-599)
  • typ (1022-1030)
  • name (430-435)
  • __doc__ (1151-1176)
  • __text_signature__ (786-791)
  • get_text_signature_from_internal_doc (1066-1071)
vm/src/builtins/function.rs (5)
  • __name__ (437-439)
  • __qualname__ (487-489)
  • __qualname__ (772-791)
  • __doc__ (447-456)
  • __doc__ (752-754)
vm/src/builtins/classmethod.rs (2)
  • __name__ (149-151)
  • __qualname__ (144-146)
vm/src/builtins/staticmethod.rs (2)
  • __name__ (110-112)
  • __qualname__ (105-107)
vm/src/builtins/memory.rs (1)
  • format (622-625)
vm/src/builtins/int.rs (1)
vm/src/builtins/float.rs (1)
  • imag (470-472)
vm/src/builtins/float.rs (3)
vm/src/builtins/int.rs (7)
  • __bool__ (580-582)
  • __pos__ (538-540)
  • __neg__ (485-487)
  • __float__ (543-545)
  • real (669-671)
  • imag (674-676)
  • conjugate (600-602)
vm/src/builtins/tuple.rs (2)
  • __bool__ (260-262)
  • zelf (248-252)
vm/src/builtins/complex.rs (6)
  • __bool__ (382-384)
  • __pos__ (349-351)
  • __neg__ (354-356)
  • real (250-252)
  • imag (255-257)
  • conjugate (316-318)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run tests under miri
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (macos-latest)
🔇 Additional comments (84)
vm/src/builtins/str.rs (1)

308-312: LGTM: Improved readability with strategic blank lines.

The addition of blank lines around the Unconstructible and SelfIter trait implementations enhances code organization and readability without affecting functionality.

vm/src/coroutine.rs (1)

132-190: LGTM: Enhanced method separation for better readability.

The strategic addition of blank lines between method definitions in the Coro implementation improves code organization and makes the structure more visually clear without any functional impact.

derive-impl/src/pymodule.rs (2)

34-34: LGTM: Consistent formatting improvement.

The addition of a blank line after the associated type declaration enhances readability by separating the type definition from the method implementation.


408-424: LGTM: Consistent trait implementation formatting.

The strategic blank lines after associated type declarations in the ContentItem trait implementations create consistent visual separation and improve code organization across all three implementations (FunctionItem, ClassItem, and AttributeItem).

vm/src/builtins/range.rs (1)

410-410: LGTM! Good micro-optimization.

Removing the unnecessary .to_owned() call is a good improvement - string literals can be passed directly as &str without allocation.

vm/src/builtins/set.rs (1)

237-240: Good refactoring - match expression improves clarity.

The pattern matching approach is more explicit and idiomatic Rust compared to the previous conditional assignment. Logic remains identical.

vm/src/frame.rs (2)

278-279: LGTM: Good micro-optimization.

Caching the filename.as_str() call improves readability and avoids the repeated method call. This is a clean refactoring.


2269-2269: LGTM: Modern Rust formatting syntax.

The change to use implicit named formatting (panic!("{msg}")) is more idiomatic than the explicit version and aligns with modern Rust conventions.

vm/src/builtins/mappingproxy.rs (2)

154-154: LGTM: Explicit method annotations for consistency.

Adding explicit #[pymethod] annotations to the keys, values, and copy methods ensures consistent Python method registration across the codebase, even though these methods were likely already being exposed.

Also applies to: 160-160, 166-166


200-200: LGTM: Improved string literal readability.

Using a raw string literal eliminates the need for escaped quotes and makes the error message more readable.

stdlib/src/mmap.rs (2)

216-226: LGTM! Excellent refactoring to use match expressions.

The change from nested if let statements to match expressions is more idiomatic Rust and improves readability while maintaining the same logic for handling negative values and defaulting behavior.


565-565: Good formatting improvement.

The added blank line appropriately separates the export check logic from the mmap cleanup operations, improving visual organization.

derive-impl/src/util.rs (4)

280-280: Good formatting improvements.

The added blank lines after method implementations improve visual separation and code readability across the trait implementations.

Also applies to: 294-294, 304-304, 328-328, 351-351, 454-454


524-525: Improved string literal formatting.

The switch to a triple-quoted raw string literal is cleaner and more readable than the previous format.


744-744: More concise error formatting.

The inline formatting in the unreachable! macro is more concise and appropriate for this context.


629-629: Enhanced readability with blank lines.

The added blank lines in the ErrorVec trait implementation improve visual separation between methods.

Also applies to: 637-637, 653-653

wtf8/src/core_str_count.rs (1)

160-160: Appropriate const fn conversion.

Converting the unlikely function to const fn is correct since it performs a simple operation (returning the input boolean) and enables compile-time evaluation in const contexts.

common/src/borrow.rs (1)

59-59: Consistent formatting improvements.

The added blank lines in the Deref implementations improve visual separation between type declarations and method implementations, enhancing code readability.

Also applies to: 85-85, 113-113

vm/src/builtins/genericalias.rs (1)

164-164: Appropriate const fn conversion.

Converting __unpacked__ to const fn is correct since it simply returns a boolean field value. This enables compile-time evaluation and usage in const contexts without changing the method's behavior.

common/src/encodings.rs (1)

124-124: LGTM! Formatting improvements enhance readability.

The added blank lines appropriately separate logical code sections and improve visual clarity without altering functionality.

Also applies to: 137-137, 157-157

vm/src/builtins/object.rs (1)

97-97: LGTM! Good micro-optimization.

Passing the string literal directly eliminates unnecessary String allocation while maintaining identical functionality.

stdlib/src/pystruct.rs (1)

262-262: LGTM! Appropriate const fn conversion.

The method only returns a simple field value, making it suitable for compile-time evaluation in constant contexts.

vm/src/ospath.rs (1)

136-142: LGTM! Safe const fn conversion.

The constructor only initializes struct fields with simple values, making it appropriate for compile-time evaluation.

common/src/fileutils.rs (2)

259-259: LGTM! Appropriate const fn conversion.

The function only performs bitwise operations with constants, making it suitable for compile-time evaluation.


365-365: LGTM! Formatting improvement.

The added blank line improves readability by visually separating the functions.

common/src/int.rs (1)

131-131: LGTM: Appropriate const fn conversion.

The function performs simple pattern matching on byte values to return base constants, making it suitable for compile-time evaluation.

vm/src/builtins/generator.rs (1)

55-65: LGTM: Improved code readability.

The blank lines between #[pygetset] methods enhance code structure and readability.

common/src/format.rs (3)

395-395: LGTM: Valid const fn conversion.

The method performs pattern matching on enum variants to return constants, with a panic for invalid cases. This is appropriate for compile-time evaluation.


680-680: LGTM: Appropriate const fn conversion.

Simple constructor method that assigns a field value, making it suitable for compile-time evaluation.


693-693: LGTM: Improved formatting.

The blank line enhances separation between different method implementations.

stdlib/src/zlib.rs (2)

419-419: LGTM: Appropriate const fn conversion.

Simple constructor method that wraps a field value, making it suitable for compile-time evaluation.


234-565: LGTM: Enhanced code readability.

The blank lines between method definitions and trait implementations improve code structure and readability.

vm/src/builtins/builtin_func.rs (2)

60-60: LGTM: Valid const fn conversion.

The method performs a simple field access, making it appropriate for compile-time evaluation.


82-233: LGTM: Improved code formatting.

The blank lines between property getters and methods enhance code structure and readability.

vm/src/builtins/module.rs (1)

72-77: LGTM! Appropriate const fn conversions

Both new() and from_def() methods correctly convert to const fn as they only perform simple field assignments without any runtime computations or allocations. This enables these constructors to be used in constant contexts.

Also applies to: 79-84

common/src/float_ops.rs (1)

5-14: LGTM! Valid const fn conversions for floating-point utilities

Both functions are correctly converted to const fn:

  • decompose_float() uses only bitwise operations, conditionals, and f64::from_bits() which are all const-compatible
  • div() performs simple conditional logic and arithmetic operations

These changes enable compile-time evaluation of these floating-point utilities.

Also applies to: 66-68

vm/src/bytes_inner.rs (1)

308-310: LGTM! Correct const fn conversions for Vec accessor methods

All three methods are correctly converted to const fn as they delegate to corresponding const methods on Vec<u8>:

  • len()Vec::len()
  • capacity()Vec::capacity()
  • is_empty()Vec::is_empty()

These changes enable compile-time evaluation of basic byte container properties.

Also applies to: 313-315, 318-320

vm/src/builtins/descriptor.rs (1)

113-115: LGTM! Appropriate const fn conversions for static attribute accessors

Both methods correctly convert to const fn as they only perform field access returning static references:

  • __name__() returns &'static PyStrInterned
  • __doc__() returns Option<&'static str>

This aligns with similar patterns in other descriptor types (like builtin_func.rs) and enables compile-time access to these static attributes.

Also applies to: 123-125

vm/src/object/core.rs (1)

605-607: LGTM! Valid const fn conversions for core object accessors

All three methods are correctly converted to const fn as they perform only simple field access and const-compatible operations:

  • weak_ref_list() does field access and Option::Some construction
  • instance_dict() does field access and Option::as_ref() call
  • as_raw() simply returns the object pointer

These enable compile-time access to fundamental object properties without runtime overhead.

Also applies to: 704-706, 775-777

vm/src/builtins/int.rs (4)

262-264: LGTM: const fn conversion is appropriate.

Converting as_bigint to const fn is correct since it's a simple field accessor that returns a reference. This enables compile-time evaluation where applicable.


674-676: LGTM: const fn conversion aligns with numeric types pattern.

The imag method correctly returns 0 for integers as a const fn, consistent with the similar implementation in vm/src/builtins/float.rs (lines 470-472) where float's imag method also returns 0.0 as a const fn.


684-686: LGTM: const fn conversion for denominator is appropriate.

Converting denominator to const fn is correct since integers always have a denominator of 1. This enables compile-time evaluation and maintains semantic correctness.


855-855: Confirmed: new_type_error accepts &str, so removing .to_owned() is safe.
No changes required—this compiles and matches existing usages in hashlib.rs, ssl.rs, and others.

common/src/hash.rs (5)

35-35: LGTM: Formatting improvement.

Adding a blank line improves readability within the BuildHasher implementation.


84-88: LGTM: const fn conversion for hash_pointer is appropriate.

Converting hash_pointer to const fn is correct since it performs simple bitwise operations that are const-compatible. This enables compile-time evaluation for pointer hashing.


144-146: LGTM: const fn conversion for hash_usize is appropriate.

Converting hash_usize to const fn is correct since it calls other const functions (fix_sentinel and mod_int). This enables compile-time evaluation for usize hashing.


149-151: LGTM: const fn conversion for fix_sentinel is appropriate.

Converting fix_sentinel to const fn is correct since it performs a simple conditional expression that's const-compatible. This enables compile-time evaluation for sentinel value handling.


154-156: LGTM: const fn conversion for mod_int is appropriate.

Converting mod_int to const fn is correct since modulo operations on primitive types are const-compatible. This enables compile-time evaluation for integer modulus operations.

stdlib/src/socket.rs (1)

728-746: hton*/ntoh* turned into const fn – looks good

Straightforward wrapper around the intrinsic {u32,u16}::to_be/from_be.
No correctness, portability or const-eval concerns spotted.

vm/src/function/method.rs (3)

118-125: Const-qualified to_function – clear and safe

Marking the simple accessor as const brings compile-time usability without side-effects.


134-147: Const-qualified to_bound_method – OK

No non-const operations involved. Change is safe and consistent with the rest of the refactor.


276-278: HeapMethodDef::new as const fn – OK

Helps build static tables; no issues.

vm/src/builtins/tuple.rs (4)

195-200: Constifying simple accessors – fine

new_unchecked / as_slice are pure reads; turning them into const fn is harmless and aids compile-time construction.


260-262: __bool__ as const fn – fine

Pure length check, no objections.


277-284: __len__ / is_empty now const – fine

No runtime effects; consistent with the overall refactor.


559-566: Typed-tuple helpers unchanged apart from whitespace

No functional changes. Nothing to report.

common/src/str.rs (1)

39-41: LGTM: Appropriate const function conversions

The addition of const qualifiers to these methods is well-executed. All functions contain only const-compatible operations:

  • is_ascii/is_utf8: Use pattern matching on enum variants
  • as_wtf8/kind: Return field references/values
  • substitution_cost: Contains only arithmetic and comparison operations

These changes enable compile-time evaluation where beneficial.

Also applies to: 43-45, 257-259, 274-276, 474-488

vm/src/builtins/dict.rs (2)

694-696: LGTM: Appropriate const constructors

Converting these constructor functions to const fn is correct since they only initialize struct fields with the provided parameters.

Also applies to: 725-727


889-891: Good simplification of error message construction

Removing the unnecessary .to_owned() calls on string literals is a nice cleanup since string literals can be directly used in error constructors.

Also applies to: 968-970

vm/src/dict_inner.rs (2)

60-63: LGTM: Valid const function conversions

These const conversions are appropriate:

  • from_index_unchecked: Simple value wrapping
  • index: Conditional logic with no mutations
  • size: Struct creation from field values
  • should_resize: Pure arithmetic and conditional operations

Also applies to: 65-71, 226-233, 236-242


141-148: LGTM: Appropriate const constructor

The GenIndexes::new function only initializes struct fields, making it suitable for const fn.

vm/src/builtins/float.rs (4)

30-33: Const‐ifying to_f64 looks good

Making this accessor const fn is safe (plain field read) and unlocks compile-time evaluation for several helper macros elsewhere.


288-350: __bool__, __pos__, __neg__ promoted to const – semantics preserved

All three methods are now trivially evaluable at compile time and still mirror CPython behaviour (bool(-0.0) remains False, NaN remains truthy). No objections.


459-477: __float__, real, imag, conjugate as const fn – OK

Bodies are pure passthroughs, so const-ifying them is safe and may help generic code relying on compile-time evaluation.


579-581: Minor error-string tweak reads clearer

Dropping the redundant String::from was the right call; no functional impact.

common/src/cformat.rs (5)

3-3: Bringing in bitflags_match! reduces boilerplate

New import is legitimate; the crate is already in the dependency tree, so compile times won’t regress.


79-87: CFloatType::caseconst fn

Pure pattern match with no heap interaction—safe and helpful for match-heavy const contexts.


103-112: CFormatType::to_char now const – fine

Compile-time evaluation of spec-parsing utilities becomes possible; implementation unchanged.


139-146: Double-check precedence when both + and space flags are present

bitflags_match! matches the first satisfied pattern. With both SIGN_CHAR and BLANK_SIGN set, the current ordering still yields "+", matching CPython precedence. If future flag combinations are added, keep this ordering invariant.


722-733: Const getters on CFormatPart are harmless

Being able to query at compile time whether a piece is a specifier or carries a key can marginally speed up format-string validation in const contexts.

common/src/boxvec.rs (2)

49-70: Vector introspection methods turned const – 👍

len, is_empty, capacity, is_full, and remaining_capacity now usable in const contexts; bodies are plain arithmetic, so no safety issues.


679-681: CapacityError::new as const fn

Construction is field assignment only—safe and occasionally handy in generic const code.

wtf8/src/lib.rs (12)

94-96: Excellent const function additions for CodePoint construction and conversion methods.

These const fn additions for CodePoint are well-implemented and enable compile-time evaluation of basic code point operations. All operations (struct initialization, pattern matching, and casting) are fully const-compatible.

Also applies to: 102-107, 113-117, 121-123


127-132: Proper const implementation for CodePoint surrogate and character conversion methods.

The const additions for surrogate handling and character conversion methods are correctly implemented. Pattern matching on numeric ranges and unsafe character creation from validated values are both const-compatible operations.

Also applies to: 136-141, 147-152


228-230: Const function correctly depends on other const functions.

The merge method is properly marked as const and calls decode_surrogate_pair, which is also being made const in this PR. The dependency chain is correctly maintained.


304-306: Appropriate const functions for Wtf8Buf basic operations.

Both from_bytes_unchecked and capacity are correctly marked as const. The struct construction and Vec::capacity() call are both const-compatible operations.

Also applies to: 438-440


646-646: Good formatting improvement for ToOwned implementation.

The added blank lines around the to_owned and clone_into methods improve readability by providing visual separation within the trait implementation.

Also applies to: 650-650


747-750: Correct const unsafe functions for byte slice conversion.

Both functions properly handle the unsafe pointer casting operations in a const context. The private from_mut_bytes_unchecked and public from_bytes_unchecked are correctly implemented as const unsafe functions.

Also applies to: 757-760


785-787: Well-implemented const functions for Wtf8 basic operations.

The len, is_empty, and ascii_byte_at methods are correctly marked as const. All operations (slice length, emptiness check, and byte indexing with pattern matching) are const-compatible.

Also applies to: 790-792, 801-806


827-829: Proper const functions for Wtf8 byte and string access.

Both as_bytes and as_str are correctly implemented as const functions. Field access and str::from_utf8 calls are both const-compatible operations.

Also applies to: 837-839


892-894: Correct const functions for Wtf8 utility methods.

The chunks and is_ascii methods are properly marked as const. Struct construction and slice ASCII checking are both const-compatible.

Also applies to: 978-980


1231-1234: Well-implemented const utility functions for surrogate handling.

Both decode_surrogate and decode_surrogate_pair are correctly marked as const functions. The bitwise operations, arithmetic, and unsafe character creation are all const-compatible.

Also applies to: 1237-1240


1288-1295: Proper const unsafe function for slice operations.

The slice_unchecked function is correctly implemented as a const unsafe function. The pointer arithmetic and slice creation operations are const-compatible in unsafe contexts.


171-173: No action needed: len_utf8 is already const fn

The len_utf8 function is declared as a pub const fn in wtf8/src/core_char.rs:20, so calling it from your const fn len_wtf8 is valid. No changes are required.

Comment on lines 110 to 115
bitflags::bitflags_match!(self.flags, {
PyMethodFlags::METHOD => self.build_method(ctx, class).into(),
PyMethodFlags::CLASS => self.build_classmethod(ctx, class).into(),
PyMethodFlags::STATIC => self.build_staticmethod(ctx, class).into(),
_ => unreachable!(),
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

to_proper_method panics when no flag is set

bitflags_match! falls through to _ => unreachable!().
Plain functions (no METHOD/CLASS/STATIC bits) will therefore trigger a panic instead of returning a regular PyNativeFunction.

-            _ => unreachable!(),
+            _ => self.build_function(ctx).into(),

Please restore the default branch to produce a callable function object.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
bitflags::bitflags_match!(self.flags, {
PyMethodFlags::METHOD => self.build_method(ctx, class).into(),
PyMethodFlags::CLASS => self.build_classmethod(ctx, class).into(),
PyMethodFlags::STATIC => self.build_staticmethod(ctx, class).into(),
_ => unreachable!(),
})
bitflags::bitflags_match!(self.flags, {
PyMethodFlags::METHOD => self.build_method(ctx, class).into(),
PyMethodFlags::CLASS => self.build_classmethod(ctx, class).into(),
PyMethodFlags::STATIC => self.build_staticmethod(ctx, class).into(),
- _ => unreachable!(),
+ _ => self.build_function(ctx).into(),
})
🤖 Prompt for AI Agents
In vm/src/function/method.rs around lines 110 to 115, the to_proper_method
function panics when no PyMethodFlags are set because the bitflags_match! macro
falls through to the unreachable!() arm. To fix this, replace the unreachable!()
default case with code that returns a regular callable PyNativeFunction for
plain functions without METHOD, CLASS, or STATIC flags, ensuring the function
does not panic and returns a valid callable object in all cases.

@@ -194,7 +197,7 @@ impl PyMappingProxy {
#[pymethod]
fn __ior__(&self, _args: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error(format!(
"\"'|=' is not supported by {}; use '|' instead\"",
r#""'|=' is not supported by {}; use '|' instead""#,
Self::class(&vm.ctx)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Are the extra surrounding quotes intended here?

Copy link
Member

Choose a reason for hiding this comment

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

That looks weird, probably not

@@ -726,19 +726,22 @@ mod _socket {
}

#[pyfunction]
fn htonl(x: u32) -> u32 {
const fn htonl(x: u32) -> u32 {
Copy link
Member

Choose a reason for hiding this comment

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

#[pyfunction] is always wrapped to be a python function. const on these function will do nothing.

... nothing bad to do it though

@youknowone youknowone merged commit 8cac433 into RustPython:main Jun 28, 2025
12 checks passed
@ShaharNaveh ShaharNaveh deleted the constify-1 branch June 29, 2025 16:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants