typing __parameters__ __type_params__ by youknowone · Pull Request #5909 · RustPython/RustPython
Walkthrough
This update extends the compiler and runtime to support default values for type parameters and automatic insertion of generic base classes in line with PEP 695. It introduces new bytecode instructions, intrinsic function handling, synchronization for type parameter defaults, and updates class construction to manage type parameter attributes and defaults.
Changes
| File(s) | Change Summary |
|---|---|
| compiler/codegen/src/compile.rs | Enhanced type parameter compilation to support defaults per PEP 695; updated class definition logic for automatic generic base insertion and deferred symbol table popping. |
| compiler/core/src/bytecode.rs | Added enums for intrinsic functions, new bytecode instructions (CallIntrinsic1, CallIntrinsic2), and updated stack effect and instruction display logic. |
| vm/src/builtins/genericalias.rs | Added subscript_generic function to create a GenericAlias from type parameters, mimicking CPython’s internal behavior. |
| vm/src/frame.rs | Implemented execution for new intrinsic call instructions; added methods for intrinsic dispatch; minor fix in ParamSpec handling. |
| vm/src/stdlib/builtins.rs | Modified __build_class__ to set both __type_params__ (cloned) and new __parameters__ attributes on classes for typing compatibility. |
| vm/src/stdlib/typevar.rs | Changed evaluate_default fields to use PyMutex for thread-safe access; added set_typeparam_default function; adjusted Generic.__class_getitem__ argument unpacking. |
| vm/src/stdlib/typing.rs | Re-exported set_typeparam_default from typevar module for public use. |
Sequence Diagram(s)
sequenceDiagram
participant Compiler
participant VM
participant Typing
participant TypeParam
Compiler->>VM: Emit instructions for type parameters
alt Default value present
Compiler->>VM: CallIntrinsic2(SetTypeparamDefault) with TypeParam, default
VM->>Typing: set_typeparam_default(TypeParam, default)
Typing-->>VM: Default set on TypeParam
end
Compiler->>VM: Emit class construction instructions
alt TypeParams exist and no explicit bases
Compiler->>VM: CallIntrinsic1(SubscriptGeneric) with type_params
VM->>Typing: subscript_generic(type_params)
Typing-->>VM: GenericAlias returned
Compiler->>VM: Call __build_class__ with GenericAlias as base
else Explicit bases present
Compiler->>VM: Call __build_class__ with explicit bases
else No type params
Compiler->>VM: Call __build_class__ normally
end
Possibly related PRs
-
__type_params__ in __build_class__ #5883: Refactors type parameter handling in the compiler, including special symbol table management and class/function compilation logic, closely related to this PR's enhancements for PEP 695 support.
-
Fix TypeParams, TypeAlias compile #5862: Fixes compilation and execution of type parameters specifically for
TypeAlias; related by modifyingcompile.rsbut focusing on different constructs than this PR.
Suggested reviewers
- arihant2math
Poem
In the warren where code bunnies dwell,
Type parameters now have defaults as well!
With intrinsic bytecode, they hop in line,
And classes generic—oh, how they shine!
A tuple of types, a carrot of base,
PEP 695’s magic fills the place.
🥕✨
📜 Recent review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
Lib/test/test_module/__init__.pyis excluded by!Lib/**Lib/test/test_typing.pyis excluded by!Lib/**
📒 Files selected for processing (6)
compiler/codegen/src/compile.rs(2 hunks)compiler/core/src/bytecode.rs(4 hunks)vm/src/builtins/genericalias.rs(1 hunks)vm/src/frame.rs(3 hunks)vm/src/stdlib/typevar.rs(18 hunks)vm/src/stdlib/typing.rs(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- vm/src/builtins/genericalias.rs
- vm/src/stdlib/typing.rs
- compiler/core/src/bytecode.rs
- vm/src/frame.rs
- compiler/codegen/src/compile.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 fmtto 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/stdlib/typevar.rs
🧠 Learnings (1)
vm/src/stdlib/typevar.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-30T10:08:48.858Z
Learning: Applies to **/*.rs : Use the macro system (`pyclass`, `pymodule`, `pyfunction`, etc.) when implementing Python functionality in Rust
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
- GitHub Check: Run snippets and cpython tests on wasm-wasi
- GitHub Check: Run snippets and cpython tests (windows-latest)
- GitHub Check: Check the WASM package and demo
- GitHub Check: Run tests under miri
- GitHub Check: Run rust tests (windows-latest)
- GitHub Check: Run snippets and cpython tests (macos-latest)
- GitHub Check: Run snippets and cpython tests (ubuntu-latest)
- GitHub Check: Check Rust code with rustfmt and clippy
- GitHub Check: Run rust tests (ubuntu-latest)
- GitHub Check: Run rust tests (macos-latest)
- GitHub Check: Ensure compilation on various targets
🔇 Additional comments (5)
vm/src/stdlib/typevar.rs (5)
5-5: LGTM: Thread safety improvements for TypeVar.The conversion of
evaluate_defaulttoPyMutex<PyObjectRef>aligns with the existing thread safety pattern used by other fields likeboundandconstraints. The access patterns are correctly updated to use.lock()throughout the implementation.Also applies to: 80-80, 149-152, 176-176, 363-363, 389-390
404-405: LGTM: ParamSpec field type changes and thread safety.The changes correctly handle the transition from
Option<PyObjectRef>toPyObjectReffordefault_value, using theNoDefaultsingleton pattern. The thread safety improvements withPyMutexare consistent with other type parameter implementations.Also applies to: 466-478, 481-483, 491-497, 591-591, 597-597, 619-629
638-638: LGTM: TypeVarTuple thread safety improvements.The thread safety changes for
evaluate_defaultare consistent with the pattern used in TypeVar and ParamSpec implementations.Also applies to: 654-657, 666-666, 758-758, 781-781
974-976: LGTM: Fixed CPython compatibility in Generic.class_getitem.The change to delegate to the typing module's
_generic_class_getitemfunction addresses the previous compatibility issue with tuple unwrapping. This approach ensures behavior matches CPython's implementation.
984-1022: LGTM: Well-implemented set_typeparam_default function.The implementation is clean and follows good Rust practices:
- Uses a generic helper function to reduce code duplication
- Properly handles all three type parameter types (TypeVar, ParamSpec, TypeVarTuple)
- Correctly uses mutex locks for thread safety
- Appropriate error handling for invalid type parameters
✨ 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.
🪧 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
@coderabbitaiin a new review comment at the desired location with your query. Examples:@coderabbitai explain this code block.@coderabbitai modularize this function.
- PR comments: Tag
@coderabbitaiin 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 pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere 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.