Skip to content

Conversation

@youknowone
Copy link
Member

@youknowone youknowone commented Dec 10, 2025

Summary by CodeRabbit

  • Refactor
    • Streamlined internal type validation logic for built-in methods and string objects.
    • Simplified type-checking mechanisms to improve code maintainability.

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 10, 2025

Walkthrough

Updates PyPayload trait to introduce a validate_downcastable_from extension point for custom downcast validation. Modifies PyUtf8Str to use this hook for UTF-8 validation without duplicate typeid checks. Updates PyNativeMethod to leverage the pyclass ctx parameter mechanism for type context.

Changes

Cohort / File(s) Change Summary
PyPayload Trait Extension
crates/vm/src/object/payload.rs
Adds new validate_downcastable_from(&obj) -> bool default method to PyPayload trait; updates downcastable_from() to require both typeid matching and custom validation check.
Builtin Function Type
crates/vm/src/builtins/builtin_func.rs
Adds ctx = "builtin_method_type" parameter to PyNativeMethod pyclass declaration; removes PyPayload impl block that provided custom class(ctx) lookup.
String Type Validation
crates/vm/src/builtins/str.rs
Renames PyUtf8Str's PyPayload method from downcastable_from() to validate_downcastable_from(); removes duplicate typeid check and relies on parent trait's typeid validation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Trait method addition and its usage across implementations: Verify that the new validate_downcastable_from hook is correctly applied and doesn't introduce unintended behavior.
  • PyUtf8Str downcast logic change: Ensure removal of typeid check is safe since parent downcastable_from() now handles it.
  • PyNativeMethod ctx parameter: Confirm that the ctx mechanism properly resolves the builtin_method_type and that removing the custom PyPayload impl is safe.

Possibly related PRs

Suggested reviewers

  • coolreader18
  • ShaharNaveh

Poem

🐰 A validation hook, oh what a delight,
No typeid checks done twice in the night,
PyUtf8Str trusts and validates right,
PyNativeMethod's context shines bright,
Downcasting now flows with less fright! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 'overridable validate_downcastable_from' directly and specifically describes the main change: introducing an overridable validate_downcastable_from method as a new extension point in PyPayload.
✨ 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.

@youknowone youknowone marked this pull request as ready for review December 10, 2025 13:00
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)
crates/vm/src/object/payload.rs (1)

25-34: Clarify safety docs and contract for validate_downcastable_from

downcastable_from now performs the typeid check itself and then calls validate_downcastable_from. The safety comment (“should only be called if payload_type_id matches the type of obj”) no longer reflects the actual behavior, and override implementations (like PyUtf8Str) rely on the fact that validate_downcastable_from is only invoked after the typeid equality has been verified.

To make this extension point safer for future implementors, I suggest:

  • Update the doc comment on downcastable_from to describe what guarantees it provides (e.g., that it first checks obj.typeid() == Self::payload_type_id()).
  • Add a brief doc comment on validate_downcastable_from stating that, when called via downcastable_from, obj is guaranteed to satisfy the payload_type_id check, and that callers should not invoke it directly without that precondition.

This documents the intended use and justifies unsafe downcasts inside overrides like PyUtf8Str::validate_downcastable_from.

crates/vm/src/builtins/str.rs (1)

1935-1939: Unsafe cast in PyUtf8Str::validate_downcastable_from is sound but deserves a slightly stronger comment

The implementation:

  • Overrides payload_type_id() to return TypeId::of::<PyStr>().
  • Relies on PyPayload::downcastable_from to check obj.typeid() == TypeId::of::<PyStr>() before calling validate_downcastable_from.
  • Then performs unsafe { obj.downcast_unchecked_ref::<PyStr>() } and checks is_utf8().

Given this call pattern, the unsafe cast is valid: when validate_downcastable_from runs, obj’s payload is guaranteed to be a PyStr, and PyUtf8Str is repr(transparent) over PyStr.

To make the invariant clearer for future changes, consider expanding the comment to mention that:

  • validate_downcastable_from is only meant to be called via PyPayload::downcastable_from, and
  • the preceding typeid check, together with the overridden payload_type_id(), is what justifies using downcast_unchecked_ref::<PyStr>() here.

Functionally the change looks correct and nicely reuses the new hook to avoid duplicating the type-id logic.

📜 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 98fff96 and e4d0a58.

📒 Files selected for processing (3)
  • crates/vm/src/builtins/builtin_func.rs (1 hunks)
  • crates/vm/src/builtins/str.rs (1 hunks)
  • crates/vm/src/object/payload.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/vm/src/object/payload.rs
  • crates/vm/src/builtins/builtin_func.rs
  • crates/vm/src/builtins/str.rs
🧬 Code graph analysis (1)
crates/vm/src/builtins/builtin_func.rs (1)
crates/derive-impl/src/util.rs (1)
  • base (416-418)
⏰ 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). (2)
  • GitHub Check: Run snippets and cpython tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython tests (windows-latest)
🔇 Additional comments (1)
crates/vm/src/builtins/builtin_func.rs (1)

151-155: ctx = "builtin_method_type" wiring for PyNativeMethod looks consistent

The added ctx = "builtin_method_type" on PyNativeMethod aligns with init() using context.types.builtin_method_type and removes the need for a separate PyPayload impl to provide class(ctx). This keeps the type wiring in one place and should preserve behavior for comparisons and calls that rely on downcast_ref::<PyNativeMethod>(), assuming the pyclass machinery provides the payload impl as expected.

@youknowone youknowone merged commit 2055145 into RustPython:main Dec 10, 2025
13 checks passed
@youknowone youknowone deleted the downcastable branch December 10, 2025 14:31
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