10000 Add `raise_if_stop!` macro for `protocol/iter.rs` by ShaharNaveh · Pull Request #5885 · RustPython/RustPython · GitHub
[go: up one dir, main page]

Skip to content

Add raise_if_stop! macro for protocol/iter.rs #5885

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 12 commits into from
Jul 2, 2025

Conversation

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

Summary by CodeRabbit

  • Refactor
    • Improved iterator handling for smoother operation and consistent error messaging.
    • Simplified constructor methods and error message formatting for iterator objects.

No changes to user-facing features or functionality.

Copy link
Contributor
coderabbitai bot commented Jul 2, 2025

Walkthrough

A new macro, raise_if_stop!, was introduced in the iterator protocol and itertools modules to unify handling of PyIterReturn variants. Existing iterator implementations were refactored to use this macro, and struct instantiations and error message formatting were streamlined for conciseness. No core logic or control flow was changed.

Changes

File(s) Change Summary
vm/src/protocol/iter.rs Added and exported new macro raise_if_stop! for handling PyIterReturn variants uniformly.
vm/src/stdlib/itertools.rs Refactored iterator next methods to use raise_if_stop! macro; simplified struct instantiations and error message formatting.

Poem

In the garden of code where iterators grow,
A macro now helps the returns to flow.
With concise new forms and errors made neat,
The itertools rabbits hop on nimble feet.
No logic disturbed, just tidier rows—
Onward the Pythonic breeze now blows!
🐇✨


📜 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 84167d2 and a8d3dbe.

📒 Files selected for processing (2)
  • vm/src/protocol/iter.rs (1 hunks)
  • vm/src/stdlib/itertools.rs (30 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • vm/src/protocol/iter.rs
  • vm/src/stdlib/itertools.rs
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython 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 Rust code with rustfmt and clippy
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
✨ 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.

@@ -1,5 +1,14 @@
pub(crate) use decl::make_module;

macro_rules! handle_pyiter_return {
Copy link
Member

Choose a reason for hiding this comment

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

This macro is expected to be defined on vm/src/protocol/iter.rs because it is mainly a function of PyIterReturn.

The name can be simplified as what it means in Python.

Suggested change
macro_rules! handle_pyiter_return {
macro_rules! raise_stop {

I like this idea 👍

@ShaharNaveh ShaharNaveh changed the title Add handle_pyiter_return! macro for itertools Add raise_stop! macro for protocol/iter.rs Jul 2, 2025
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: 2

🧹 Nitpick comments (1)
vm/src/protocol/iter.rs (1)

282-289: Consider error propagation in the macro.

The macro doesn't handle potential errors that might occur when evaluating the input expression. If the input expression can fail, those errors should be propagated.

Consider this alternative implementation that handles potential errors in the input:

 macro_rules! raise_stop {
     ($input:expr) => {
-        match $input {
+        match $input? {
             $crate::protocol::PyIterReturn::Return(obj) => obj,
             $crate::protocol::PyIterReturn::StopIteration(v) => {
                 return Ok($crate::protocol::PyIterReturn::StopIteration(v))
             }
         }
     };
 }

However, verify this change aligns with the intended usage patterns in vm/src/stdlib/itertools.rs.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1f93b95 and 27c64de.

📒 Files selected for processing (2)
  • vm/src/protocol/iter.rs (1 hunks)
  • vm/src/stdlib/itertools.rs (30 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • vm/src/stdlib/itertools.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/protocol/iter.rs
🧠 Learnings (2)
📓 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 : 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
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Check Rust code with rustfmt and clippy
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
  • GitHub Check: Run tests under miri
  • GitHub Check: Run snippets and cpython tests (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Check the WASM package and demo
🔇 Additional comments (1)
vm/src/protocol/iter.rs (1)

280-290: Macro implementation follows Rust best practices.

The macro correctly uses $crate:: prefix for absolute path resolution and implements the expected pattern matching logic for PyIterReturn handling. The early return pattern is appropriate for iterator implementations.

Comment on lines 280 to 290
#[macro_export]
macro_rules! raise_stop {
($input:expr) => {
match $input {
$crate::protocol::PyIterReturn::Return(obj) => obj,
$crate::protocol::PyIterReturn::StopIteration(v) => {
return Ok($crate::protocol::PyIterReturn::StopIteration(v))
}
}
};
}
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

Add documentation for the macro's usage constraints.

The macro assumes it's used within a function that returns PyResult<PyIterReturn>, but this constraint isn't documented. Consider adding documentation to clarify the expected usage context.

Add documentation above the macro:

+/// Macro to handle `PyIterReturn` values in iterator implementations.
+/// 
+/// Extracts the object from `PyIterReturn::Return(obj)` or performs early return
+/// for `PyIterReturn::StopIteration(v)`. This macro should only be used within
+/// functions that return `PyResult<PyIterReturn>`.
+/// 
+/// # Example
+/// ```rust
+/// fn iterator_next(&self, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
+///     let value = raise_stop!(some_pyiter_return_value);
+///     // Process the extracted value...
+/// }
+/// ```
 #[macro_export]
 macro_rules! raise_stop {
🤖 Prompt for AI Agents
In vm/src/protocol/iter.rs around lines 280 to 290, the raise_stop! macro lacks
documentation specifying that it must be used within a function returning
PyResult<PyIterReturn>. Add a doc comment above the macro definition explaining
this usage constraint and provide a brief example showing how to use the macro
inside such a function to clarify its expected context.

⚠️ Potential issue

Naming inconsistency with PR objectives.

The PR title mentions handle_pyiter_return! macro, but the implemented macro is named raise_stop!. Please ensure the naming is consistent with the intended functionality and PR objectives.

Consider renaming the macro to match the PR title:

-macro_rules! raise_stop {
+macro_rules! handle_pyiter_return {

Or update the PR title if raise_stop! is the preferred name.

📝 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
#[macro_export]
macro_rules! raise_stop {
($input:expr) => {
match $input {
$crate::protocol::PyIterReturn::Return(obj) => obj,
$crate::protocol::PyIterReturn::StopIteration(v) => {
return Ok($crate::protocol::PyIterReturn::StopIteration(v))
}
}
};
}
#[macro_export]
macro_rules! handle_pyiter_return {
($input:expr) => {
match $input {
$crate::protocol::PyIterReturn::Return(obj) => obj,
$crate::protocol::PyIterReturn::StopIteration(v) => {
return Ok($crate::protocol::PyIterReturn::StopIteration(v))
}
}
};
}
🤖 Prompt for AI Agents
In vm/src/protocol/iter.rs around lines 280 to 290, the macro is named
raise_stop! but the PR title refers to handle_pyiter_return!. Rename the macro
from raise_stop! to handle_pyiter_return! to maintain consistency with the PR
objectives, or alternatively update the PR title to reflect the current macro
name if that is preferred.

PyIterReturn::Return(obj) => obj,
PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)),
};
let obj = raise_stop!(zelf.iterable.next(vm)?);
Copy link
Member

Choose a reason for hiding this comment

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

uh, my fault. now returning a value from raise_stop! looks awkward.

Suggested change
let obj = raise_stop!(zelf.iterable.next(vm)?);
let obj = raise_if_stop!(zelf.iterable.next(vm)?);

I will add if in the middle

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No worries it's just a simple: :%s/raise_stop/raise_if_stop/g 😉

@ShaharNaveh ShaharNaveh changed the title Add raise_stop! macro for protocol/iter.rs Add raise_if_stop! macro for protocol/iter.rs Jul 2, 2025
@ShaharNaveh ShaharNaveh requested a review from youknowone July 2, 2025 15:32
@youknowone youknowone merged commit b6acfe0 into RustPython:main Jul 2, 2025
12 checks passed
@ShaharNaveh ShaharNaveh deleted the cleanup-itertools branch July 3, 2025 07:20
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