8000 Use `Self` where possible by ShaharNaveh · Pull Request #5892 · RustPython/RustPython · GitHub
[go: up one dir, main page]

Skip to content

Use Self where possible #5892

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 11 commits into from
Jul 4, 2025
Merged

Use Self where possible #5892

merged 11 commits into from
Jul 4, 2025

Conversation

ShaharNaveh
Copy link
Contributor
@ShaharNaveh ShaharNaveh commented Jul 3, 2025

Summary by CodeRabbit

  • Refactor
    • Updated internal code style to use more generic type references, improving consistency and maintainability. Many methods now use Self instead of explicit type names for return types, parameter types, and pattern matching.
    • Method and constant signatures were updated across various modules for improved generic support and code clarity.
    • No changes to logic, features, or user-facing behavior. All modifications are internal and stylistic.

Copy link
Contributor
coderabbitai bot commented Jul 3, 2025

Walkthrough

This pull request performs a comprehensive, project-wide refactor to replace explicit type and enum variant references with the Rust Self keyword in method bodies, constructors, pattern matches, and return types. The changes affect numerous files across the codebase, improving code conciseness, consistency, and idiomatic style, without altering any logic, control flow, or error handling.

Changes

File(s) Change Summary
common/src/atomic.rs, common/src/refcount.rs, compiler/codegen/src/compile.rs, compiler/codegen/src/ir.rs, compiler/codegen/src/lib.rs, compiler/codegen/src/symboltable.rs, compiler/core/src/bytecode.rs, compiler/core/src/frozen.rs, compiler/core/src/mode.rs, compiler/src/lib.rs, derive-impl/src/compile_bytecode.rs, derive-impl/src/error.rs, derive-impl/src/from_args.rs, stdlib/src/array.rs, stdlib/src/bz2.rs, stdlib/src/contextvars.rs, stdlib/src/csv.rs, stdlib/src/hashlib.rs, stdlib/src/posixsubprocess.rs, stdlib/src/pyexpat.rs, stdlib/src/pystruct.rs, stdlib/src/resource.rs, stdlib/src/select.rs, stdlib/src/socket.rs, stdlib/src/syslog.rs, stdlib/src/unicodedata.rs, stdlib/src/zlib.rs, vm/src/buffer.rs, vm/src/builtins/asyncgenerator.rs, vm/src/builtins/bool.rs, vm/src/builtins/builtin_func.rs, vm/src/builtins/bytearray.rs, vm/src/builtins/bytes.rs, vm/src/builtins/classmethod.rs, vm/src/builtins/code.rs, vm/src/builtins/complex.rs, vm/src/builtins/coroutine.rs, vm/src/builtins/dict.rs, vm/src/builtins/enumerate.rs, vm/src/builtins/float.rs, vm/src/builtins/function.rs, vm/src/builtins/generator.rs, vm/src/builtins/genericalias.rs, vm/src/builtins/int.rs, vm/src/builtins/iter.rs, vm/src/builtins/list.rs, vm/src/builtins/map.rs, vm/src/builtins/mappingproxy.rs, vm/src/builtins/memory.rs, vm/src/builtins/module.rs, vm/src/builtins/object.rs, vm/src/builtins/property.rs, vm/src/builtins/range.rs, vm/src/builtins/set.rs, vm/src/builtins/slice.rs, vm/src/builtins/staticmethod.rs, vm/src/builtins/str.rs, vm/src/builtins/super.rs, vm/src/builtins/traceback.rs, vm/src/builtins/tuple.rs, vm/src/builtins/type.rs, vm/src/builtins/weakproxy.rs, vm/src/builtins/zip.rs, vm/src/bytes_inner.rs, vm/src/codecs.rs, vm/src/convert/try_from.rs, vm/src/coroutine.rs, vm/src/dict_inner.rs, vm/src/exceptions.rs, vm/src/format.rs, vm/src/frame.rs, vm/src/function/argument.rs, vm/src/function/arithmetic.rs, vm/src/function/buffer.rs, vm/src/function/either.rs, vm/src/function/fspath.rs, vm/src/function/number.rs, vm/src/function/protocol.rs, vm/src/intern.rs, vm/src/object/core.rs, vm/src/object/ext.rs, vm/src/object/traverse.rs, vm/src/object/traverse_object.rs, vm/src/ospath.rs, vm/src/protocol/buffer.rs, vm/src/protocol/iter.rs, vm/src/protocol/mapping.rs, vm/src/protocol/number.rs, vm/src/protocol/object.rs, vm/src/protocol/sequence.rs, vm/src/py_io.rs, vm/src/scope.rs, vm/src/sequence.rs, vm/src/sliceable.rs, vm/src/stdlib/ast/basic.rs, vm/src/stdlib/ast/exception.rs, vm/src/stdlib/ast/expression.rs, vm/src/stdlib/ast/statement.rs, vm/src/stdlib/ast/string.rs, vm/src/stdlib/ast/type_ignore.rs Refactored to use Self instead of explicit type/enum names in constructors, pattern matches, method return types, type annotations, and trait implementations. Updated signatures and internal calls for improved idiomatic Rust style. No logic or control flow changes.
common/src/boxvec.rs, common/src/cformat.rs, common/src/format.rs, common/src/linked_list.rs, common/src/lock/cell_lock.rs, common/src/lock/thread_mutex.rs, vm/src/builtins/bytearray.rs, vm/src/builtins/bytes.rs, vm/src/builtins/code.rs, vm/src/builtins/set.rs, vm/src/builtins/str.rs, vm/src/dict_inner.rs, vm/src/protocol/mapping.rs, vm/src/protocol/number.rs, vm/src/protocol/object.rs, vm/src/protocol/sequence.rs, vm/src/sequence.rs, vm/src/scope.rs Updated method and associated type signatures to use Self in place of explicit type names, improving generics and consistency.
derive-impl/src/compile_bytecode.rs, derive-impl/src/error.rs, derive-impl/src/from_args.rs, stdlib/src/array.rs, stdlib/src/zlib.rs, vm/src/builtins/asyncgenerator.rs, vm/src/builtins/bytearray.rs, vm/src/builtins/bytes.rs, vm/src/builtins/code.rs, vm/src/builtins/dict.rs, vm/src/builtins/set.rs, vm/src/builtins/traceback.rs, vm/src/builtins/type.rs, vm/src/bytes_inner.rs, vm/src/dict_inner.rs, vm/src/protocol/iter.rs, vm/src/sequence.rs, vm/src/scope.rs Changed public method signatures and trait implementations to use Self in return types and type parameters.

Sequence Diagram(s)

Omitted due to the purely stylistic nature of the changes.

Possibly related PRs

  • RustPython/RustPython#5823: Introduces a new builtins field and a Constructor trait implementation for PyFunction, which is related to this PR’s refactoring of internal type references in vm/src/builtins/function.rs.

Suggested reviewers

  • youknowone

Poem

In fields of code where rabbits run,
We swap our names for Self—what fun!
No more Py or Rusty call,
Just Self stands proud, embracing all.
With every hop, our code grows neat,
Refactored paths beneath our feet.
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Clippy (1.86.0)
Updating git repository `https://github.com/youknowone/ferrilab`

error: failed to load source for dependency radium

Caused by:
Unable to update https://github.com/youknowone/ferrilab?branch=fix-nightly#4a301c3a

Caused by:
failed to create directory /usr/local/git/db/ferrilab-ed7d38936952b47e

Caused by:
Permission denied (os error 13)

✨ 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.

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
Contributor
@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: 3

🧹 Nitpick comments (6)
vm/src/builtins/type.rs (1)

436-439: Tiny nit: remove the superfluous explicit type in the closure.

The closure map(|cls| -> &Self { cls }) explicitly annotates the return type, but type-inference already knows it’s &Self. Dropping the arrow clause makes the chain shorter.

-            .chain(self.mro.read().iter().map(|cls| -> &Self { cls }))
+            .chain(self.mro.read().iter().map(|cls| cls))
vm/src/builtins/bytearray.rs (1)

650-673: Consider taking &self instead of consuming self for lstrip/rstrip.

These methods currently take ownership of the PyRef, which forces callers to re-bind:

ba = ba.lstrip(...)

Using a shared reference would avoid that extra move/cloning cost:

- fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
+ fn lstrip(&self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {

The same applies to rstrip.

vm/src/bytes_inner.rs (4)

345-350: Avoid passing large structs by value

needle: Either<Self, PyIntRef> moves a complete Vec<u8> every call.
An API that takes references avoids this allocation and still keeps the caller ergonomics:

-    pub fn contains(&self, needle: Either<Self, PyIntRef>, vm: &VirtualMachine) -> PyResult<bool> {
+    pub fn contains(
+        &self,
+        needle: Either<&Self, &PyIntRef>,
+        vm: &VirtualMachine,
+    ) -> PyResult<bool> {
         Ok(match needle {
-            Either::A(byte) => self.elements.contains_str(byte.elements.as_slice()),
-            Either::B(int) => self.elements.contains(&int.as_bigint().byte_or(vm)?),
+            Either::A(byte) => self.elements.contains_str(byte.elements.as_slice()),
+            Either::B(int)  => self.elements.contains(&int.as_bigint().byte_or(vm)?),
         })
     }

(Same idea applies to most of the other newly‐Self parameters below.)


570-585: maketrans still consumes two full buffers – worth revisiting

The method now reads from: Self, to: Self; this already cloned the data before the PR, so it is not a new issue.
If you ever touch this again, consider &Self to prevent an otherwise needless move.


758-801: Large replace helpers – unchanged semantics, but consider borrowing

All four helpers (replace_interleave, replace_delete, replace_in_place, replace_general) now take Self by value, as before.
Given these are potentially large buffers, a future micro-optimisation could pass &Self and clone only when needed, but that is outside the scope of this PR.

Also applies to: 802-827, 831-872, 876-924


1022-1027: Potential ambiguity with Self::new() / Self::with_capacity()

Inside the impl AnyStrContainer<[u8]> for Vec<u8> block, Self::new() and Self::with_capacity() currently resolve to the inherent Vec methods, so there is no recursion.
However clippy can flag this as unclear. Using the fully-qualified inherent path avoids any doubt:

-        Self::new()
+        Vec::new()
...
-        Self::with_capacity(capacity)
+        Vec::with_capacity(capacity)

Run cargo clippy -- -W clippy::needless_return -W clippy::unnecessary_wraps (or the full clippy set) to ensure there is no warning about the ambiguous call resolution.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a2a6af and fe13f80.

📒 Files selected for processing (107)
  • common/src/atomic.rs (1 hunks)
  • common/src/boxvec.rs (3 hunks)
  • common/src/cformat.rs (5 hunks)
  • common/src/format.rs (17 hunks)
  • common/src/linked_list.rs (2 hunks)
  • common/src/lock/cell_lock.rs (3 hunks)
  • common/src/lock/thread_mutex.rs (2 hunks)
  • common/src/refcount.rs (1 hunks)
  • common/src/str.rs (1 hunks)
  • compiler/codegen/src/compile.rs (1 hunks)
  • compiler/codegen/src/ir.rs (3 hunks)
  • compiler/codegen/src/lib.rs (1 hunks)
  • compiler/codegen/src/symboltable.rs (4 hunks)
  • compiler/core/src/bytecode.rs (10 hunks)
  • compiler/core/src/frozen.rs (3 hunks)
  • compiler/core/src/mode.rs (1 hunks)
  • compiler/src/lib.rs (2 hunks)
  • derive-impl/src/compile_bytecode.rs (2 hunks)
  • derive-impl/src/error.rs (2 hunks)
  • derive-impl/src/from_args.rs (3 hunks)
  • stdlib/src/array.rs (8 hunks)
  • stdlib/src/bz2.rs (1 hunks)
  • stdlib/src/contextvars.rs (3 hunks)
  • stdlib/src/csv.rs (5 hunks)
  • stdlib/src/hashlib.rs (7 hunks)
  • stdlib/src/posixsubprocess.rs (2 hunks)
  • stdlib/src/pyexpat.rs (1 hunks)
  • stdlib/src/pystruct.rs (4 hunks)
  • stdlib/src/resource.rs (1 hunks)
  • stdlib/src/select.rs (4 hunks)
  • stdlib/src/socket.rs (2 hunks)
  • stdlib/src/syslog.rs (1 hunks)
  • stdlib/src/unicodedata.rs (2 hunks)
  • stdlib/src/zlib.rs (4 hunks)
  • vm/src/buffer.rs (6 hunks)
  • vm/src/builtins/asyncgenerator.rs (2 hunks)
  • vm/src/builtins/bool.rs (1 hunks)
  • vm/src/builtins/builtin_func.rs (1 hunks)
  • vm/src/builtins/bytearray.rs (8 hunks)
  • vm/src/builtins/bytes.rs (9 hunks)
  • vm/src/builtins/classmethod.rs (1 hunks)
  • vm/src/builtins/code.rs (3 hunks)
  • vm/src/builtins/complex.rs (4 hunks)
  • vm/src/builtins/coroutine.rs (1 hunks)
  • vm/src/builtins/dict.rs (6 hunks)
  • vm/src/builtins/enumerate.rs (1 hunks)
  • vm/src/builtins/float.rs (3 hunks)
  • vm/src/builtins/function.rs (5 hunks)
  • vm/src/builtins/generator.rs (1 hunks)
  • vm/src/builtins/genericalias.rs (3 hunks)
  • vm/src/builtins/int.rs (8 hunks)
  • vm/src/builtins/iter.rs (1 hunks)
  • vm/src/builtins/list.rs (3 hunks)
  • vm/src/builtins/map.rs (1 hunks)
  • vm/src/builtins/mappingproxy.rs (1 hunks)
  • vm/src/builtins/memory.rs (3 hunks)
  • vm/src/builtins/module.rs (2 hunks)
  • vm/src/builtins/object.rs (1 hunks)
  • vm/src/builtins/property.rs (2 hunks)
  • vm/src/builtins/range.rs (5 hunks)
  • vm/src/builtins/set.rs (11 hunks)
  • vm/src/builtins/slice.rs (2 hunks)
  • vm/src/builtins/staticmethod.rs (1 hunks)
  • vm/src/builtins/str.rs (23 hunks)
  • vm/src/builtins/super.rs (2 hunks)
  • vm/src/builtins/traceback.rs (2 hunks)
  • vm/src/builtins/tuple.rs (1 hunks)
  • vm/src/builtins/type.rs (7 hunks)
  • vm/src/builtins/weakproxy.rs (1 hunks)
  • vm/src/builtins/zip.rs (1 hunks)
  • vm/src/bytes_inner.rs (16 hunks)
  • vm/src/codecs.rs (3 hunks)
  • vm/src/convert/try_from.rs (1 hunks)
  • vm/src/coroutine.rs (2 hunks)
  • vm/src/dict_inner.rs (5 hunks)
  • vm/src/exceptions.rs (2 hunks)
  • vm/src/format.rs (2 hunks)
  • vm/src/frame.rs (3 hunks)
  • vm/src/function/argument.rs (11 hunks)
  • vm/src/function/arithmetic.rs (1 hunks)
  • vm/src/function/buffer.rs (1 hunks)
  • vm/src/function/either.rs (1 hunks)
  • vm/src/function/fspath.rs (2 hunks)
  • vm/src/function/number.rs (2 hunks)
  • vm/src/function/protocol.rs (3 hunks)
  • vm/src/intern.rs (1 hunks)
  • vm/src/object/core.rs (11 hunks)
  • vm/src/object/ext.rs (1 hunks)
  • vm/src/object/traverse.rs (1 hunks)
  • vm/src/object/traverse_object.rs (2 hunks)
  • vm/src/ospath.rs (2 hunks)
  • vm/src/protocol/buffer.rs (1 hunks)
  • vm/src/protocol/iter.rs (3 hunks)
  • vm/src/protocol/mapping.rs (1 hunks)
  • vm/src/protocol/number.rs (2 hunks)
  • vm/src/protocol/object.rs (6 hunks)
  • vm/src/protocol/sequence.rs (1 hunks)
  • vm/src/py_io.rs (1 hunks)
  • vm/src/scope.rs (1 hunks)
  • vm/src/sequence.rs (1 hunks)
  • vm/src/sliceable.rs (1 hunks)
  • vm/src/stdlib/ast/basic.rs (1 hunks)
  • vm/src/stdlib/ast/exception.rs (3 hunks)
  • vm/src/stdlib/ast/expression.rs (4 hunks)
  • vm/src/stdlib/ast/statement.rs (22 hunks)
  • vm/src/stdlib/ast/string.rs (1 hunks)
  • vm/src/stdlib/ast/type_ignore.rs (2 hunks)
⛔ Files not processed due to max files limit (21)
  • vm/src/stdlib/ast/type_parameters.rs
  • vm/src/stdlib/collections.rs
  • vm/src/stdlib/functools.rs
  • vm/src/stdlib/io.rs
  • vm/src/stdlib/itertools.rs
  • vm/src/stdlib/operator.rs
  • vm/src/stdlib/os.rs
  • vm/src/stdlib/posix.rs
  • vm/src/stdlib/sre.rs
  • vm/src/stdlib/sys.rs
  • vm/src/stdlib/thread.rs
  • vm/src/stdlib/time.rs
  • vm/src/stdlib/typevar.rs
  • vm/src/stdlib/typing.rs
  • vm/src/vm/context.rs
  • vm/src/vm/method.rs
  • vm/src/vm/mod.rs
  • vm/src/vm/setting.rs
  • vm/src/vm/thread.rs
  • vm/src/warn.rs
  • vm/sre_engine/src/engine.rs
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.rs`: Follow the default rustfmt code style (`cargo fmt` to format) Always ...

**/*.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

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • vm/src/builtins/zip.rs
  • compiler/core/src/mode.rs
  • stdlib/src/bz2.rs
  • vm/src/builtins/mappingproxy.rs
  • vm/src/builtins/map.rs
  • common/src/cformat.rs
  • vm/src/builtins/classmethod.rs
  • vm/src/builtins/staticmethod.rs
  • vm/src/builtins/generator.rs
  • vm/src/function/buffer.rs
  • vm/src/function/arithmetic.rs
  • vm/src/format.rs
  • compiler/src/lib.rs
  • vm/src/protocol/buffer.rs
  • vm/src/builtins/iter.rs
  • vm/src/builtins/coroutine.rs
  • vm/src/builtins/slice.rs
  • stdlib/src/hashlib.rs
  • vm/src/function/number.rs
  • compiler/codegen/src/lib.rs
  • vm/src/builtins/enumerate.rs
  • common/src/atomic.rs
  • vm/src/protocol/sequence.rs
  • vm/src/stdlib/ast/basic.rs
  • stdlib/src/posixsubprocess.rs
  • vm/src/stdlib/ast/string.rs
  • vm/src/sequence.rs
  • common/src/refcount.rs
  • common/src/lock/thread_mutex.rs
  • vm/src/builtins/weakproxy.rs
  • vm/src/builtins/builtin_func.rs
  • vm/src/stdlib/ast/expression.rs
  • vm/src/protocol/mapping.rs
  • vm/src/object/traverse.rs
  • vm/src/convert/try_from.rs
  • common/src/linked_list.rs
  • vm/src/coroutine.rs
  • derive-impl/src/compile_bytecode.rs
  • stdlib/src/pyexpat.rs
  • vm/src/function/fspath.rs
  • vm/src/builtins/traceback.rs
  • common/src/str.rs
  • vm/src/py_io.rs
  • stdlib/src/resource.rs
  • vm/src/builtins/object.rs
  • vm/src/builtins/memory.rs
  • compiler/codegen/src/symboltable.rs
  • stdlib/src/syslog.rs
  • derive-impl/src/from_args.rs
  • vm/src/builtins/function.rs
  • vm/src/builtins/tuple.rs
  • vm/src/builtins/int.rs
  • vm/src/builtins/property.rs
  • vm/src/intern.rs
  • vm/src/builtins/bool.rs
  • vm/src/builtins/genericalias.rs
  • stdlib/src/zlib.rs
  • stdlib/src/pystruct.rs
  • vm/src/ospath.rs
  • vm/src/stdlib/ast/type_ignore.rs
  • vm/src/object/ext.rs
  • vm/src/builtins/float.rs
  • vm/src/builtins/list.rs
  • vm/src/protocol/number.rs
  • stdlib/src/unicodedata.rs
  • vm/src/builtins/super.rs
  • vm/src/function/argument.rs
  • vm/src/stdlib/ast/exception.rs
  • compiler/codegen/src/ir.rs
  • stdlib/src/contextvars.rs
  • stdlib/src/select.rs
  • vm/src/sliceable.rs
  • vm/src/codecs.rs
  • vm/src/builtins/asyncgenerator.rs
  • vm/src/builtins/code.rs
  • common/src/lock/cell_lock.rs
  • vm/src/scope.rs
  • vm/src/function/protocol.rs
  • vm/src/object/traverse_object.rs
  • vm/src/builtins/module.rs
  • compiler/core/src/bytecode.rs
  • vm/src/object/core.rs
  • compiler/codegen/src/compile.rs
  • vm/src/frame.rs
  • common/src/boxvec.rs
  • vm/src/buffer.rs
  • stdlib/src/csv.rs
  • vm/src/exceptions.rs
  • derive-impl/src/error.rs
  • vm/src/stdlib/ast/statement.rs
  • compiler/core/src/frozen.rs
  • vm/src/builtins/dict.rs
  • vm/src/builtins/range.rs
  • vm/src/function/either.rs
  • stdlib/src/socket.rs
  • vm/src/builtins/complex.rs
  • stdlib/src/array.rs
  • vm/src/protocol/iter.rs
  • vm/src/protocol/object.rs
  • vm/src/dict_inner.rs
  • vm/src/builtins/bytes.rs
  • common/src/format.rs
  • vm/src/builtins/bytearray.rs
  • vm/src/builtins/set.rs
  • vm/src/builtins/str.rs
  • vm/src/builtins/type.rs
  • vm/src/bytes_inner.rs
🧠 Learnings (41)
📓 Common learnings
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow the default rustfmt code style (`cargo fmt` to format)
vm/src/builtins/map.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
common/src/cformat.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow the default rustfmt code style (`cargo fmt` to format)
vm/src/builtins/classmethod.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/staticmethod.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/generator.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/function/arithmetic.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/format.rs (2)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow the default rustfmt code style (`cargo fmt` to format)
compiler/src/lib.rs (2)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
stdlib/src/hashlib.rs (2)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
compiler/codegen/src/lib.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/protocol/sequence.rs (2)
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.810Z
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: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.810Z
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.
stdlib/src/posixsubprocess.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
vm/src/stdlib/ast/expression.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
vm/src/protocol/mapping.rs (2)
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.810Z
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: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.810Z
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.
vm/src/py_io.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow the default rustfmt code style (`cargo fmt` to format)
vm/src/builtins/object.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/function.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/int.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/property.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
stdlib/src/zlib.rs (2)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
stdlib/src/pystruct.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/float.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/list.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/protocol/number.rs (3)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
Learnt from: moreal
PR: RustPython/RustPython#5847
File: vm/src/stdlib/stat.rs:547-567
Timestamp: 2025-06-27T14:47:28.810Z
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.810Z
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.
vm/src/builtins/super.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/function/argument.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
vm/src/stdlib/ast/exception.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
vm/src/builtins/code.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/module.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/object/core.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
vm/src/exceptions.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/stdlib/ast/statement.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/range.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/complex.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/protocol/iter.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/protocol/object.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/bytes.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
common/src/format.rs (2)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow the default rustfmt code style (`cargo fmt` to format)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Follow Rust best practices for error handling and memory management
vm/src/builtins/str.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
vm/src/builtins/type.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
🧬 Code Graph Analysis (5)
vm/src/builtins/object.rs (13)
vm/src/builtins/bytes.rs (1)
  • new_ref (102-104)
vm/src/builtins/list.rs (1)
  • new_ref (66-68)
vm/src/builtins/bytearray.rs (1)
  • new_ref (76-78)
vm/src/builtins/set.rs (1)
  • new_ref (42-46)
vm/src/builtins/classmethod.rs (1)
  • new_ref (114-122)
vm/src/builtins/complex.rs (1)
  • new_ref (235-237)
vm/src/builtins/function.rs (1)
  • new_ref (729-735)
vm/src/builtins/dict.rs (2)
  • new_ref (54-56)
  • dict (755-755)
vm/src/builtins/staticmethod.rs (1)
  • new_ref (64-72)
vm/src/builtins/tuple.rs (1)
  • new_ref (176-183)
vm/src/builtins/str.rs (1)
  • new_ref (397-400)
vm/src/object/core.rs (3)
  • new_ref (1046-1051)
  • Self (373-376)
  • dict (709-711)
vm/src/builtins/namespace.rs (1)
  • new_ref (30-36)
vm/src/object/ext.rs (1)
vm/src/object/core.rs (1)
  • Self (373-376)
vm/src/builtins/float.rs (5)
vm/src/builtins/complex.rs (2)
  • from (50-52)
  • other (413-413)
vm/src/builtins/int.rs (4)
  • from (45-47)
  • other (300-301)
  • other (311-311)
  • other (719-720)
vm/src/builtins/list.rs (1)
  • other (134-134)
vm/src/builtins/builtin_func.rs (1)
  • other (216-216)
vm/src/builtins/memory.rs (1)
  • other (333-333)
vm/src/stdlib/ast/statement.rs (3)
vm/src/stdlib/ast/expression.rs (2)
  • ast_from_object (51-139)
  • ast_to_object (8-49)
vm/src/class.rs (1)
  • static_type (25-33)
vm/src/stdlib/ast.rs (1)
  • range_from_object (166-189)
vm/src/builtins/bytes.rs (6)
vm/src/builtins/bytearray.rs (10)
  • repeat (95-97)
  • center (338-340)
  • ljust (343-345)
  • rjust (348-350)
  • join (358-360)
  • iter (837-842)
  • translate (425-427)
  • mod_ (540-543)
  • lstrip (650-660)
  • rstrip (663-673)
vm/src/builtins/tuple.rs (2)
  • repeat (196-210)
  • iter (420-425)
vm/src/builtins/str.rs (9)
  • repeat (483-500)
  • center (1284-1291)
  • ljust (1294-1301)
  • rjust (1304-1311)
  • join (1121-1139)
  • iter (1514-1519)
  • translate (1329-1359)
  • lstrip (800-816)
  • rstrip (819-835)
vm/src/protocol/sequence.rs (1)
  • repeat (135-149)
vm/src/bytes_inner.rs (7)
  • center (520-526)
  • ljust (528-534)
  • rjust (536-542)
  • join (551-554)
  • translate (587-607)
  • lstrip (619-625)
  • rstrip (627-633)
vm/src/builtins/weakproxy.rs (1)
  • __bytes__ (98-100)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Run tests under miri
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (240)
vm/src/stdlib/ast/string.rs (1)

258-259: LGTM! Excellent use of Self in enum pattern matching.

The replacement of explicit JoinedStrPart:: with Self:: in the match arms improves code conciseness and follows Rust idioms. This change maintains the same functionality while making the code more maintainable.

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

39-39: LGTM! Proper use of Self in struct instantiation.

The replacement of explicit PyZip with Self in the struct instantiation improves code conciseness and follows Rust best practices. The functionality remains identical while the code becomes more maintainable.

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

33-35: LGTM! Correct usage of Self in constructor method.

The replacement of explicit PyCoroutine with Self in the struct instantiation follows Rust best practices and improves code readability. The constructor logic remains unchanged while the code becomes more concise and maintainable.

vm/src/function/arithmetic.rs (1)

37-38: LGTM! Excellent use of Self in enum pattern matching.

The replacement of explicit PyArithmeticValue:: with Self:: in the match arms improves code conciseness and follows Rust idioms. This change maintains the same functionality while making the code more maintainable and readable.

common/src/atomic.rs (1)

68-70: LGTM! Proper use of Self in constructor method.

The replacement of explicit OncePtr with Self in the struct instantiation follows Rust best practices and improves code readability. The constructor logic remains unchanged while the code becomes more concise and maintainable.

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

35-39: LGTM! Improved idiomatic Rust usage.

Using Self instead of the explicit type name PyGenerator within the impl block is more concise and idiomatic.

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

47-50: LGTM! Improved idiomatic Rust usage.

Using Self instead of the explicit type name PyEnumerate within the impl block is more concise and idiomatic.

stdlib/src/bz2.rs (1)

50-52: LGTM! Improved idiomatic Rust usage.

Using Self::StreamEnd instead of the explicit enum name Status::StreamEnd within the impl block is more concise and idiomatic.

compiler/core/src/mode.rs (1)

16-18: LGTM! Improved idiomatic Rust usage.

Using Self:: instead of the explicit enum name Mode:: within the impl block is more concise and idiomatic.

stdlib/src/syslog.rs (1)

52-53: LGTM! Improved idiomatic Rust usage.

Using Self:: instead of the explicit enum name GlobalIdent:: within the impl block is more concise and idiomatic.

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

95-97: LGTM! Excellent use of idiomatic Rust style.

Using Self instead of the explicit type name within impl blocks is the preferred Rust idiom. This change improves maintainability and follows best practices.

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

49-52: LGTM! Consistent with idiomatic Rust style.

Using Self instead of explicit type names within impl blocks is the preferred approach in Rust. This change improves code consistency and maintainability.

vm/src/stdlib/ast/basic.rs (1)

17-17: LGTM! Proper use of Self in constructor call.

Using Self::new() instead of the fully qualified type name within impl blocks is idiomatic Rust. This change improves code readability and maintainability.

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

30-33: LGTM! Consistent idiomatic Rust style.

Using Self for struct initialization within impl blocks is the preferred Rust idiom. This change improves code consistency and maintainability across the codebase.

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

32-33: LGTM! Idiomatic enum variant matching.

Using Self:: for enum variant matching within impl blocks is the preferred Rust idiom. This change improves code consistency and makes the code more maintainable.

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

31-32: LGTM! Excellent use of Self for enum variants.

This change improves code readability by using the idiomatic Self:: syntax instead of explicit enum variant paths within the impl block.

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

147-148: LGTM! Clean improvement using Self in pattern matching.

The use of Self::A and Self::B instead of explicit Either::A and Either::B follows Rust idioms and enhances code maintainability.

stdlib/src/pyexpat.rs (1)

68-75: LGTM! Idiomatic constructor using Self.

Replacing the explicit struct name with Self in the constructor is a clean improvement that makes the code more maintainable and follows Rust best practices.

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

339-339: LGTM! Proper use of Self for method calls.

Using Self::new_ref instead of PyTuple::new_ref within the impl block is more concise and follows Rust conventions for referring to the current type.

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

267-267: LGTM! Clean constructor syntax using Self.

The change from NativeFunctionOrMethod(...) to Self(...) is a nice stylistic improvement that makes the code more readable and idiomatic.

vm/src/function/number.rs (1)

44-45: Use of Self constructor is clear and idiomatic
Nothing to flag – the swap to Self { value } is correct and keeps the logic unchanged.

compiler/codegen/src/compile.rs (1)

286-286: Excellent use of Self in constructor method.

This change makes the code more concise and idiomatic by using Self instead of the explicit struct name within the impl block. This is the preferred Rust style for constructor methods and improves maintainability.

vm/src/function/buffer.rs (1)

174-176: Idiomatic use of Self – looks good

Replacing the explicit variant path with Self::String is inline with Rust style and keeps the logic unchanged.

vm/src/protocol/buffer.rs (1)

66-72: Constructor call shortened with Self::new – no concerns

The switch from PyBuffer::new to Self::new is purely stylistic within the same impl scope and does not affect behaviour.

common/src/lock/thread_mutex.rs (1)

24-28: Consistent Self usage in constants & ctor

Both the INIT constant and new constructor now use Self for clarity. Implementation remains identical; no functional impact observed.

Also applies to: 82-85

vm/src/function/fspath.rs (1)

28-35: Enum variant shorthand applied consistently

All occurrences now use Self::{Str,Bytes} for pattern matching & construction. Improves readability without altering semantics.

Also applies to: 64-66, 72-74, 79-81, 86-88

compiler/codegen/src/lib.rs (1)

31-63: LGTM: Idiomatic use of Self in pattern matching.

The replacement of explicit enum variant paths with Self:: notation makes the code more concise and follows Rust best practices. The logic remains unchanged while improving readability.

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

55-55: LGTM: Consistent use of Self in struct construction.

Using Self { value } instead of PyFloat { value } improves code maintainability and follows Rust idioms.


526-526: LGTM: Consistent generic parameter usage.

The change from payload_if_subclass::<PyFloat> to payload_if_subclass::<Self> aligns with similar patterns used in other builtin types (as seen in vm/src/builtins/list.rs, vm/src/builtins/complex.rs, and vm/src/builtins/int.rs) and improves code consistency.

vm/src/py_io.rs (1)

48-48: LGTM: Idiomatic trait method dispatch.

Using <Self as fmt::Write> instead of <String as fmt::Write> makes the code more generic and follows Rust best practices.

common/src/cformat.rs (4)

106-109: LGTM: Consistent enum variant pattern matching.

Using Self::Number(x), Self::Float(x), etc. instead of the fully qualified variants improves code conciseness while maintaining clarity.


122-122: LGTM: Idiomatic struct construction in trait implementation.

Using Self::Quantity(quantity) follows Rust best practices for constructor methods.


341-341: LGTM: Consistent static method calls.

Using Self::compute_fill_string instead of the fully qualified method name improves maintainability and follows Rust conventions.

Also applies to: 364-364


724-724: LGTM: Simplified pattern matching.

Using Self::Spec instead of CFormatPart::Spec in pattern matches makes the code more concise and idiomatic.

Also applies to: 730-730

vm/src/stdlib/ast/expression.rs (2)

682-682: LGTM: Idiomatic pattern matching and construction for ExprYield.

Using Self in both destructuring (let Self { value, range } = self;) and construction (Ok(Self { ... })) follows Rust best practices and improves code maintainability.

Also applies to: 698-698


1023-1023: LGTM: Consistent pattern matching and construction for ExprList.

The use of Self in both destructuring and construction patterns aligns with the changes made to other AST node types and follows Rust idioms.

Also applies to: 1041-1041

vm/src/coroutine.rs (2)

14-15: LGTM! Idiomatic use of Self in enum variants.

The replacement of ExecutionResult::Yield and ExecutionResult::Return with Self::Yield and Self::Return is correct and follows Rust best practices for more concise, maintainable code.


52-52: LGTM! Proper use of Self in constructor.

Using Self instead of the explicit struct name Coro in the constructor is idiomatic Rust and improves code maintainability.

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

51-51: LGTM! Correct use of Self in constructor implementation.

Replacing PySuper with Self in the Constructor trait implementation is idiomatic and maintains the same functionality while improving code readability.


208-208: LGTM! Appropriate use of Self in descriptor implementation.

Using Self instead of PySuper in the GetDescriptor trait implementation follows Rust best practices and improves code maintainability.

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

56-56: LGTM! Idiomatic constructor implementation.

Replacing PyWeakProxy with Self in the constructor is correct and follows Rust best practices for more concise and maintainable code.

vm/src/function/argument.rs (6)

81-84: LGTM! Consistent use of Self in FuncArgs implementations.

The replacement of explicit FuncArgs with Self in the From trait implementations and methods improves code consistency and follows Rust idioms.

Also applies to: 90-93, 128-131


253-253: LGTM! Proper use of Self in error conversion.

Using Self::Exception instead of ArgumentError::Exception is idiomatic and maintains the same functionality.


265-281: LGTM! Consistent enum variant usage with Self.

Replacing ArgumentError variants with Self variants in the match expression is correct and improves code maintainability.


348-348: LGTM! Idiomatic Self usage in KwArgs implementations.

The consistent use of Self instead of explicit KwArgs type names across various trait implementations follows Rust best practices.

Also applies to: 362-362, 368-368, 381-381


462-462: LGTM! Proper constructor pattern with Self.

Using Self in the PosArgs constructor is idiomatic and maintains consistency with the codebase improvements.


504-506: LGTM! Correct enum variant usage in OptionalArg.

Replacing explicit OptionalArg variants with Self variants in both pattern matching and construction is idiomatic Rust and improves code readability.

Also applies to: 535-537

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

496-496: LGTM! Idiomatic pointer cast with Self.

Replacing *const PyObject with *const Self in the unique_id method is correct and follows Rust best practices. This change aligns with the pattern used elsewhere in the codebase (as seen in vm/src/object/core.rs) and improves code maintainability.

vm/src/sequence.rs (1)

142-142: Excellent use of Self for improved type genericity.

This change makes the return type more generic and follows Rust best practices by using Self instead of the concrete type Vec<T>.

vm/src/stdlib/ast/type_ignore.rs (1)

11-11: Great use of Self for enum variant references.

Replacing TypeIgnore::TypeIgnore with Self::TypeIgnore makes the code more concise and follows Rust idioms for referencing enum variants within impl blocks.

Also applies to: 21-21

vm/src/sliceable.rs (1)

309-309: Improved type cast using Self.

Using Self instead of the explicit isize type makes the cast more self-documenting and consistent with the surrounding codebase.

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

68-68: Excellent refactoring to use Self in constructors and type annotations.

These changes make the code more maintainable by using Self instead of repeating the PySlice type name. This follows Rust best practices and reduces the need for updates if the type name ever changes.

Also applies to: 74-78, 83-87

vm/src/function/either.rs (1)

31-31: Proper use of Self in trait bounds.

The change correctly uses Self to refer to PyObjectRef (the target type) in the trait bounds, making the implementation more generic and self-documenting.

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

31-31: Good use of Self in constructor!

Using Self instead of the explicit struct name improves code maintainability and follows Rust best practices.


66-66: Excellent iterator return type improvement!

Using Self as the iterator item type makes the method signature more generic and idiomatic.

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

237-237: Clean return type improvement!

Using Self in the return type makes the function signature more maintainable and idiomatic.


310-310: Good constructor pattern!

Using Self for struct instantiation within impl blocks follows Rust best practices and improves readability.

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

202-204: Excellent improvement for descriptor subclassing!

Using Self::py_new and Self::init instead of explicit type names enables better subclass support while maintaining type safety through the downcast operation.

vm/src/intern.rs (1)

314-314: Safe and idiomatic transmute improvement!

Using &Self instead of the explicit type reference maintains type safety while making the unsafe operation more generic and maintainable.

stdlib/src/pystruct.rs (4)

42-42: Clean tuple struct construction!

Using Self instead of the explicit struct name follows Rust conventions and improves maintainability.


168-168: Good return type improvement!

Using Self in the return type makes the function signature cleaner and more maintainable.


183-183: Excellent constructor pattern!

Using Self for struct instantiation within impl blocks is idiomatic Rust and improves code readability.


247-247: Great constructor improvement!

Using Self instead of the explicit struct name follows Rust best practices and makes the code more maintainable.

stdlib/src/hashlib.rs (7)

103-106: LGTM! Excellent use of Self in constructor.

This change improves code maintainability by using the idiomatic Self keyword instead of the explicit struct name in the constructor.


146-146: LGTM! Consistent use of Self::new in method.

Using Self::new instead of the explicit constructor call follows Rust best practices and improves code consistency.


176-179: LGTM! Proper use of Self in constructor.

This change enhances code readability and maintainability by using the Self keyword consistently in the constructor.


219-219: LGTM! Consistent constructor pattern.

Using Self::new maintains consistency with the pattern established in other methods and follows Rust conventions.


370-373: LGTM! Clean constructor implementation.

The use of Self in the constructor improves code clarity and follows idiomatic Rust practices.


406-410: LGTM! Consistent enum variant usage.

Using Self::Shake128 and Self::Shake256 instead of the fully qualified enum paths improves code readability and maintains consistency within the impl block.

Also applies to: 414-418


423-425: LGTM! Consistent pattern matching with Self.

The pattern matching consistently uses Self::Variant syntax, which improves code maintainability and follows Rust best practices for enum handling within impl blocks.

Also applies to: 430-432, 437-439

vm/src/builtins/list.rs (3)

40-43: LGTM! Clean constructor implementation with Self.

Using Self in the From trait implementation improves code readability and follows Rust idioms for constructor patterns.


134-134: LGTM! Consistent use of Self in generic context.

Using Self as the generic type parameter improves code clarity and maintains consistency within the method implementation.


382-382: LGTM! Proper constructor trait implementation.

Using Self::default() in the Constructor trait follows Rust conventions and improves code maintainability.

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

71-71: LGTM! Clean constructor trait implementation.

Using Self::new in the Constructor trait implementation improves code consistency and follows Rust best practices for type references within impl blocks.


204-204: LGTM! Consistent constructor usage in method.

The use of Self::new maintains consistency and improves code readability in the __getitem__ method implementation.


599-604: LGTM! Proper use of Self::new in iterator implementation.

Using Self::new for creating the starred alias follows Rust conventions and improves code maintainability in the Iterable trait implementation.

vm/src/builtins/function.rs (6)

81-95: LGTM! Excellent constructor implementation with Self.

Using Self in the constructor improves code readability and maintainability. The implementation follows Rust best practices for struct initialization within impl blocks.


452-452: LGTM! Clean downcast operation with Self.

Using Self in the downcast operation improves type safety and code consistency while maintaining the same functionality.


463-463: LGTM! Consistent type reference with Self.

Using PyRef<Self> follows Rust conventions and improves code maintainability by using the type alias consistently.


640-651: LGTM! Proper constructor call pattern.

Using Self::new in the Constructor trait implementation maintains consistency and follows Rust best practices for method calls within impl blocks.


718-718: LGTM! Clean constructor delegation.

Using Self::new in the Constructor trait implementation improves code consistency and readability.


726-726: LGTM! Consistent struct literal with Self.

Using Self in the struct literal follows Rust idioms and improves code maintainability within the impl block.

vm/src/builtins/memory.rs (3)

80-83: Idiomatic use of Self – looks good
Switching to Self::from_buffer keeps the code concise and resilient to future type-renames.


94-104: Consistent struct construction with Self – no issues
The move to Ok(Self { .. }) is purely stylistic and correct.


123-130: new_view refactor complete
Replacing PyMemoryView with Self maintains clarity and adheres to the PR objective.

compiler/codegen/src/ir.rs (3)

14-15: Const definition updated to Self – approved
This change is straightforward and preserves behaviour.


60-64: Default impl now returns Self – approved
The refactor is idiomatic and has no functional impact.


94-111: Destructuring with let Self { .. } – approved
The pattern remains correct and improves readability without altering semantics.

stdlib/src/socket.rs (3)

800-810: LGTM: Idiomatic use of Self in Default implementation

The replacement of PySocket with Self in the constructor follows Rust best practices and improves code maintainability.


1660-1667: LGTM: Proper use of Self in constructor

The change from Address { host, port } to Self { host, port } is idiomatic Rust and improves code consistency within the impl block.


1669-1688: LGTM: Consistent use of Self for associated function call

The replacement of Address::from_tuple with Self::from_tuple maintains consistency with the use of Self throughout the impl block and follows Rust conventions.

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

36-41: LGTM: Idiomatic use of Self in constructor

The replacement of PyAsyncGen with Self in the constructor follows Rust best practices and improves code readability within the impl block.


78-81: LGTM: Proper use of Self in method return type

The change from PyRef<PyAsyncGen> to Self is correct since this method is in an impl PyRef<PyAsyncGen> block, making Self equivalent to PyRef<PyAsyncGen>. This follows Rust idioms and improves maintainability.

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

188-193: Excellent use of Self for struct construction.

This change correctly replaces the explicit PyRange type name with Self within the impl block, making the code more concise and idiomatic.


207-212: Good refactoring to use idiomatic Rust syntax.

Using Self instead of the explicit type name improves code readability and maintainability within impl blocks.


299-305: Correct usage of Self for struct construction.

The change from PyRange { ... } to Self { ... } is appropriate and follows Rust conventions.


318-322: Proper use of Self:: for associated functions.

These changes correctly replace PyRange::new and PyRange::new_from with Self::new and Self::new_from respectively 8000 .


700-708: Excellent enum variant refactoring.

The changes from RangeIndex::Int and RangeIndex::Slice to Self::Int and Self::Slice are correct and make the code more concise within the TryFromObject implementation.

stdlib/src/select.rs (4)

149-150: Good use of Self for struct construction.

Replacing Selectable { obj, fno } with Self { obj, fno } is the idiomatic way to construct structs within impl blocks.


158-164: Correct refactoring for tuple struct construction.

Both changes are appropriate: Self::new() for the associated function call and Self(fdset) for tuple struct construction.


443-444: Proper tuple struct construction with Self.

The change from EventMask(mask) to Self(mask) correctly uses the Self keyword for tuple struct construction.


605-606: Clean struct construction using Self.

This change improves code consistency by using Self instead of the explicit PyEpoll type name.

stdlib/src/contextvars.rs (3)

153-154: Excellent use of Self for associated function call.

Replacing PyContext::empty(vm) with Self::empty(vm) is more concise and idiomatic within the impl block.


256-257: Good refactoring in Constructor implementation.

Using Self::empty(vm) instead of the explicit type name improves code clarity within the trait implementation.


502-508: Proper struct construction with Self.

The change from ContextVar { ... } to Self { ... } follows Rust conventions for struct construction within impl blocks.

vm/src/object/traverse_object.rs (2)

20-31: Correct use of Self in const context.

Replacing PyObjVTable { ... } with Self { ... } is appropriate and works correctly in const contexts.


52-53: Proper type cast using Self.

The change from PyInner<Erased> to Self in the unsafe cast is correct and more concise within the impl block.

stdlib/src/unicodedata.rs (2)

50-54: Excellent enum variant refactoring.

The changes from NormalizeForm::Nfc, NormalizeForm::Nfkc, etc. to Self::Nfc, Self::Nfkc, etc. are correct and make the code more concise.


224-230: Clean enum pattern matching with Self::.

Replacing the explicit EastAsianWidth:: qualifiers with Self:: improves readability and follows Rust conventions for pattern matching within impl blocks.

vm/src/codecs.rs (3)

45-45: Excellent use of Self for improved idiomatic Rust style!

Using Self(tuple) instead of PyCodec(tuple) makes the code more maintainable and follows Rust best practices.


142-142: Good consistency in using Self for method calls.

The change to Self::from_tuple maintains consistency with the other Self usage improvements in this impl block.


193-195: Perfect constructor style improvement!

Using Self { ... } instead of the explicit struct name makes the constructor more maintainable and idiomatic.

vm/src/ospath.rs (3)

47-47: Excellent return type improvement!

Using PyResult<Self> instead of PyResult<OsPath> makes the method signature more maintainable and idiomatic.


53-53: Consistent constructor style with the return type change.

The Self { path, mode } construction aligns perfectly with the PyResult<Self> return type change above.


122-124: Great improvement to enum variant references!

Using Self::Path and Self::Fd instead of the fully qualified OsPathOrFd:: variants is more idiomatic and maintainable.

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

17-17: Excellent return type improvement for better maintainability.

Using Option<Self> instead of Option<ParameterKind> makes the method signature more idiomatic and maintainable.


19-22: Perfect enum variant style improvements!

Replacing ParameterKind:: with Self:: for all variant references makes the code more concise and idiomatic.


37-37: Consistent return type improvement.

Using Option<Result<Self>> aligns with the Rust idiom of using Self in return types within impl blocks.


55-59: Great constructor consistency with the return type changes.

Using Self { ... } for the constructor aligns perfectly with the Option<Result<Self>> return type improvement.

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

53-53: Excellent trait implementation improvement!

Using Self in the From trait return type is more idiomatic and maintains the same functionality.


66-66: Consistent constructor style improvement.

The Self { obj, call } construction follows the idiomatic Rust pattern for struct initialization within impl blocks.


178-178: Perfect consistency with the ArgCallable From implementation!

Using Self in both From trait implementations maintains consistency and idiomatic style throughout the module.

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

51-51: Excellent trait implementation constructor improvement!

Using Self { value } in the From trait implementation is more idiomatic and maintainable than the explicit type name.


164-164: Great use of Self in generic parameters!

Using downcast_exact::<Self> instead of the explicit type makes the code more maintainable and follows Rust idioms.


396-396: Perfect return type improvement for the __complex__ method!

Using Self in the return type makes the method signature more maintainable and idiomatic.


413-413: Excellent consistency in generic parameter usage!

Using payload_if_subclass::<Self> maintains consistency with the other Self improvements and enhances maintainability.

vm/src/builtins/code.rs (3)

205-207: LGTM: Idiomatic use of Self in constructor

The change from explicit PyCode to Self in both the return type and struct instantiation follows Rust best practices for impl blocks.


338-338: LGTM: Consistent use of Self in return type

The return type change from PyResult<PyCode> to PyResult<Self> is idiomatic and maintains consistency with the constructor pattern.


395-421: LGTM: Proper use of Self in struct instantiation

The struct instantiation using Self instead of explicit PyCode is more concise and follows Rust conventions within impl blocks.

vm/src/frame.rs (3)

145-145: LGTM: Idiomatic use of Self in constructor return type

The change from explicit Frame to Self in the return type follows Rust best practices for impl blocks.


158-171: LGTM: Consistent struct instantiation with Self

Using Self instead of explicit Frame in the struct instantiation is more concise and idiomatic within impl blocks.


2288-2288: LGTM: Proper use of Self in generic type parameter

The change from elem.payload_is::<Frame>() to elem.payload_is::<Self>() maintains correctness while following the consistent pattern of using Self throughout the codebase.

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

226-226: Excellent use of Self keyword for improved code consistency.

The systematic replacement of explicit PyInt type references with Self throughout the implementation significantly improves code maintainability and follows Rust idiomatic patterns. All changes are correctly applied within impl PyInt blocks where Self appropriately refers to the current type.

Also applies to: 258-258, 301-301, 311-311, 405-405, 720-720, 754-795

compiler/codegen/src/symboltable.rs (1)

52-60: Clean idiomatic improvements using Self keyword.

The changes appropriately replace explicit type names with Self in constructors, enum variant patterns, and type annotations. This enhances code maintainability and follows Rust best practices for code within impl blocks.

Also applies to: 90-95, 157-163, 296-296

vm/src/scope.rs (1)

19-22: Proper application of Self keyword in method signatures and constructors.

The changes correctly replace explicit Scope type references with Self in return types and constructors, improving code consistency and following Rust idiomatic patterns within the impl block.

Also applies to: 28-35

common/src/boxvec.rs (1)

41-46: Consistent and correct use of Self keyword throughout.

The changes systematically replace explicit type names with Self in constructors and return types for both BoxVec<T> and CapacityError<T>. This improves code maintainability and follows Rust idiomatic practices within impl blocks.

Also applies to: 596-596, 679-681

common/src/lock/cell_lock.rs (1)

14-16: LGTM! Excellent use of Self in const declarations.

These changes properly replace explicit type names with Self in constant initializations within impl blocks, making the code more concise and idiomatic.

Also applies to: 64-66, 206-206

vm/src/protocol/iter.rs (3)

79-82: LGTM! Proper generalization with Self.

The From trait implementation is correctly generalized to use PyIter<Self> instead of the explicit PyIter<PyObjectRef>, making it more flexible and idiomatic.


135-135: LGTM! Appropriate use of Self::check.

Using Self::check instead of PyIter::check is correct within the TryFromObject implementation context and improves readability.


163-164: LGTM! Clean enum variant pattern matching.

Replacing explicit PyIterReturn:: prefixes with Self:: in pattern matching is idiomatic and improves code conciseness within the impl block.

compiler/core/src/frozen.rs (3)

35-35: LGTM! Concise struct construction.

Using Self { bytes } instead of the explicit type name makes the constructor more concise and maintainable.


45-46: LGTM! Proper use of Self in method signature and unsafe cast.

The return type and pointer cast correctly use Self, improving code consistency while maintaining the same semantics.


103-103: LGTM! Clean method signature.

Using Self as the return type is more idiomatic and consistent with Rust conventions.

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

78-85: LGTM! Consistent use of Self in constructor.

The error method properly uses Self for both return type and struct construction, improving code consistency.


87-94: LGTM! Clean method signature and construction.

The spans_error method correctly uses Self throughout, making it more concise and idiomatic.


96-104: LGTM! Proper use of Self in generic contexts.

The from_vec method appropriately uses Self in both the parameter type Vec<Self> and return type, maintaining semantic correctness.


116-120: LGTM! Idiomatic trait implementation.

The From<Error> trait implementation correctly uses Self for return type and struct construction, following Rust best practices.

compiler/core/src/bytecode.rs (6)

39-49: LGTM! Clean enum variant pattern matching.

The pattern matching in borrow_constant properly uses Self:: prefixes for enum variants, making the code more concise and maintainable.


139-148: LGTM! Consistent flag constant definitions.

The NAME_MAPPING constant correctly uses Self:: prefixes for the flag values, improving readability and maintainability.


157-158: LGTM! Idiomatic constructor implementations.

The null() and marker() methods properly use Self in constructor calls, following Rust conventions for associated functions.

Also applies to: 172-173, 284-285


336-337: LGTM! Proper OpArgType trait implementations.

The trait implementations correctly use Self for constructor calls and enum variants, improving code consistency.

Also applies to: 354-358


634-637: LGTM! Clean trait implementations.

The From and TryFrom trait implementations properly use Self for return types and in unsafe transmute operations, maintaining semantic correctness while improving readability.

Also applies to: 644-647


683-684: LGTM! Consistent method call.

Using Self::from_bits instead of the explicit type name is more idiomatic and maintainable.

compiler/src/lib.rs (1)

60-62: Good use of Self for enum variants

Replacing the fully-qualified names with Self::{Codegen, Parse} inside the impl CompileError block improves readability and keeps the code resilient to type renames without altering behaviour.

Also applies to: 67-78, 83-85

stdlib/src/array.rs (1)

1457-1468: Casting via as Self remains correct

The switch from explicit u8 casts to as Self keeps the impl From<MachineFormatCode> for u8 concise while preserving the original logic.

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

85-89: LGTM: Idiomatic use of Self in Default implementation.

The replacement of PyFrozenSet with Self in the struct construction is more concise and follows Rust best practices.


214-218: LGTM: Consistent use of Self in method signature and implementation.

Both the return type and struct construction now use Self, making the code more maintainable and concise.


245-263: LGTM: Excellent consistency in set operation methods.

The systematic replacement of explicit return types with Self across union, intersection, difference, and symmetric_difference methods creates a uniform and maintainable API.

Also applies to: 265-271, 277-288


1268-1268: LGTM: Clean struct construction with Self.

The TryFromObject implementation now uses idiomatic Self construction.

common/src/format.rs (5)

41-58: LGTM: Excellent enum method refactoring.

The conversion from explicit FormatConversion variants to Self:: variants in both from_char and from_string methods demonstrates consistent application of idiomatic Rust patterns.


70-78: LGTM: Clean FormatAlign implementation.

The method signature and variant references now use Self consistently, improving code readability.


144-144: LGTM: Proper trait implementation with Self.

The From trait implementation correctly uses Self as the return type, following Rust conventions.


302-312: LGTM: Comprehensive FormatSpec construction.

The struct construction using Self maintains the same field initialization while being more concise and maintainable.


719-723: LGTM: Clean FromStr trait implementation.

The trait implementation now uses Self::parse() which is more idiomatic and consistent with the rest of the code.

vm/src/format.rs (1)

15-40: LGTM: Excellent error handling refactoring.

The systematic replacement of explicit enum variants (FormatSpecError:: and FormatParseError::) with Self:: in the match arms makes the code more concise while maintaining identical functionality and error messages.

Also applies to: 48-48

common/src/str.rs (1)

50-52: LGTM: Clean use of Self in pattern matching.

The pattern matching update from explicit StrKind:: variants to Self:: variants is idiomatic and improves code conciseness while maintaining identical functionality.

common/src/refcount.rs (1)

24-26: LGTM: Idiomatic use of Self in constructor.

Using Self instead of the explicit RefCount type name in the constructor follows Rust best practices and improves maintainability.

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

72-72: LGTM: Consistent use of Self with PyRef::new_ref pattern.

The change to use Self instead of PyBaseObject is consistent with the pattern used throughout the codebase for PyRef::new_ref calls, as seen in similar constructors across other builtin types.

vm/src/protocol/sequence.rs (1)

53-62: LGTM: Improved constant declaration with Self.

Using Self instead of the explicit PySequenceMethods type name in the constant declaration is more concise and follows Rust idiomatic style within impl blocks.

stdlib/src/posixsubprocess.rs (2)

74-74: LGTM: Idiomatic struct construction with Self.

Using Self instead of the explicit CStrPathLike type name in the constructor is more concise and follows Rust best practices.


179-181: LGTM: Clean pattern matching with Self.

The pattern matching update from explicit ExecErrorContext:: variants to Self:: variants improves code readability and follows idiomatic Rust style within impl blocks.

vm/src/protocol/mapping.rs (1)

44-44: Excellent use of Self for improved consistency.

This change properly uses Self instead of the explicit type name in the constant declaration, making the code more idiomatic and maintainable.

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

24-24: Good use of Self in trait implementation.

Using Self instead of the explicit bool type in the return type annotation is more idiomatic and maintains consistency with Rust best practices.

common/src/linked_list.rs (2)

143-149: Proper use of Self in constructor.

Using Self instead of the explicit LinkedList<L, T> type in the constructor return type is more idiomatic and maintainable.


326-334: Good improvement in constructor return type.

Replacing the explicit Pointers<T> type with Self in the constructor follows Rust best practices and improves code consistency.

vm/src/protocol/number.rs (2)

162-162: Excellent use of Self in constant declaration.

Using Self instead of the explicit PyNumberMethods type in the constant declaration is more idiomatic and improves code maintainability.


200-200: Good improvement in function return type.

Replacing &'static PyNumberMethods with &'static Self follows Rust best practices and makes the code more consistent.

vm/src/stdlib/ast/statement.rs (3)

7-34: Excellent use of Self in pattern matching.

The consistent replacement of ruff::Stmt:: with Self:: in all match arms makes the code more idiomatic and easier to maintain. This change properly leverages Rust's Self keyword within the impl block.


45-159: Good improvement in constructor calls.

Using Self:: instead of ruff::Stmt:: for enum variant construction is more idiomati 6DB6 c and consistent with Rust best practices. The changes maintain the same functionality while improving code clarity.


171-181: Proper use of Self in struct destructuring and construction.

The consistent replacement of explicit struct names with Self in destructuring patterns and constructor calls throughout the AST node implementations is excellent. This improves code maintainability and follows Rust idioms perfectly.

Also applies to: 345-348, 363-363, 374-377, 392-392, 450-455, 478-478, 958-962, 979-979, 995-998, 1013-1013, 1070-1073, 1088-1088, 1101-1104, 1119-1119, 1132-1135, 1150-1150, 1163-1163, 1176-1176, 1184-1184, 1197-1197, 1205-1205, 1218-1218

stdlib/src/csv.rs (5)

71-71: Excellent use of Self in constructor method.

The change from PyDialect::try_from_object to Self::try_from_object improves code consistency and follows Rust idioms within impl blocks.


428-432: Great consistency improvement with Self:: enum variants.

Using Self::Always, Self::NonNumeric, and Self::Never instead of fully qualified variants makes the code more concise and maintainable within the impl block.


447-456: Consistent enum variant usage with Self::.

The refactor from QuoteStyle::* to Self::* variants maintains consistency with the codebase style improvements.


490-490: Proper use of Self in struct instantiation.

Using Self { ... } instead of FormatOptions { ... } follows Rust best practices within impl blocks.


560-560: Clean use of Self::default().

This change improves consistency and follows the pattern established throughout the refactor.

vm/src/stdlib/ast/exception.rs (3)

7-7: Proper use of Self:: in pattern matching.

The change from fully qualified enum variant to Self::ExceptHandler improves code consistency within the impl block.


18-22: Improved constructor formatting with Self::.

The refactor to use Self::ExceptHandler with better multiline formatting enhances both consistency and readability.


35-40: Clean destructuring pattern with Self.

Using Self in the destructuring pattern follows Rust idioms and improves code maintainability.

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

86-86: Good generalization with &Py<Self>.

Changing the parameter type from &Py<PyModule> to &Py<Self> makes the code more generic and consistent with Rust best practices within impl blocks.


172-172: Consistent constructor usage with Self::new().

Using Self::new() instead of PyModule::new() follows the established pattern and improves code consistency.

stdlib/src/zlib.rs (4)

121-121: Proper return type generalization.

Changing the return type from PyResult<InitOptions> to PyResult<Self> follows Rust conventions and improves consistency.


130-131: Consistent enum variant usage.

Using Self::Standard and Self::Gzip instead of fully qualified variants improves readability within the impl block.


425-426: Excellent trait implementation consistency.

The use of Self::Ok, Self::StreamEnd, Self::None, Self::Finish, and Self::Sync in trait implementations follows Rust best practices and maintains consistency across the codebase.

Also applies to: 434-435, 522-522


517-517: Clean enum comparison with Self::.

Using Self::StreamEnd instead of the fully qualified variant improves code consistency within the impl block.

vm/src/dict_inner.rs (5)

798-798: LGTM! Improved type reference style.

Using Self instead of the explicit type name in the unsafe cast is more idiomatic and maintainable.


893-893: LGTM! Consistent use of Self in associated type.

This change improves code maintainability by using Self instead of the explicit type name.


954-954: LGTM! Consistent use of Self in associated type.

Using Self instead of Wtf8Buf improves code consistency and maintainability.


1015-1015: LGTM! Consistent use of Self in associated type.

The change from Vec<u8> to Self enhances code consistency across the DictKey implementations.


1040-1040: LGTM! Consistent use of Self in associated type.

Using Self instead of usize maintains consistency with the codebase-wide refactoring.

vm/src/exceptions.rs (4)

550-550: LGTM! Improved constructor return type.

Using Self instead of the explicit type name follows Rust conventions and improves code maintainability.


551-551: LGTM! Consistent use of Self in struct instantiation.

This change aligns with Rust best practices for using Self in constructor methods.


691-691: LGTM! Consistent use of Self in method call.

Using Self::class instead of the explicit type improves code consistency and maintainability.


694-694: LGTM! Improved constructor call style.

Using Self::new follows Rust conventions and enhances code readability within the impl block.

vm/src/buffer.rs (4)

30-43: LGTM: Idiomatic use of Self in enum implementation

The changes to use Self for the return type and enum variant references follow Rust best practices and improve code maintainability.


270-275: LGTM: Constructor using Self

Using Self for the constructor is the idiomatic Rust approach within impl blocks.


324-340: LGTM: Method signature and constructor improvements

The use of Self for both the return type and constructor follows Rust conventions and makes the code more concise.


547-558: LGTM: Self usage in trait implementation

Using Self instead of explicit f16 type references is more maintainable and follows Rust idioms for trait implementations.

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

66-67: LGTM: Idiomatic downcasting with Self

Using Self for the downcast operation is more maintainable and follows Rust conventions.


190-191: LGTM: Generic downcast with Self

The use of Self in the generic downcast operation is the idiomatic approach.


266-270: LGTM: Method signature and constructor using Self

Both the return type and constructor usage of Self follow Rust best practices and improve code clarity.


334-334: LGTM: Parameter type using Self

Using Self for the parameter type is more concise and maintainable.


406-406: LGTM: Downcast result type with Self

The use of Self for the downcast result type follows Rust idioms.


695-697: LGTM: Constructor improvements with Self

Both the return type and constructor call using Self are idiomatic Rust and improve maintainability.

vm/src/builtins/type.rs (5)

262-271: Use of Self here is correct and improves readability.

The switch from the concrete PyType name to Self inside PyRef::new_ref is totally safe and eliminates repetition without altering semantics.
No additional action required.


307-316: Consistent replacement with Self looks good.

Same comment as above – the static‐type constructor now matches the heap‐type constructor stylistically.


536-538: Iterator helper remains sound after Self refactor.

Option::as_deref() converts Option<&PyRef<_>> to Option<&Py<_>>, so the signature
impl Iterator<Item = &Self> still compiles cleanly.


448-459: __new__ signature updated – behaviour unchanged.

The method now accepts PyRef<Self> instead of PyRef<PyType> which is idiomatic inside the impl block and doesn’t affect logic.


489-497: Helpers is_subtype / check_exact migrated to Self – good.

No functional difference, but this keeps the impl generic-friendly.

vm/src/protocol/object.rs (3)

276-286: Closure signature changed to &Self – safe.

All interior calls still expect &PyObject, so the alias is purely cosmetic.


412-458: Large method body untouched; signature only.

abstract_issubclass keeps identical control-flow and error paths. ✔️


540-547: real_is_instanceobject_isinstance chain unaffected.

Just confirming: the switch to &Self does not change borrow semantics and still satisfies trait bounds (TryFromObject etc.).

vm/src/builtins/bytearray.rs (3)

81-85: Constructor helper now returns Self – fine.

from_inner is clearer and gate-keeps the struct invariants as before.


338-360: Padding helpers (center, ljust, rjust, join) converted to Self.

The returned inner value is still wrapped via .into(), so no semantic drift.


541-543: __mod__ keeps behaviour; signature tidied.

Nothing to flag – the % operator still delegates to cformat.

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

119-119: LGTM: Idiomatic use of Self in return type.

The change from PyResult<PyBytes> to PyResult<Self> follows Rust best practices and improves code maintainability.


273-283: LGTM: Consistent use of Self in padding method return types.

The systematic replacement of PyResult<PyBytes> with PyResult<Self> across the padding methods (center, ljust, rjust) follows Rust best practices and improves code consistency.


293-466: LGTM: Idiomatic return type improvements.

The changes to use PyResult<Self> instead of PyResult<PyBytes> in the join, translate, replace, and mod_ methods follow Rust conventions and improve code maintainability.


514-533: LGTM: Appropriate use of Self in PyRef implementation.

The changes to use Self instead of explicit type references in the bytes, lstrip, and rstrip methods are idiomatic and maintain the same functionality while improving code readability.

vm/src/builtins/str.rs (7)

184-184: LGTM: Idiomatic struct instantiation and constructor calls.

The changes to use Self instead of PyStr in struct instantiation and constructor calls follow Rust best practices and improve code maintainability within the impl blocks.

Also applies to: 367-373


520-520: LGTM: Consistent use of Self in type parameters.

The changes to use Self instead of PyStr in payload() and downcast() method type parameters are idiomatic and maintain the same functionality while improving code consistency.

Also applies to: 1338-1338, 1370-1370, 1408-1408


629-629: LGTM: Idiomatic return types for string manipulation methods.

The changes to use Self instead of PyStr in the return types of lower(), upper(), and strip() methods follow Rust conventions and improve code maintainability.

Also applies to: 651-651, 768-768


848-848: LGTM: Consistent type annotations in closures.

The changes to use &Py<Self> instead of &Py<PyStr> in closure parameters maintain functionality while following idiomatic Rust style.

Also applies to: 868-868


1696-1825: LGTM: Comprehensive use of Self in trait implementation.

The systematic replacement of PyStr with Self throughout the SliceableSequenceOp trait implementation, including the type alias and method calls, follows Rust best practices and improves code consistency.


1889-1928: LGTM: Idiomatic associated function calls.

The changes to use Self:: prefix for method calls (new, with_capacity, push_str, chars) instead of explicit type names follow Rust conventions and improve code readability.


2002-2128: LGTM: Consistent pattern across all container implementations.

The changes to use Self:: prefix in the Wtf8Buf and AsciiString implementations maintain consistency with the established pattern and follow Rust best practices.

vm/src/bytes_inner.rs (5)

32-36: Prefer Self – stylistic improvement looks good

Replacing the explicit struct name with Self makes the conversion impl shorter and keeps it in-sync if the type is ever renamed.


551-554: No regression introduced

Behaviour is unchanged; signature is now cleaner.
Nothing else to flag.


609-633: Strip helpers – signature polish LGTM

The switch to Self in the optional parameters keeps the public API unchanged while reducing verbosity.


636-651: Prefix / suffix helpers – stylistic change only

Nothing behavioural changed; good to merge.


694-712: Partition helpers – looks correct

Self substitution is safe here; no further remarks.

Comment on lines 124 to 134
impl TryFromObject for std::time::Duration {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
use std::time::Duration;
if let Some(float) = obj.payload::<PyFloat>() {
Ok(Duration::from_secs_f64(float.to_f64()))
Ok(Self::from_secs_f64(float.to_f64()))
} else if let Some(int) = obj.try_index_opt(vm) {
let sec = int?
.as_bigint()
.to_u64()
.ok_or_else(|| vm.new_value_error("value out of range"))?;
Ok(Duration::from_secs(sec))
Ok(Self::from_secs(sec))
} else {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard against invalid floats to prevent panics

std::time::Duration::from_secs_f64 (and from_secs) will panic on negative, NaN, or exceedingly large values. Since the input comes from Python objects, add an explicit validity check before constructing the Duration.

-if let Some(float) = obj.payload::<PyFloat>() {
-    Ok(Self::from_secs_f64(float.to_f64()))
+if let Some(float) = obj.payload::<PyFloat>() {
+    let secs = float.to_f64();
+    if !secs.is_finite() || secs < 0.0 {
+        return Err(vm.new_value_error("duration seconds must be a non-negative finite number"));
+    }
+    Ok(Self::from_secs_f64(secs))
 }

Likewise, reject negative integers before calling from_secs.

📝 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
impl TryFromObject for std::time::Duration {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
use std::time::Duration;
if let Some(float) = obj.payload::<PyFloat>() {
Ok(Duration::from_secs_f64(float.to_f64()))
Ok(Self::from_secs_f64(float.to_f64()))
} else if let Some(int) = obj.try_index_opt(vm) {
let sec = int?
.as_bigint()
.to_u64()
.ok_or_else(|| vm.new_value_error("value out of range"))?;
Ok(Duration::from_secs(sec))
Ok(Self::from_secs(sec))
} else {
impl TryFromObject for std::time::Duration {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
if let Some(float) = obj.payload::<PyFloat>() {
let secs = float.to_f64();
if !secs.is_finite() || secs < 0.0 {
return Err(vm.new_value_error(
"duration seconds must be a non-negative finite number",
));
}
Ok(Self::from_secs_f64(secs))
} else if let Some(int) = obj.try_index_opt(vm) {
let sec = int?
.as_bigint()
.to_u64()
.ok_or_else(|| vm.new_value_error("value out of range"))?;
Ok(Self::from_secs(sec))
} else {
// ...
}
}
}
🤖 Prompt for AI Agents
In vm/src/convert/try_from.rs around lines 124 to 134, the conversion to
std::time::Duration does not validate the float or integer values, risking
panics on negative, NaN, or out-of-range inputs. Add explicit checks to ensure
the float is finite, non-negative, and within a valid range before calling
from_secs_f64, and verify the integer is non-negative before calling from_secs.
Return a ValueError via vm.new_value_error if these validations fail.

Comment on lines +865 to 870
impl AsRef<Self> for PyObject {
#[inline(always)]
fn as_ref(&self) -> &PyObject {
fn as_ref(&self) -> &Self {
self
}
}
Copy link
Contributor
@coderabbitai coderabbitai bot Jul 3, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove conflicting blanket-impl of AsRef

std already has impl<T> AsRef<T> for T.
Re-implementing it for PyObject creates a coherence conflict and will fail to compile.

-impl AsRef<Self> for PyObject {
-    #[inline(always)]
-    fn as_ref(&self) -> &Self {
-        self
-    }
-}
📝 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
impl AsRef<Self> for PyObject {
#[inline(always)]
fn as_ref(&self) -> &PyObject {
fn as_ref(&self) -> &Self {
self
}
}
🤖 Prompt for AI Agents
In vm/src/object/core.rs around lines 865 to 870, remove the entire impl block
for AsRef<Self> for PyObject because the standard library already provides a
blanket implementation of AsRef for all types, causing a coherence conflict.
Deleting this redundant implementation will resolve the compilation error.

Copy link
Member

Choose a reason for hiding this comment

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

@coderabbitai Please create a new issue about it

Copy link
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

I'll create a GitHub issue about the AsRef implementation conflict for you.


🏁 Script executed:

#!/bin/bash
# Create a GitHub issue about the AsRef implementation conflict
gh issue create \
  --title "Remove conflicting AsRef implementation for PyObject" \
  --body "## Problem

A compilation conflict exists in \`vm/src/object/core.rs\` where there's a custom implementation of \`AsRef<Self> for PyObject\` that conflicts with the standard library's blanket implementation \`impl<T> AsRef<T> for T\`.

This creates a coherence conflict and will cause compilation failures.

## Location

File: \`vm/src/object/core.rs\` around lines 865-870

## Context

This issue was identified during the review of PR #5892 which aims to use \`Self\` where possible throughout the codebase.

## Backlinks

- Related PR: https://github.com/RustPython/RustPython/pull/5892
- Comment: https://github.com/RustPython/RustPython/pull/5892#discussion_r2183174088

Requested by: @youknowone" \
  --assignee youknowone

Length of output: 862


@youknowone I've successfully created GitHub issue #5897 about the conflicting AsRef implementation: #5897

The issue has been assigned to you and includes:

  • Clear description of the compilation conflict
  • Location of the problematic code in vm/src/object/core.rs
  • Context about the PR Use Self where possible #5892
  • Backlinks to this PR and comment thread

The issue is now ready for tracking the resolution of this AsRef coherence conflict.


🧬 Code Graph Analysis Results

Relevant snippets from vm/src/object/core.rs (entire file provided)

The file vm/src/object/core.rs defines the core object model types and their management in the RustPython VM. It includes:

  • Definitions of the core Python object representation PyObject and its generic form Py<T>.
  • Reference-counted smart pointer types PyObjectRef, PyRef<T>, and weak references PyWeak, PyWeakRef<T>.
  • Implementation details for reference counting, downcasting, and payload access.
  • The PyInner<T> struct which holds the actual object data including refcount, type info, dict, weak references, slots, and payload.
  • The WeakRefList and WeakListInner structs managing weak references to objects.
  • Methods for creating, cloning, dropping, and downcasting Python objects.
  • The InstanceDict wrapper for instance dictionaries.
  • Initialization of the type hierarchy including type, object, and weakref types.
  • Macros and utility functions for partially initializing structs.
  • Implementations of traits like Deref, Clone, Drop, Debug, Borrow, and AsRef for the core types.
  • Safety comments and explanations about vtable usage and memory layout optimizations.
  • Drop logic that handles calling __del__ and clearing weak references.
  • Methods for managing object slots and dictionaries.
  • Thread-safety annotations and conditional compilation for threading support.

This file is central to the VM's object system and provides the foundational types and operations for Python objects, including their lifecycle and type information.


Possibly relevant snippets from vm/src/object/traverse_object.rs (lines 19-31)

pub const fn of<T: PyObjectPayload>() -> &'static Self {
    &Self {
        drop_dealloc: drop_dealloc_obj::<T>,
        debug: debug_obj::<T>,
        trace: const {
            if T::IS_TRACE {
                Some(try_trace_obj::<T>)
            } else {
                None
            }
        },
    }
}

This snippet defines a function returning a static vtable for a given payload type T. It includes function pointers for dropping, debugging, and optionally tracing the object payload. This is relevant to how PyInner<T> objects manage their payloads and vtables.


Possibly relevant snippets from vm/src/object/traverse.rs (lines 30-42)

fn traverse(&self, traverse_fn: &mut TraverseFn<'_>);

fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) {
    traverse_fn(self)
}

fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) {
    traverse_fn(self.as_object())
}

These are trait method signatures and implementations for traversing references in objects, relevant to garbage collection or tracing. The Traverse trait is implemented for Py<T> and PyObject in core.rs.


Possibly relevant snippets from vm/src/object/ext.rs

Several snippets showing implementations of borrow and deref methods for wrapper types around PyObject and Py<T>. For example:

fn borrow(&self) -> &PyObject {
    self.inner.borrow()
}

fn borrow(&self) -> &Py<T> {
    &self.inner
}

These are relevant for understanding how references to Python objects are accessed and manipulated.


Possibly relevant snippets from vm/src/vm/thread.rs (lines 38-63)

pub fn with_vm<F, R>(obj: &PyObject, f: F) -> Option<R>
where
    F: Fn(&VirtualMachine) -> R,
{
    // Implementation that finds the VM owning the object and runs closure `f` with it.
}

This function 10000 is used in WeakRefList::clear to run callbacks with the VM context, relevant to weak reference callback invocation.


Possibly relevant snippets from vm/src/builtins/object.rs (lines 417-446)

fn set_class(instance: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
    match value.downcast::<PyType>() {
        Ok(cls) => {
            // Checks for mutable types or module types before setting __class__
            instance.set_class(cls, vm);
            Ok(())
        }
        Err(value) => {
            let value_class = value.class();
            let type_repr = &value_class.name();
            Err(vm.new_type_error(format!(
                "__class__ must be set to a class, not '{type_repr}' object"
            )))
        }
    }
}

This snippet shows how setting the __class__ attribute is handled, including type checks and error handling.


Possibly relevant snippets from vm/src/builtins/weakproxy.rs (lines 223-225)

fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
    zelf.try_upgrade(vm)?.repr(vm)
}

Shows usage of weak references and upgrading them to strong references, relevant to weak reference management.


Possibly relevant snippets from vm/src/builtins/type.rs (lines 48-58)

fn traverse(&self, tracer_fn: &mut crate::object::TraverseFn<'_>) {
    self.base.traverse(tracer_fn);
    self.bases.traverse(tracer_fn);
    self.mro.traverse(tracer_fn);
    self.subclasses.traverse(tracer_fn);
    self.attributes
        .read_recursive()
        .iter()
        .map(|(_, v)| v.traverse(tracer_fn))
        .count();
}

Shows traversal of type objects, relevant to garbage collection and object graph traversal.


Possibly relevant snippets from vm/src/builtins/type.rs (lines 215, 496, 932)

obj.downcast_ref::<Self>
obj.downcast_ref_if_exact::<PyType>
obj.clone().downcast::<Self>

These show downcasting operations on objects to PyType, relevant to type checking and casting.


Possibly relevant snippets from vm/src/builtins/weakref.rs (line 58-59)

wr.payload::<PyWeak>

Shows payload access for weak references, relevant to weak reference internals.


Possibly relevant snippets from vm/src/builtins/bytes.rs (lines 102-104)

pub fn new_ref(data: Vec<u8>, ctx: &Context) -> PyRef<Self> {
    PyRef::new_ref(Self::from(data), ctx.types.bytes_type.to_owned(), None)
}

Example of creating a new Python object reference, relevant to object creation patterns.


Possibly relevant snippets from vm/src/builtins/str.rs (lines 224-226)

fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    self.as_wtf8().fmt(f)
}

Shows debug formatting for string objects, relevant to fmt::Debug implementations.


Possibly relevant snippets from vm/src/builtins/tuple.rs (lines 514-516)

fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
    self.tuple.traverse(tracer_fn);
}

Shows traversal for tuple objects, relevant to GC.


Possibly relevant snippets from vm/src/builtins/dict.rs (lines 40-43)

fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    // TODO: implement more detailed, non-recursive Debug formatter
    f.write_str("dict")
}

Shows debug formatting for dict objects.


Possibly relevant snippets from vm/src/builtins/function.rs (lines 729-735)

pub fn new_ref(object: PyObjectRef, function: PyObjectRef, ctx: &Context) -> PyRef<Self> {
    PyRef::new_ref(
        Self::new(object, function),
        ctx.types.bound_method_type.to_owned(),
        None,
    )
}

Shows creation of new function objects.


Possibly relevant snippets from vm/src/builtins/staticmethod.rs (lines 64-72)

pub fn new_ref(callable: PyObjectRef, ctx: &Context) -> PyRef<Self> {
    PyRef::new_ref(
        Self {
            callable: PyMutex::new(callable),
        },
        ctx.types.staticmethod_type.to_owned(),
        None,
    )
}

Shows creation of staticmethod objects.


Possibly relevant snippets from vm/src/builtins/classmethod.rs (lines 114-122)

pub fn new_ref(callable: PyObjectRef, ctx: &Context) -> PyRef<Self> {
    PyRef::new_ref(
        Self {
            callable: PyMutex::new(callable),
        },
        ctx.types.classmethod_type.to_owned(),
        None,
    )
}

Shows creation of classmethod objects.


Possibly relevant snippets from vm/src/builtins/property.rs (line 95)

zelf.try_to_ref::<Self>

Shows downcasting or conversion to a typed reference.


Possibly relevant snippets from vm/src/builtins/getset.rs (line 110)

zelf.try_to_ref::<Self>

Similar to above, for getset descriptors.


Possibly relevant snippets from vm/src/builtins/super.rs (lines 29-37)

fn new(typ: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
    let obj = if vm.is_none(&obj) {
        None
    } else {
        let obj_type = super_check(typ.clone(), obj.clone(), vm)?;
        Some((obj, obj_type))
    };
    Ok(Self { typ, obj })
}

Shows creation of super objects with type checks.


Possibly relevant snippets from vm/src/builtins/namespace.rs (lines 30-36)

pub fn new_ref(ctx: &Context) -> PyRef<Self> {
    PyRef::new_ref(
        Self {},
        ctx.types.namespace_type.to_owned(),
        Some(ctx.new_dict()),
    )
}

Shows creation of namespace objects.


Possibly relevant snippets from vm/src/builtins/complex.rs (lines 437-448)

fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
    let value = zelf.value;

    let re_hash =
        hash::hash_float(value.re).unwrap_or_else(|| hash::hash_object_id(zelf.get_id()));

    let im_hash =
        hash::hash_float(value.im).unwrap_or_else(|| hash::hash_object_id(zelf.get_id()));

    let Wrapping(ret) = Wrapping(re_hash) + Wrapping(im_hash) * Wrapping(hash::IMAG);
    Ok(hash::fix_sentinel(ret))
}

Shows hashing logic for complex numbers.


Possibly relevant snippets from vm/src/builtins/descriptor.rs (lines 191-211)

fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
    match self.getter {
        MemberGetter::Getter(getter) => (getter)(vm, obj),
        MemberGetter::Offset(offset) => get_slot_from_object(obj, offset, self, vm),
    }
}

fn set(
    &self,
    obj: PyObjectRef,
    value: PySetterValue<PyObjectRef>,
    vm: &VirtualMachine,
) -> PyResult<()> {
    match self.setter {
        MemberSetter::Setter(setter) => match setter {
            Some(setter) => (setter)(vm, obj, value),
            None => Err(vm.new_attribute_error("readonly attribute")),
        },
        MemberSetter::Offset(offset) => set_slot_at_object(obj, offset, self, value, vm),
    }
}

Shows descriptor get/set logic.


Possibly relevant snippets from vm/src/builtins/mappingproxy.rs (lines 106-118)

fn get(
    &self,
    key: PyObjectRef,
    default: OptionalArg,
    vm: &VirtualMachine,
) -> PyResult<Option<PyObjectRef>> {
    let obj = self.to_object(vm)?;
    Ok(Some(vm.call_method(
        &obj,
        "get",
        (key, default.unwrap_or_none(vm)),
    )?))
}

Shows mappingproxy get method.


Possibly relevant snippets from vm/src/builtins/zip.rs (lines 50-54)

zelf
    .iterators
    .iter()
    .map(|obj| obj.clone().into())
    .collect::<Vec<_>>()

Shows iterator cloning.


Possibly relevant snippets from vm/src/builtins/asyncgenerator.rs (line 347)

v.payload_is::<PyAsyncGenWrappedValue>

Shows payload type checking.


Possibly relevant snippets from vm/src/builtins/bytes.rs (lines 288-290)

fn count(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> {
    self.inner.count(options, vm)
}

Shows count method delegation.


Possibly relevant snippets from vm/src/builtins/int.rs (lines 52-54)

fn class(ctx: &Context) -> &'static Py<PyType> {
    ctx.types.int_type
}

Shows class getter for int.


Possibly relevant snippets from vm/src/builtins/float.rs (lines 526, 530)

other.payload_if_subclass::<Self>
other.payload_if_subclass::<PyInt>

Shows payload type checking for float.


Possibly relevant snippets from vm/src/builtins/tuple.rs (lines 259-267)

fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
    let mut count: usize = 0;
    for element in self {
        if vm.identical_or_equal(element, &needle)? {
            count += 1;
        }
    }
    Ok(count)
}

Shows count method for tuple.


Possibly relevant snippets from vm/src/builtins/list.rs (lines 254-256)

fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
    self.mut_count(vm, &needle)
}

Shows count method for list.


Possibly relevant snippets from vm/src/builtins/set.rs (lines 682-685)

pub fn add(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
    self.inner.add(item, vm)?;
    Ok(())
}

Shows add method for set.


Possibly relevant snippets from vm/src/builtins/str.rs (lines 569-574)

pub(crate) fn hash(&self, vm: &VirtualMachine) -> hash::PyHash {
    match self.hash.load(atomic::Ordering::Relaxed) {
        hash::SENTINEL => self._compute_hash(vm),
        hash => hash,
    }
}

Shows hash caching for strings.


Possibly relevant snippets from vm/src/builtins/str.rs (lines 932-936)

fn format(&self, args: FuncArgs, vm: &VirtualMachine) -> PyResult<Wtf8Buf> {
    let format_str =
        FormatString::from_str(self.as_wtf8()).map_err(|e| e.to_pyexception(vm))?;
    format(&format_str, &args, vm)
}

Shows string formatting.


Possibly relevant snippets from vm/src/builtins/bytes_inner.rs (lines 544-549)

pub fn count(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> {
    let (needle, range) = options.get_value(self.elements.len(), vm)?;
    Ok(self
        .elements
        .py_count(needle.as_slice(), range, |h, n| h.find_iter(n).count()))
}

Shows count method for bytes.


Possibly relevant snippets from vm/src/builtins/memory.rs (lines 325-385)

fn eq(zelf: &Py<Self>, other: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
    if zelf.is(other) {
        return Ok(true);
    }
    if zelf.released.load() {
        return Ok(false);
    }

    if let Some(other) = other.payload::<Self>() {
        if other.released.load() {
            return Ok(false);
        }
    }

    let other = match PyBuffer::try_from_borrowed_object(vm, other) {
        Ok(buf) => buf,
        Err(_) => return Ok(false),
    };

    if !is_equiv_shape(&zelf.desc, &other.desc) {
        return Ok(false);
    }

    // ... compares buffer contents ...

    ret
}

Shows equality comparison for memoryview-like objects.


Possibly relevant snippets from vm/src/builtins/method.rs (lines 22-84)

pub fn get(obj: PyObjectRef, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult<Self> {
    let cls = obj.class();
    let getattro = cls.mro_find_map(|cls| cls.slots.getattro.load()).unwrap();
    if getattro as usize != PyBaseObject::getattro as usize {
        return obj.get_attr(name, vm).map(Self::Attribute);
    }

    // ... descriptor lookup and method binding logic ...

    Err(vm.new_no_attribute_error(obj.clone(), name.to_owned()))
}

Shows attribute lookup and method binding.


Possibly relevant snippets from vm/src/vm/thread.rs (lines 38-63)

pub fn with_vm<F, R>(obj: &PyObject, f: F) -> Option<R>
where
    F: Fn(&VirtualMachine) -> R,
{
    // Finds the VM owning the object and runs closure `f` with it.
}

Used in weakref callback invocation.


Possibly relevant snippets from vm/src/builtins/object.rs (lines 417-446)

fn set_class(instance: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
    match value.downcast::<PyType>() {
        Ok(cls) => {
            // Checks for mutable types or module types before setting __class__
            instance.set_class(cls, vm);
            Ok(())
        }
        Err(value) => {
            let value_class = value.class();
            let type_repr = &value_class.name();
            Err(vm.new_type_error(format!(
                "__class__ must be set to a class, not '{type_repr}' object"
            )))
        }
    }
}

Summary

The entire vm/src/object/core.rs file is relevant as it defines the core object model, reference counting, weak references, downcasting, and type hierarchy initialization.

Additional relevant snippets include:

  • vm/src/object/traverse_object.rs for vtable definitions.
  • vm/src/object/traverse.rs for traversal traits.
  • vm/src/object/ext.rs for reference wrappers.
  • vm/src/vm/thread.rs for VM context access during weakref callbacks.
  • vm/src/builtins/object.rs for __class__ attribute setting logic.
  • vm/src/builtins/weakproxy.rs for weak reference usage.
  • vm/src/builtins/type.rs for type object traversal and downcasting.
  • Various builtins modules showing object creation, downcasting, and method implementations.

These snippets provide comprehensive context for understanding the core object system, reference management, and type handling in RustPython.


🧠 Learnings used
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.851Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust

Copy link
Member

Choose a reason for hiding this comment

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

@coderabbitai Please make this change a separated PR

Copy link
Contributor
@coderabbitai coderabbitai bot Jul 4, 2025

Choose a reason for hiding this comment

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

A summary of the changes CodeRabbit can apply:

  • Remove lines 865 to 870 in vm/src/object/core.rs to delete the conflicting impl AsRef<Self> for PyObject and resolve the conflict with Rust’s standard library blanket implementation.

A summary of the context that CodeRabbit is considering across the codebase:

I need to verify the exact lines that contain the conflicting implementation and ensure I'm targeting the right code block.

Show context details

Shell Result:

Shell script executed:

Show the exact lines around the conflicting AsRef implementation

sed -n '860,875p' vm/src/object/core.rs

Output:
fn as_ref(&self) -> &PyObject {
    self
}

}

impl AsRef for PyObject {
#[inline(always)]
fn as_ref(&self) -> &Self {
self
}
}

impl<'a, T: PyObjectPayload> From<&'a Py> for &'a PyObject {
#[inline(always)]
fn from(py_ref: &'a Py) -> Self {
py_ref.as_object()

Let me also check if there are any compilation tests or CI that would catch this conflict to understand the urgency.

Show context details

Shell Result:

Shell script executed:

Search for any compilation-related issues or tests mentioning AsRef conflicts

rg -n -i "coherence|conflict.*asref|asref.*conflict" --type rust

Error: Command failed with exit code 1: jk_chrootlaunch --jail /inmem/6577/e3b65aaf-f4f1-4d40-9553-3fc5a153eff9 --group jailuser --user jailuser --exec /usr/bin/env -- '/bin/bash --norc --noprofile -c "cd '\''/home/jailuser/git'\'' && bash -x /.coderabbit_commands_2d544bce-6f49-4b9b-8398-1e9a7ab49e19.sh"'

+ rg -n -i 'coherence|conflict.*asref|asref.*conflict' --type rust
  • Executed edits - (🔄 Check again to try again)

Copy link
Contributor

Choose a reason for hiding this comment

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

Creating a PR to execute the edits....

The changes have been created in this pull request: View PR

Copy link
Member
@youknowone youknowone left a comment

Choose a reason for hiding this comment

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

👍

@youknowone youknowone merged commit 69545c0 into RustPython:main Jul 4, 2025
12 checks passed
@ShaharNaveh ShaharNaveh deleted the use-self branch July 4, 2025 08:31
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
0