-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
Conversation
""" WalkthroughThis change set focuses on marking many functions and methods across the codebase as Changes
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
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (11)
✨ Finishing Touches
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. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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 (2)
stdlib/src/socket.rs (1)
1669-1688
: IPv6 tuple parsing rejects 3- or 4-element tuples
from_tuple_ipv6
unconditionally forwards the wholetuple
slice toAddress::from_tuple
, which itself requireslen()==2
.
Any valid IPv6 3- or 4-element address ((host, port[, flowinfo[, scopeid]])
) will therefore raiseTypeError
.- 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 signatureThis const function signature is invalid. Const functions cannot:
- Take
&mut self
parameters- Perform mutations (this function contains
self.idx = ...
andself.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: Validconst fn
conversion.The method simply returns a field reference, making it appropriate for compile-time evaluation. Consider applying similar
const fn
conversions to the equivalentas_coro
methods inasyncgenerator.rs
andcoroutine.rs
for consistency.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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
andSelfIter
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
, andAttributeItem
).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 thekeys
,values
, andcopy
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 tomatch
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 toconst 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__
toconst 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! Appropriateconst 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! Safeconst 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! Appropriateconst 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: Appropriateconst 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: Validconst 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: Appropriateconst 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: Appropriateconst 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: Validconst 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 conversionsBoth
new()
andfrom_def()
methods correctly convert toconst 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 utilitiesBoth functions are correctly converted to
const fn
:
decompose_float()
uses only bitwise operations, conditionals, andf64::from_bits()
which are all const-compatiblediv()
performs simple conditional logic and arithmetic operationsThese 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 methodsAll three methods are correctly converted to
const fn
as they delegate to corresponding const methods onVec<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 accessorsBoth methods correctly convert to
const fn
as they only perform field access returning static references:
__name__()
returns&'static PyStrInterned
__doc__()
returnsOption<&'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 accessorsAll 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 andOption::Some
constructioninstance_dict()
does field access andOption::as_ref()
callas_raw()
simply returns the object pointerThese 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
toconst 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 returns0
for integers as a const fn, consistent with the similar implementation invm/src/builtins/float.rs
(lines 470-472) where float'simag
method also returns0.0
as a const fn.
684-686
: LGTM: const fn conversion for denominator is appropriate.Converting
denominator
toconst fn
is correct since integers always have a denominator of1
. 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 inhashlib.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
toconst 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
toconst fn
is correct since it calls other const functions (fix_sentinel
andmod_int
). This enables compile-time evaluation for usize hashing.
149-151
: LGTM: const fn conversion for fix_sentinel is appropriate.Converting
fix_sentinel
toconst 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
toconst 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 intoconst fn
– looks goodStraightforward 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-qualifiedto_function
– clear and safeMarking the simple accessor as
const
brings compile-time usability without side-effects.
134-147
: Const-qualifiedto_bound_method
– OKNo non-const operations involved. Change is safe and consistent with the rest of the refactor.
276-278
:HeapMethodDef::new
asconst fn
– OKHelps 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 intoconst fn
is harmless and aids compile-time construction.
260-262
:__bool__
asconst fn
– finePure length check, no objections.
277-284
:__len__
/is_empty
nowconst
– fineNo runtime effects; consistent with the overall refactor.
559-566
: Typed-tuple helpers unchanged apart from whitespaceNo functional changes. Nothing to report.
common/src/str.rs (1)
39-41
: LGTM: Appropriate const function conversionsThe 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 variantsas_wtf8
/kind
: Return field references/valuessubstitution_cost
: Contains only arithmetic and comparison operationsThese 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 constructorsConverting 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 constructionRemoving 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 conversionsThese const conversions are appropriate:
from_index_unchecked
: Simple value wrappingindex
: Conditional logic with no mutationssize
: Struct creation from field valuesshould_resize
: Pure arithmetic and conditional operationsAlso applies to: 65-71, 226-233, 236-242
141-148
: LGTM: Appropriate const constructorThe
GenIndexes::new
function only initializes struct fields, making it suitable forconst fn
.vm/src/builtins/float.rs (4)
30-33
: Const‐ifyingto_f64
looks goodMaking 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 toconst
– semantics preservedAll three methods are now trivially evaluable at compile time and still mirror CPython behaviour (
bool(-0.0)
remainsFalse
,NaN
remains truthy). No objections.
459-477
:__float__
,real
,imag
,conjugate
asconst fn
– OKBodies 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 clearerDropping the redundant
String::from
was the right call; no functional impact.common/src/cformat.rs (5)
3-3
: Bringing inbitflags_match!
reduces boilerplateNew import is legitimate; the crate is already in the dependency tree, so compile times won’t regress.
79-87
:CFloatType::case
→const fn
Pure pattern match with no heap interaction—safe and helpful for
match
-heavy const contexts.
103-112
:CFormatType::to_char
nowconst
– fineCompile-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 bothSIGN_CHAR
andBLANK_SIGN
set, the current ordering still yields"+"
, matching CPython precedence. If future flag combinations are added, keep this ordering invariant.
722-733
: Const getters onCFormatPart
are harmlessBeing 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 turnedconst
– 👍
len
,is_empty
,capacity
,is_full
, andremaining_capacity
now usable in const contexts; bodies are plain arithmetic, so no safety issues.
679-681
:CapacityError::new
asconst 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 forCodePoint
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 callsdecode_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
andcapacity
are correctly marked as const. The struct construction andVec::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
andclone_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 publicfrom_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
, andascii_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
andas_str
are correctly implemented as const functions. Field access andstr::from_utf8
calls are both const-compatible operations.Also applies to: 837-839
892-894
: Correct const functions for Wtf8 utility methods.The
chunks
andis_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
anddecode_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 alreadyconst fn
The
len_utf8
function is declared as apub const fn
inwtf8/src/core_char.rs:20
, so calling it from yourconst fn len_wtf8
is valid. No changes are required.
vm/src/function/method.rs
Outdated
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!(), | ||
}) |
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.
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.
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) |
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.
Are the extra surrounding quotes intended here?
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.
That looks weird, probably not
@@ -726,19 +726,22 @@ mod _socket { | |||
} | |||
|
|||
#[pyfunction] | |||
fn htonl(x: u32) -> u32 { | |||
const fn htonl(x: u32) -> u32 { |
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.
#[pyfunction] is always wrapped to be a python function. const on these function will do nothing.
... nothing bad to do it though
If this PR is too large I don't mind splitting it:)
Summary by CodeRabbit
New Features
const
, allowing their use in compile-time constant contexts.Refactor
Bug Fixes
Style