Skip to content

PyCode::qualname #5929

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 10, 2025
Merged

PyCode::qualname #5929

merged 1 commit into from
Jul 10, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jul 10, 2025

Summary by CodeRabbit

  • New Features

    • Added support for tracking and exposing the fully qualified name of code objects.
    • Introduced a new Python property co_qualname to retrieve the qualified name of code objects.
  • Bug Fixes

    • Ensured the qualified name is preserved when code objects are replaced.
  • Chores

    • Updated serialization and deserialization to include the qualified name for code objects.

Copy link
Contributor

coderabbitai bot commented Jul 10, 2025

Walkthrough

A new qualname (qualified name) field is introduced and propagated across the code generation, bytecode, and VM layers. This field tracks the fully qualified name of code objects (such as functions, classes, lambdas, and comprehensions) during compilation, serialization, and runtime. Accessors and serialization logic are updated to handle this new field.

Changes

File(s) Change Summary
compiler/codegen/src/compile.rs Introduced and updated qualname handling in Compiler, propagating it through code object compilation for functions, classes, lambdas, and comprehensions.
compiler/codegen/src/ir.rs Added qualname: Option<String> to CodeInfo; updated construction and finalization logic to use it.
compiler/core/src/bytecode.rs Added public qualname field to CodeObject; updated mapping methods to include it.
compiler/core/src/marshal.rs Updated serialization and deserialization to read/write the new qualname field for code objects.
vm/src/builtins/code.rs Added Python-accessible co_qualname property to PyCode; ensured qualname is preserved in replacements.

Sequence Diagram(s)

sequenceDiagram
    participant Compiler
    participant CodeInfo
    participant CodeObject
    participant marshal
    participant PyCode

    Compiler->>CodeInfo: Create with qualname (from code context)
    CodeInfo->>CodeObject: Finalize, passing qualname
    CodeObject->>marshal: Serialize/deserialize qualname
    CodeObject->>PyCode: Expose qualname as co_qualname property
Loading

Poem

In the warren of code, a name travels far,
From compiler’s nibble to bytecode jar.
Now each function and class, in full acclaim,
Bears its qualname—never the same!
With marshaled care and Python’s delight,
Rabbits rejoice: “Qualified names, done right!”
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 28034cd and 0a7d2a6.

⛔ Files ignored due to path filters (1)
  • Lib/test/test_code.py is excluded by !Lib/**
📒 Files selected for processing (5)
  • compiler/codegen/src/compile.rs (7 hunks)
  • compiler/codegen/src/ir.rs (3 hunks)
  • compiler/core/src/bytecode.rs (3 hunks)
  • compiler/core/src/marshal.rs (3 hunks)
  • vm/src/builtins/code.rs (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • compiler/core/src/bytecode.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • vm/src/builtins/code.rs
  • compiler/codegen/src/ir.rs
  • compiler/core/src/marshal.rs
  • compiler/codegen/src/compile.rs
⏰ 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: Check Rust code with rustfmt and clippy
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run tests under miri
  • 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 (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Ensure compilation on various targets
✨ 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: 0

🧹 Nitpick comments (2)
compiler/codegen/src/compile.rs (2)

405-411: Optimize redundant string cloning.

The logic for calculating qualname is correct, but there's an opportunity to optimize the string handling.

Apply this diff to avoid redundant cloning:

-        // Calculate qualname based on the current qualified path
-        let qualname = if self.qualified_path.is_empty() {
-            Some(obj_name.clone())
-        } else {
-            Some(self.qualified_path.join("."))
-        };
+        // Calculate qualname based on the current qualified path
+        let qualname = if self.qualified_path.is_empty() {
+            Some(obj_name.clone())
+        } else {
+            Some(self.qualified_path.join("."))
+        };

Actually, the current implementation is fine. The obj_name is used later in the struct, so the clone is necessary.


313-314: Consider refactoring to reduce code duplication.

The pattern of updating qualname after pushing qualified paths is repeated across functions, classes, and comprehensions. While the current implementation is correct, consider extracting this into a helper method to improve maintainability.

Consider adding a helper method like:

fn update_qualname_from_path(&mut self) {
    let qualified_name = self.qualified_path.join(".");
    self.code_stack.last_mut().unwrap().qualname = Some(qualified_name);
}

This would reduce the repeated pattern of self.qualified_path.join(".") and make the intent clearer.

Also applies to: 405-411, 420-420, 507-509, 513-514, 735-736, 978-979

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 54ff198 and 28034cd.

📒 Files selected for processing (5)
  • compiler/codegen/src/compile.rs (7 hunks)
  • compiler/codegen/src/ir.rs (3 hunks)
  • compiler/core/src/bytecode.rs (3 hunks)
  • compiler/core/src/marshal.rs (3 hunks)
  • vm/src/builtins/code.rs (2 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/builtins/code.rs
  • compiler/codegen/src/ir.rs
  • compiler/core/src/marshal.rs
  • compiler/core/src/bytecode.rs
  • compiler/codegen/src/compile.rs
⏰ 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 rust tests (ubuntu-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run tests under miri
🔇 Additional comments (16)
vm/src/builtins/code.rs (2)

301-304: LGTM! Clean implementation of co_qualname getter.

The implementation follows the same pattern as other code object getters and correctly exposes the qualified name to Python code.


408-408: Good preservation of qualname in replace method.

The qualified name is correctly preserved when creating replaced code objects, ensuring consistency with the original code object's identity.

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

76-76: Well-designed optional qualname field.

The optional qualname field allows flexible qualified name tracking during code generation, with appropriate fallback handling in finalize_code.


167-168: Correct fallback logic for qualname.

The implementation properly falls back to obj_name when qualname is not set, ensuring code objects always have a qualified name. The clone() is necessary since obj_name is moved in the destructuring.

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

118-119: Clean addition of qualname field with proper documentation.

The field is correctly typed as C::Name and includes helpful documentation referencing CPython's co_qualname for clarity.


1145-1145: Consistent qualname mapping in map_bag method.

The qualified name is properly mapped using bag.make_name(), maintaining consistency with other name field mappings like obj_name and source_path.


1175-1175: Consistent qualname mapping in map_clone_bag method.

The qualified name mapping in the clone variant follows the same pattern as the non-clone version, ensuring consistency across both mapping methods.

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

213-214: Correct deserialization of qualname field.

The qualified name is properly read from the marshaled data using the same pattern as other string fields, with appropriate length-prefixed reading.


256-256: Proper inclusion of qualname in CodeObject construction.

The deserialized qualified name is correctly included in the CodeObject construction, maintaining field order consistency.


616-616: Symmetric serialization of qualname field.

The qualified name is properly serialized using write_vec() in the same position as it's read during deserialization, ensuring symmetric marshaling behavior.

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

313-314: LGTM: Proper initialization of qualname in constructor.

The qualname is correctly initialized to the code name in the Compiler::new constructor, establishing the base case for module-level code objects.


420-420: LGTM: Qualname correctly stored in CodeInfo.

The qualname field is properly included in the ir::CodeInfo structure creation.


507-509: LGTM: Function qualname correctly updated.

The qualname is appropriately updated after establishing the qualified path for the function, ensuring it reflects the full qualified name.


513-514: LGTM: Lambda qualname follows Python conventions.

Setting the lambda qualname to "<lambda>" is correct and follows standard Python behavior for anonymous functions.


735-736: LGTM: Class qualname handling is consistent.

The qualname update for classes follows the same pattern as functions, ensuring consistency across different code object types.


978-979: LGTM: Comprehension qualname correctly set.

Setting the comprehension qualname to the comprehension name (e.g., "<listcomp>") is appropriate and follows Python conventions.

@youknowone youknowone merged commit 18d7c1b into RustPython:main Jul 10, 2025
12 checks passed
@youknowone youknowone deleted the co_qualname branch July 10, 2025 01:27
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