Skip to content

Tidy codegen::ir::BlockIdx api - #6413

Merged
youknowone merged 2 commits into
RustPython:mainfrom
ShaharNaveh:ir-blockidx-api-tidy
Dec 12, 2025
Merged

youknowone merged 2 commits into
RustPython:mainfrom
ShaharNaveh:ir-blockidx-api-tidy

Conversation

@ShaharNaveh

@ShaharNaveh ShaharNaveh commented Dec 12, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Refactor
    • Streamlined compiler/internal codegen types and public interfaces to unify block identifiers and improve consistency across the code generation module. This reduces internal surface area and aims to make future maintenance and API evolution safer without changing runtime behavior.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 12, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

BlockIdx was encapsulated (inner u32 made private) and given pub const fn new and From<BlockIdx> for u32; the codegen compiler API and call sites were updated to use BlockIdx (and BlockIdx::new / BlockIdx::NULL) instead of ir::BlockIdx and direct tuple construction.

Changes

Cohort / File(s) Summary
BlockIdx Type Encapsulation
crates/codegen/src/ir.rs
Made BlockIdx's inner u32 private; added pub const fn new(value: u32) -> Self; changed NULL to BlockIdx::new(u32::MAX); added impl From<BlockIdx> for u32; retained idx() and updated indexing impls to use it.
Compiler API and Usage Updates
crates/codegen/src/compile.rs
Replaced ir::BlockIdx usages with BlockIdx; updated initializations from ir::BlockIdx(0) to BlockIdx::new(0); switched ir::BlockIdx::NULL → BlockIdx::NULL; adjusted public signatures and trait return types (_emit, new_block, switch_to_block, EmitArg impls) to use BlockIdx.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Verify all public-facing function signatures and trait impls compile after the type rename.
  • Check every call site for correct use of BlockIdx::new() versus BlockIdx::NULL.
  • Confirm the From<BlockIdx> for u32 conversion is used correctly in indexing and that no implicit tuple access remains.
  • Ensure no remaining ir::BlockIdx references in public APIs or inter-module boundaries.

Poem

🐰 I hopped in code where indices play,
I tucked the inner bits away,
A gentle new, a quiet turn,
Now BlockIdx keeps its secrets firm.
✨ Small hops, neat changes — off I go!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: refactoring the BlockIdx API to be more tidy by making the inner field private and introducing proper constructor/conversion methods.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (2)
crates/codegen/src/ir.rs (1)

50-54: From<BlockIdx> for u32 is a good interop hook.
Consider also adding a small as_u32() inherent if you want to avoid sprinkling u32::from(...) at call sites, but current approach is fine.

crates/codegen/src/compile.rs (1)

5403-5420: Prefer comparing against BlockIdx::NULL (avoid re-encoding the sentinel as u32::MAX).
This keeps the “NULL == u32::MAX” detail encapsulated inside BlockIdx.

-        assert_eq!(
-            u32::from(prev_block.next),
-            u32::MAX,
-            "switching {prev:?} -> {block:?} from block that's already got a next"
-        );
+        assert_eq!(
+            prev_block.next,
+            BlockIdx::NULL,
+            "switching {prev:?} -> {block:?} from block that's already got a next"
+        );
📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5a5b721 and 5400ca9.

📒 Files selected for processing (2)
  • crates/codegen/src/compile.rs (9 hunks)
  • crates/codegen/src/ir.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style by running cargo fmt to format Rust code
Always run clippy to lint Rust code (cargo clippy) before completing tasks and fix any warnings or lints introduced by 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

Files:

  • crates/codegen/src/ir.rs
  • crates/codegen/src/compile.rs
🧬 Code graph analysis (2)
crates/codegen/src/ir.rs (1)
crates/codegen/src/compile.rs (2)
  • new (325-332)
  • new (353-395)
crates/codegen/src/compile.rs (1)
crates/codegen/src/ir.rs (4)
  • new (39-41)
  • idx (45-47)
  • default (104-109)
  • from (51-53)
⏰ 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). (10)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • 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: Run snippets and cpython tests on wasm-wasi
  • GitHub Check: Check Rust code with clippy
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (7)
crates/codegen/src/ir.rs (1)

32-48: Nice encapsulation of BlockIdx + clearer construction API.
Private inner field + const fn new() keeps invariants local and forces call sites away from tuple-field access.

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

124-128: Good: loop_data now carries BlockIdx directly (no ir:: noise).


359-360: Good: construction sites moved to BlockIdx::new(0).
Keeps call sites compatible now that the inner field is private.

Also applies to: 748-749


5331-5349: Good: _emit/emit_no_arg consistently use BlockIdx::NULL.


5396-5401: Good: new_block() returns BlockIdx and constructs via BlockIdx::new.


5708-5726: EmitArg returning a BlockIdx target is a clean separation of “arg vs jump target”.
The EmitArg<bytecode::Label> for BlockIdx specialization reads well at call sites.


32-33: Run cargo fmt and cargo clippy before merging.

cargo fmt --all
cargo clippy --all-targets --all-features -- -D warnings

Comment thread crates/codegen/src/ir.rs Resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (3)
crates/codegen/src/ir.rs (3)

31-48: Nice encapsulation of BlockIdx + const fn constructor/accessor.
This tightens the API surface cleanly and keeps call sites ergonomic (NULL, new, idx). Consider adding #[repr(transparent)] if you ever rely on layout/FFI (optional).

Ensure cargo fmt + cargo clippy stay clean per repo guidelines.


50-54: From<BlockIdx> for u32 is good; consider symmetric From<u32> for BlockIdx for .into().
Not required since BlockIdx::new exists, but symmetry often improves readability at call sites.


176-217: Avoid direct BlockIdx(0) / .0 usage inside this module to fully realize the “tidy API” goal.
Even though it’s legal within the defining module, using BlockIdx::new(0) and u32::from(...) makes the encapsulation intent consistent and reduces future refactor footguns.

-            let mut next_block = BlockIdx(0);
+            let mut next_block = BlockIdx::new(0);

-        stack.push(BlockIdx(0));
+        stack.push(BlockIdx::new(0));

-                eprintln!("===BLOCK {}===", block.0);
+                eprintln!("===BLOCK {}===", u32::from(block));

-                        OpArg(ins.target.0)
+                        OpArg(u32::from(ins.target))

-fn iter_blocks(blocks: &[Block]) -> impl Iterator<Item = (BlockIdx, &Block)> + '_ {
-    let mut next = BlockIdx(0);
+fn iter_blocks(blocks: &[Block]) -> impl Iterator<Item = (BlockIdx, &Block)> + '_ {
+    let mut next = BlockIdx::new(0);

Also applies to: 292-366, 402-412

📜 Review details

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5400ca9 and f764a88.

📒 Files selected for processing (1)
  • crates/codegen/src/ir.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.rs: Follow the default rustfmt code style by running cargo fmt to format Rust code
Always run clippy to lint Rust code (cargo clippy) before completing tasks and fix any warnings or lints introduced by 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

Files:

  • crates/codegen/src/ir.rs
🧬 Code graph analysis (1)
crates/codegen/src/ir.rs (1)
crates/codegen/src/compile.rs (2)
  • new (325-332)
  • new (353-395)
⏰ 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 rust tests (macos-latest)
  • 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 (windows-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Check Rust code with clippy
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (1)
crates/codegen/src/ir.rs (1)

56-82: Indexing impls look correct and keep BlockIdx-based indexing readable.
Using idx.idx() avoids exposing internals and doesn’t recurse (it indexes via usize).

@youknowone youknowone left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Did you have any motivation to work on it?
e.g. Was this not working good for your another patch?

@ShaharNaveh

Copy link
Copy Markdown
Contributor Author

Did you have any motivation to work on it? e.g. Was this not working good for your another patch?

IMO this looks cleaner, but not something critical. Generally, I prefer to not have a tuple struct with a pub item inside, this makes it easy to bypass any validation that you might want to add in your TryFrom or ::new method, we can always have new_unchecked that does what BlockIdx(val) do, (in this example every u32 is valid, but for other structs it might not be always the case)

@ShaharNaveh

Copy link
Copy Markdown
Contributor Author

@youknowone
youknowone merged commit 75dcf80 into RustPython:main Dec 12, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Feb 28, 2026
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