Skip to content

Refactor compile_function #6001

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 3 commits into from
Jul 20, 2025
Merged

Refactor compile_function #6001

merged 3 commits into from
Jul 20, 2025

Conversation

youknowone
Copy link
Member

@youknowone youknowone commented Jul 19, 2025

Summary by CodeRabbit

  • New Features

    • Improved support for generic functions and classes with enhanced handling of type parameters and symbol tables.
    • Added new error messages for invalid expressions within type parameter scopes.
  • Bug Fixes

    • Corrected stack swap behavior to ensure accurate execution of swap instructions.
    • Expanded optimization checks to include async functions.
  • Refactor

    • Modularized function and class compilation for better maintainability and clarity.
    • Centralized symbol table and name resolution logic for improved consistency.
  • Documentation

    • Updated internal comments for clarity regarding docstring cleaning.

Copy link
Contributor

coderabbitai bot commented Jul 19, 2025

Walkthrough

This update refactors and modularizes the compiler's symbol table and scope management, adding helper methods for variable indexing, enhancing qualified name handling, and restructuring function and class compilation to better support type parameter scopes. It also introduces stricter checks for invalid expressions in type parameter contexts and adjusts stack operations and symbol table optimization logic.

Changes

File(s) Change Summary
compiler/codegen/src/compile.rs Refactored symbol table and scope management, added helper methods for variable indices, improved qualified name logic, modularized function/class/type param compilation, and updated docstring handling.
compiler/codegen/src/ir.rs Added symbol_table_index to CodeInfo; updated related logic and block stack checks in stack depth calculation.
compiler/codegen/src/symboltable.rs Added error checks to disallow yield, await, and named expressions in type parameter scopes.
vm/src/frame.rs Corrected stack index calculation for the Swap instruction to align with intended semantics.
vm/src/stdlib/symtable.rs Broadened is_optimized to include async functions in addition to regular functions.

Sequence Diagram(s)

sequenceDiagram
    participant Compiler
    participant SymbolTable
    participant CodeInfo

    Compiler->>SymbolTable: push_symbol_table()
    Note right of SymbolTable: Panic if no sub-tables
    Compiler->>CodeInfo: enter_scope(name, scope_type, key, lineno)
    Note right of CodeInfo: Set symbol_table_index
    Compiler->>SymbolTable: get_var_index(name, var_type)
    Compiler->>SymbolTable: pop_symbol_table()
    Compiler->>CodeInfo: exit_scope()
Loading
sequenceDiagram
    participant Compiler
    participant SymbolTable

    Compiler->>SymbolTable: scan_expression(expr)
    alt Scope is TypeParams
        SymbolTable-->>Compiler: Error if expr is yield/await/named
    else
        SymbolTable-->>Compiler: Continue scanning
    end
Loading

Possibly related PRs

Poem

In the warren of symbols, a rabbit hops with glee,
Refactoring the names, as tidy as can be!
Type params now guarded, no yields in their den,
Classes and functions—modularized again.
With stacks swapped just right,
And scopes shining bright,
This code is a carrot—crisp, clean, and light! 🥕

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

@youknowone youknowone marked this pull request as ready for review July 20, 2025 01:29
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 (1)
compiler/codegen/src/symboltable.rs (1)

1015-1036: LGTM! Well-implemented type parameter expression validation.

The new validation logic correctly enforces Python's semantic rules for type parameter scopes. The implementation properly:

  • Checks the current scope type before applying restrictions
  • Uses comprehensive pattern matching for prohibited expressions
  • Provides clear error messages with precise location information
  • Follows Rust best practices for error handling

Consider using "assignment expression" instead of "named expression" in the error message for consistency with Python terminology:

-                    Expr::Named(_) => Some("named"),
+                    Expr::Named(_) => Some("assignment"),

And update the error message format string accordingly:

-                            "{keyword} expression cannot be used within a type parameter"
+                            "{keyword} expression cannot be used within a type parameter"

This would make the error message "assignment expression cannot be used within a type parameter" which aligns better with standard Python terminology.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between da5a44e and bbc6171.

📒 Files selected for processing (5)
  • compiler/codegen/src/compile.rs (17 hunks)
  • compiler/codegen/src/ir.rs (3 hunks)
  • compiler/codegen/src/symboltable.rs (1 hunks)
  • vm/src/frame.rs (1 hunks)
  • vm/src/stdlib/symtable.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .github/copilot-instructions.md
🧠 Learnings (1)
vm/src/stdlib/symtable.rs (1)
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-19T03:16:56.511Z
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). (9)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (ubuntu-latest)
🔇 Additional comments (14)
vm/src/stdlib/symtable.rs (1)

73-76: LGTM! Proper extension of optimization to async functions.

The change correctly extends optimization recognition to async functions using the idiomatic matches! macro. This aligns well with the broader compiler enhancements for async function scope handling.

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

104-106: Good addition for symbol table tracking.

The new symbol_table_index field properly links code objects to their symbol tables, supporting the enhanced symbol table management mentioned in the refactoring. The field is correctly integrated into the struct and destructuring pattern.


325-328: Solid defensive programming improvement.

The conditional check prevents pushing null block indices onto the stack during stack depth calculation, which could otherwise cause issues. This is a good defensive programming practice that improves robustness.

vm/src/frame.rs (1)

698-707: Add unit tests to verify the Swap instruction index calculation

We couldn’t find any existing tests or documentation for Instruction::Swap. The current code in vm/src/frame.rs (≈ lines 698–707) computes:

  • i = len – 1 (TOS index)
  • index_val = index.get(arg) as usize
  • j = len – index_val

But swapping TOS with the element i positions down usually maps to index (len – 1) – i. Please:

  • Add targeted unit tests for Swap(i) (e.g., small stacks, various i values)
  • Confirm whether j = len – index_val matches the intended semantics or needs adjustment
compiler/codegen/src/compile.rs (10)

388-439: LGTM! Well-structured helper methods for symbol table management.

These helper methods effectively centralize variable index management and improve code maintainability.


441-462: Good defensive programming with the sub_tables check.

The added validation prevents attempting to remove from an empty vector and provides a helpful error message for debugging.


602-602: Correct initialization of symbol_table_index field.

The field is properly set to link the code object with its symbol table.


680-693: Appropriate removal of the sub_tables assertion.

The comment clearly documents why various scope types can have remaining sub_tables, making this change correct for the enhanced type parameter support.


754-844: Excellent refactoring of qualified name generation.

The enhanced logic properly handles type parameter scopes, global symbols, and function locals according to Python semantics. The implementation is well-documented and covers all necessary cases.


987-1113: Excellent unification of name operation handling.

The refactored compile_name method provides clear separation of concerns with the NameOp enum and comprehensive handling of all name operation scenarios, including proper type parameter scope support.


1925-2089: Well-designed modularization of function compilation logic.

The three helper methods effectively separate concerns for default arguments, function body compilation, and annotation processing. This improves code organization and maintainability.


2093-2230: Comprehensive implementation of PEP 695 generic function support.

The refactored method effectively orchestrates the compilation of both regular and generic functions, with proper handling of type parameters, defaults passing, and stack management.


2437-2666: Robust implementation of generic class compilation.

The changes properly handle both regular and generic classes, with correct setup of class namespaces, type parameters, and the generic base mechanism required by PEP 695.


5413-5414: Better documentation reference.

The updated comment more accurately describes the function's relationship to inspect.cleandoc.

@youknowone youknowone merged commit 5284b73 into RustPython:main Jul 20, 2025
12 checks passed
@youknowone youknowone deleted the scope branch July 20, 2025 01:57
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