Skip to content

Conversation

@youknowone
Copy link
Member

@youknowone youknowone commented Jul 29, 2024

Summary by CodeRabbit

  • Refactor
    • Improved singleton value conversion and error reporting for invalid inputs.
    • Expanded and unified handling of class-pattern components so pattern arguments and keyword attributes/patterns fully round-trip to/from AST representations.
    • Standardized serialization/deserialization signatures across related AST structures for more consistent behavior.

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

@youknowone youknowone changed the title Update inspect from CPython 3.12 Update dataclasses, inspect from CPython 3.12 Jul 29, 2024
@youknowone youknowone force-pushed the inspect branch 3 times, most recently from faed11a to a3579b3 Compare July 29, 2024 23:47
@youknowone youknowone force-pushed the inspect branch 3 times, most recently from 4937811 to b1235fe Compare March 30, 2025 05:51
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 12, 2025

Walkthrough

Extended AST pattern conversions: added full bidirectional mapping for ruff::Singleton (None/True/False) and converted several PatternMatchClass-related types into vector wrappers, updated split/merge utilities and Node impls to use the new wrappers and revised function signatures.

Changes

Cohort / File(s) Summary
Singleton Conversion
crates/vm/src/stdlib/ast/pattern.rs
Implemented ast_to_object mapping for ruff::Singleton → VM objects (none, true, false) and ast_from_object recognizing VM objects and returning Singleton variants; adjusted parameter names/signatures.
PatternMatchClass wrapper types
crates/vm/src/stdlib/ast/pattern.rs
Replaced three placeholder structs with wrappers: PatternMatchClassPatterns(Vec<ruff::Pattern>), PatternMatchClassKeywordAttributes(Vec<ruff::Identifier>), PatternMatchClassKeywordPatterns(Vec<ruff::Pattern>). Each now delegates ast_to_object/ast_from_object to the inner vectors.
split/merge utilities & Node routing
crates/vm/src/stdlib/ast/pattern.rs
split_pattern_match_class now returns the new wrapper types built from ruff::PatternArguments. merge_pattern_match_class accepts the wrappers and returns (Vec<ruff::Pattern>, Vec<ruff::PatternKeyword>) by zipping attributes and patterns. Node implementations updated to route through new wrappers; several function signatures adjusted to (vm: &VirtualMachine, source_file: &SourceFile, object: PyObjectRef) style.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Pay attention to correctness of conversions between wrappers and inner vectors (edge cases: empty lists, mismatched lengths).
  • Validate merge_pattern_match_class zipping logic produces correct PatternKeyword ordering and error handling.
  • Confirm all ast_to_object / ast_from_object signature changes match trait expectations and are used consistently across Node impls.
  • Review tests or add ones for round-tripping class-pattern structures and singleton conversions.

Poem

🐇 I nibbled bytes beneath moonlight’s beam,
Turned None to none and True to gleam.
Patterns gathered, wrapped in a row,
Split, merged, hopped — now round-trips flow.
Code carrots crunch; the AST sings “go!” 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title 'Update dataclasses, inspect from CPython 3.13' does not match the actual changes shown in the summary, which focus entirely on AST pattern matching class handling in the Rust VM, not dataclasses or inspect module updates. Revise the title to accurately reflect the primary change, such as 'Implement AST pattern-match class conversion for None/True/False singletons' or 'Add roundtrip AST conversion for class pattern components'.
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ 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 changed the title Update dataclasses, inspect from CPython 3.12 Update dataclasses, inspect from CPython 3.13 Dec 12, 2025
@youknowone youknowone force-pushed the inspect branch 2 times, most recently from d4d8bda to b6dfa84 Compare December 12, 2025 12:01
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)
crates/vm/src/stdlib/ast/pattern.rs (1)

210-227: Correct object-to-singleton conversion with minor formatting nit.

The identity checks and error handling are appropriate. The conversion logic correctly distinguishes between the three singleton values.

Consider using display format {} instead of debug format {:?} in the error message for cleaner output:

         } else {
             Err(vm.new_value_error(format!(
-                "Expected None, True, or False, got {:?}",
+                "Expected None, True, or False, got {}",
                 object.class().name()
             )))
         }
📜 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 75dcf80 and b6dfa84.

⛔ Files ignored due to path filters (26)
  • Lib/dataclasses.py is excluded by !Lib/**
  • Lib/dis.py is excluded by !Lib/**
  • Lib/inspect.py is excluded by !Lib/**
  • Lib/test/__init__.py is excluded by !Lib/**
  • Lib/test/test__opcode.py is excluded by !Lib/**
  • Lib/test/test_abc.py is excluded by !Lib/**
  • Lib/test/test_compile.py is excluded by !Lib/**
  • Lib/test/test_copy.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/__init__.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_module_1.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_module_1_str.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_module_2.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_module_2_str.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_textanno.py is excluded by !Lib/**
  • Lib/test/test_enum.py is excluded by !Lib/**
  • Lib/test/test_fstring.py is excluded by !Lib/**
  • Lib/test/test_inspect/__init__.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_fodder.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_fodder2.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_stock_annotations.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_stringized_annotations.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_stringized_annotations_2.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_stringized_annotations_pep695.py is excluded by !Lib/**
  • Lib/test/test_inspect/test_inspect.py is excluded by !Lib/**
  • Lib/test/test_unittest/testmock/testhelpers.py is excluded by !Lib/**
  • Lib/test/test_warnings/__init__.py is excluded by !Lib/**
📒 Files selected for processing (1)
  • crates/vm/src/stdlib/ast/pattern.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/stdlib/ast/pattern.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). (10)
  • 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 (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run rust tests (windows-latest)
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Check Rust code with clippy
  • GitHub Check: Ensure compilation on various targets
  • GitHub Check: Run snippets and cpython tests on wasm-wasi
🔇 Additional comments (1)
crates/vm/src/stdlib/ast/pattern.rs (1)

202-208: LGTM! Clean singleton-to-object conversion.

The exhaustive pattern match correctly maps each Singleton variant to its corresponding VM object representation.

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: 1

🧹 Nitpick comments (1)
crates/vm/src/stdlib/ast/pattern.rs (1)

543-558: Avoid cloning kwd_attrs (optional)

split_pattern_match_class currently clones attr because it later consumes arguments.keywords. You can split attrs/patterns in a single consuming loop to avoid clones.

📜 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 b6dfa84 and 9bbfdf5.

⛔ Files ignored due to path filters (25)
  • Lib/dataclasses.py is excluded by !Lib/**
  • Lib/dis.py is excluded by !Lib/**
  • Lib/inspect.py is excluded by !Lib/**
  • Lib/test/test__opcode.py is excluded by !Lib/**
  • Lib/test/test_abc.py is excluded by !Lib/**
  • Lib/test/test_compile.py is excluded by !Lib/**
  • Lib/test/test_copy.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/__init__.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_module_1.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_module_1_str.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_module_2.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_module_2_str.py is excluded by !Lib/**
  • Lib/test/test_dataclasses/dataclass_textanno.py is excluded by !Lib/**
  • Lib/test/test_enum.py is excluded by !Lib/**
  • Lib/test/test_fstring.py is excluded by !Lib/**
  • Lib/test/test_inspect/__init__.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_fodder.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_fodder2.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_stock_annotations.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_stringized_annotations.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_stringized_annotations_2.py is excluded by !Lib/**
  • Lib/test/test_inspect/inspect_stringized_annotations_pep695.py is excluded by !Lib/**
  • Lib/test/test_inspect/test_inspect.py is excluded by !Lib/**
  • Lib/test/test_unittest/testmock/testhelpers.py is excluded by !Lib/**
  • Lib/test/test_warnings/__init__.py is excluded by !Lib/**
📒 Files selected for processing (1)
  • crates/vm/src/stdlib/ast/pattern.rs (3 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/stdlib/ast/pattern.rs
🧬 Code graph analysis (1)
crates/vm/src/stdlib/ast/pattern.rs (5)
crates/vm/src/stdlib/itertools.rs (1)
  • None (1152-1152)
crates/vm/src/stdlib/ast/other.rs (1)
  • object (39-39)
crates/vm/src/builtins/genericalias.rs (1)
  • arguments (66-66)
crates/vm/src/frame.rs (1)
  • kwd_attrs (1122-1122)
crates/vm/src/stdlib/functools.rs (1)
  • keywords (72-74)
⏰ 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). (8)
  • GitHub Check: Run rust tests (macos-latest)
  • GitHub Check: Run rust tests (ubuntu-latest)
  • GitHub Check: Run snippets and cpython 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 on wasm-wasi
  • GitHub Check: Check the WASM package and demo
  • GitHub Check: Ensure compilation on various targets
🔇 Additional comments (1)
crates/vm/src/stdlib/ast/pattern.rs (1)

390-435: Wrapper types look fine; delegation is clean

The tuple-struct wrappers + Node delegation keep the PatternMatchClass conversion code simpler and should round-trip as long as Vec<T>: Node and ruff::Identifier: Node behave as expected.

Comment on lines 560 to 578
/// Merges the pattern match class attributes and patterns, opposite of [`split_pattern_match_class`].
fn merge_pattern_match_class(
_patterns: PatternMatchClassPatterns,
_kwd_attrs: PatternMatchClassKeywordAttributes,
_kwd_patterns: PatternMatchClassKeywordPatterns,
patterns: PatternMatchClassPatterns,
kwd_attrs: PatternMatchClassKeywordAttributes,
kwd_patterns: PatternMatchClassKeywordPatterns,
) -> (Vec<ruff::Pattern>, Vec<ruff::PatternKeyword>) {
todo!()
let keywords = kwd_attrs
.0
.into_iter()
.zip(kwd_patterns.0)
.map(|(attr, pattern)| ruff::PatternKeyword {
range: Default::default(),
node_index: Default::default(),
attr,
pattern,
})
.collect();
(patterns.0, keywords)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Don’t silently truncate mismatched kwd_attrs / kwd_patterns lengths

zip will drop extras if lengths differ. Since ast_from_object accepts user-constructed AST objects, this should error instead of losing data.

Low-impact fix: validate in ruff::PatternMatchClass::ast_from_object (where vm is available) before calling merge_pattern_match_class:

 let kwd_attrs = Node::ast_from_object(
     vm, source_file, get_node_field(vm, &object, "kwd_attrs", "MatchClass")?
 )?;
 let kwd_patterns = Node::ast_from_object(
     vm, source_file, get_node_field(vm, &object, "kwd_patterns", "MatchClass")?
 )?;
+
+if kwd_attrs.0.len() != kwd_patterns.0.len() {
+    return Err(vm.new_value_error(format!(
+        "MatchClass kwd_attrs and kwd_patterns must have the same length ({} != {})",
+        kwd_attrs.0.len(),
+        kwd_patterns.0.len(),
+    )));
+}
 let (patterns, keywords) = merge_pattern_match_class(patterns, kwd_attrs, kwd_patterns);

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In crates/vm/src/stdlib/ast/pattern.rs around lines 560 to 578, the current
merge_pattern_match_class uses zip and silently drops extra entries when
kwd_attrs and kwd_patterns lengths differ; instead, validate that
kwd_attrs.0.len() == kwd_patterns.0.len() before merging (preferably in
ruff::PatternMatchClass::ast_from_object where the VM is available) and
return/raise a TypeError (or appropriate VM error) if they differ with a clear
message indicating mismatched keyword attributes and patterns lengths; only
after validation, construct PatternKeyword entries and return the merged
vectors.

@youknowone youknowone merged commit 093ba25 into RustPython:main Dec 12, 2025
13 checks passed
@youknowone youknowone deleted the inspect branch December 12, 2025 13:44
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