Skip to content

typing TypeAlias #5945

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 1 commit into from
Jul 11, 2025
Merged

typing TypeAlias #5945

merged 1 commit into from
Jul 11, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jul 11, 2025

Summary by CodeRabbit

  • New Features

    • Added Python-accessible properties to type aliases: __name__, __value__, and __type_params__.
    • Implemented a custom string representation (__repr__) for type aliases.
  • Refactor

    • Updated the handling of type aliases and type parameters to use intrinsic function calls, improving the internal consistency of typing operations.
    • Removed legacy bytecode instructions for typing constructs in favor of a unified intrinsic function approach.

Copy link
Contributor

coderabbitai bot commented Jul 11, 2025

Walkthrough

The changes refactor the compilation and execution of PEP 695 type alias and type parameter constructs. Direct bytecode instructions for these constructs are removed and replaced by intrinsic function calls. The stack manipulation and argument passing are updated accordingly. Additionally, new Python properties and a __repr__ method are exposed for TypeAliasType.

Changes

File(s) Change Summary
compiler/codegen/src/compile.rs Refactored compilation of PEP 695 constructs to emit intrinsic function calls instead of direct instructions.
compiler/core/src/bytecode.rs Removed type-related instructions; activated and updated intrinsic function enums for type constructs.
vm/src/frame.rs Removed execution of type-related instructions; added handling for new intrinsic function variants.
vm/src/stdlib/typing.rs Added __name__, __value__, __type_params__ properties and __repr__ method to TypeAliasType.

Sequence Diagram(s)

sequenceDiagram
    participant Compiler
    participant VM
    participant Typing

    Compiler->>VM: Emit CallIntrinsic1(TypeAlias, [name, type_params, value])
    VM->>Typing: TypeAliasType::new(name, type_params, value)
    Typing-->>VM: TypeAliasType instance
    VM-->>Compiler: Push TypeAliasType to stack
Loading
sequenceDiagram
    participant Compiler
    participant VM
    participant Typing

    Compiler->>VM: Emit CallIntrinsic1(TypeVar/ParamSpec/TypeVarTuple, args)
    VM->>Typing: Create TypeVar/ParamSpec/TypeVarTuple
    Typing-->>VM: Typing object
    VM-->>Compiler: Push typing object to stack
Loading

Possibly related PRs

  • RustPython/RustPython#5862: Refactors compilation of PEP 695 constructs, focusing on stack order and handling optional type parameters, but still uses direct instructions rather than intrinsic calls.

Poem

A whisker-twitch, a hop, a leap—
The typing code now runs so deep!
Intrinsics called, instructions gone,
Type aliases now hop along.
With properties and names anew,
This bunny codes with much ado!
🐇✨

✨ 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: 1

🧹 Nitpick comments (1)
vm/src/frame.rs (1)

2235-2240: Improve error message to specify expected arguments.

The error message could be more descriptive about what the 3 arguments should be.

                if tuple.len() != 3 {
                    return Err(vm.new_type_error(format!(
-                        "TypeAlias expects exactly 3 arguments, got {}",
+                        "TypeAlias expects exactly 3 arguments (name, type_params, value), got {}",
                        tuple.len()
                    )));
                }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b6c78c and 30f421b.

⛔ Files ignored due to path filters (1)
  • Lib/test/test_typing.py is excluded by !Lib/**
📒 Files selected for processing (4)
  • compiler/codegen/src/compile.rs (4 hunks)
  • compiler/core/src/bytecode.rs (3 hunks)
  • vm/src/frame.rs (2 hunks)
  • vm/src/stdlib/typing.rs (1 hunks)
🧰 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/stdlib/typing.rs
  • vm/src/frame.rs
  • compiler/core/src/bytecode.rs
  • compiler/codegen/src/compile.rs
🧬 Code Graph Analysis (1)
vm/src/frame.rs (3)
vm/src/stdlib/typing.rs (1)
  • new (109-115)
vm/src/protocol/sequence.rs (1)
  • tuple (279-289)
vm/src/builtins/genericalias.rs (1)
  • type_params (626-626)
⏰ 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 (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run tests under miri
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
🔇 Additional comments (11)
vm/src/stdlib/typing.rs (3)

117-120: LGTM!

The property getter correctly exposes the name field to Python.


122-125: LGTM!

The property getter correctly exposes the value field to Python.


127-130: LGTM!

The property getter correctly exposes the type_params tuple to Python.

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

385-392: LGTM!

The intrinsic functions for type parameter handling are properly defined with sequential discriminant values.


401-403: LGTM!

The intrinsic functions for bounded and constrained type variables are properly defined.


660-660: Confirmed LAST_INSTRUCTION update

ExtendedArg is the final variant in the Instruction enum, so setting
const LAST_INSTRUCTION: Instruction = Instruction::ExtendedArg;
is correct. Approving the change.

  • Location: compiler/core/src/bytecode.rs (lines 655–660)
compiler/codegen/src/compile.rs (3)

1070-1104: Well-structured refactoring to use intrinsic functions.

The changes correctly refactor the TypeAlias compilation to use intrinsic function calls instead of direct bytecode instructions. The addition of stack state comments improves code clarity and maintainability.


1257-1272: Consistent refactoring of TypeVar compilation.

The TypeVar and TypeVarWithBound compilation correctly uses the new intrinsic function pattern, maintaining the same functionality while aligning with the architectural shift.


1295-1327: Uniform refactoring of remaining type parameter constructs.

ParamSpec and TypeVarTuple compilation follows the same intrinsic function pattern, completing the consistent refactoring of all PEP 695 type parameter constructs.

vm/src/frame.rs (2)

2210-2228: LGTM! Clean implementation of typing intrinsics.

The TypeVar, ParamSpec, and TypeVarTuple intrinsic functions are implemented correctly, following the expected pattern for creating these typing constructs.


2277-2290: LGTM! TypeVar variants implemented correctly.

The TypeVarWithBound and TypeVarWithConstraint intrinsic functions properly handle the two-argument variants of TypeVar creation.

Comment on lines +132 to +136
#[pymethod(name = "__repr__")]
fn repr(&self, vm: &VirtualMachine) -> PyResult<String> {
let name = self.name.str(vm)?;
Ok(name.as_str().to_owned())
}
Copy link
Contributor

@coderabbitai coderabbitai bot Jul 11, 2025

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the repr format matches Python's TypeAliasType behavior.

The current implementation returns only the alias name. Please verify this matches the expected behavior in Python 3.12+.


🏁 Script executed:

#!/bin/bash
# Check if there are any tests that verify the __repr__ behavior
rg -A 5 "TypeAliasType.*__repr__" --type rust
rg -A 10 "test.*type.*alias.*repr" --type rust -i

Length of output: 99


🌐 Web query:

What is the expected __repr__ format for TypeAliasType in Python 3.12?

💡 Result:

In Python 3.12, the type statement and the introduction of the TypeAliasType object in typing provide structured, introspectable type aliases. When you define a type alias using the new syntax, for example:

type Vector = list[float]

Python internally creates an instance of TypeAliasType named Vector[4][2][5]. The expected __repr__ output for such a type alias reflects this new type object:

<TypeAliasType Vector>

This matches the pattern Python uses for many higher-level type objects, showing both the type (TypeAliasType) and the alias name (Vector). If you inspect the alias at runtime—e.g., with repr(Vector)—you should see output in this form[4].

For TypeAliasType instances constructed manually (rare in typical library code but possible for advanced users or tools), the format is the same:

from typing import TypeAliasType
MyAlias = TypeAliasType('MyAlias', list[int], ())
repr(MyAlias)
# Output: <TypeAliasType MyAlias>

This format—<TypeAliasType AliasName>—is standard and allows for clear introspection and debugging of type aliases in Python 3.12 and later[4].

Note: If you're using the TypeAlias annotation (not the new type statement), the object is just the type itself (e.g., <class 'list'> for Vector: TypeAlias = list[float]), not a TypeAliasType object, so its __repr__ will be the usual for that type[4][2]. The specialized __repr__ is specific to TypeAliasType created via the type statement or explicitly with TypeAliasType().

Summary table:

Alias Definition Style Object Type repr Output Example
type MyAlias = list[int] TypeAliasType <TypeAliasType MyAlias>
MyAlias: TypeAlias = list[int] underlying type <class 'list'>

This behavior is consistent with Python 3.12+ static typing changes and improves the introspection of aliases during development and debugging[4][5].

Citations:


Update __repr__ to match Python 3.12’s <TypeAliasType AliasName> format

The current implementation returns only the alias name (e.g. "Vector"), but Python 3.12’s TypeAliasType should repr as <TypeAliasType Vector>. Please update the method accordingly:

• File: vm/src/stdlib/typing.rs
Lines: 132–136

         #[pymethod(name = "__repr__")]
         fn repr(&self, vm: &VirtualMachine) -> PyResult<String> {
-            let name = self.name.str(vm)?;
-            Ok(name.as_str().to_owned())
+            let name = self.name.str(vm)?;
+            Ok(format!("<TypeAliasType {}>", name.as_str()))
         }

• Add a unit test (e.g. in tests/typing.rs) to assert that
repr(type Vector = list[float]) == "<TypeAliasType Vector>".
This will ensure your implementation aligns with upstream Python behavior.

📝 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
#[pymethod(name = "__repr__")]
fn repr(&self, vm: &VirtualMachine) -> PyResult<String> {
let name = self.name.str(vm)?;
Ok(name.as_str().to_owned())
}
#[pymethod(name = "__repr__")]
fn repr(&self, vm: &VirtualMachine) -> PyResult<String> {
let name = self.name.str(vm)?;
Ok(format!("<TypeAliasType {}>", name.as_str()))
}
🤖 Prompt for AI Agents
In vm/src/stdlib/typing.rs lines 132 to 136, update the repr method to return a
string formatted as "<TypeAliasType AliasName>" instead of just the alias name.
Modify the code to include the fixed prefix "<TypeAliasType " and suffix ">"
around the alias name. Additionally, add a unit test in tests/typing.rs that
creates a type alias like Vector = list[float] and asserts that its repr output
equals "<TypeAliasType Vector>" to verify compliance with Python 3.12 behavior.

Copy link
Member Author

Choose a reason for hiding this comment

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

>>> type A = object
>>> A
A
>>> repr(A)
'A'

Copy link
Contributor

Choose a reason for hiding this comment

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

@youknowone Thank you for the correction! You're absolutely right. The current implementation in the diff is correct - it returns just the alias name as a string, which matches the actual behavior in Python 3.12.

I apologize for the confusion in my previous analysis. The web search results were misleading about the __repr__ format. Your demonstration clearly shows that repr(A) returns 'A' (just the alias name), not <TypeAliasType A>.

The current implementation is working as expected and aligns with Python 3.12's actual behavior.


✏️ Learnings added
Learnt from: youknowone
PR: RustPython/RustPython#5945
File: vm/src/stdlib/typing.rs:132-136
Timestamp: 2025-07-11T07:16:06.209Z
Learning: In Python 3.12, TypeAliasType's __repr__ method returns just the alias name as a string (e.g., repr(A) returns 'A'), not the "<TypeAliasType AliasName>" format. This applies to type aliases created with the `type` statement syntax.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
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

@youknowone youknowone merged commit 0ae6b45 into RustPython:main Jul 11, 2025
22 of 23 checks passed
@youknowone youknowone deleted the type-alias branch July 11, 2025 07:16
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.

1 participant