Remove unused rust impl for formatting dis output#7660
Remove unused rust impl for formatting dis output#7660ShaharNaveh wants to merge 11 commits intoRustPython:mainfrom
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughRemove disassembly/display formatting and the Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
@youknowone seems that the places where we are using our implementation of
What do you think will be the best approach with solving this? |
|
lets remove them if obsolete |
🎉 |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
crates/compiler-core/src/bytecode/instruction.rs (1)
1371-1397:⚠️ Potential issue | 🔴 Critical
frame.rsstill calls the now-removedInstructionMetadata::displaymethod — this will fail to compile.The trait definition at lines 1371–1397 no longer includes the
displaymethod, butcrates/vm/src/frame.rshas two call sites:
- Line 2101:
instruction.display(arg, &self.code.code).to_string()in theflame_guard!macro- Line 2115:
instruction.display(arg, &self.code.code)in the feature-gated trace outputBoth must be updated (e.g., to
{:?}formatting likeir.rs) before this change can compile.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/compiler-core/src/bytecode/instruction.rs` around lines 1371 - 1397, InstructionMetadata no longer provides display, so update the two call sites in frame.rs that call instruction.display(arg, &self.code.code): inside the flame_guard! usage (previously instruction.display(...).to_string()) and in the feature-gated trace output (previously instruction.display(...)). Replace those calls with Debug-style formatting (e.g. format!("{:?}", instruction) or using the Debug formatter) so they compile against the current InstructionMetadata trait; ensure the flame_guard! site produces a String (format! already does) and the trace output uses the formatted Debug value.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Outside diff comments:
In `@crates/compiler-core/src/bytecode/instruction.rs`:
- Around line 1371-1397: InstructionMetadata no longer provides display, so
update the two call sites in frame.rs that call instruction.display(arg,
&self.code.code): inside the flame_guard! usage (previously
instruction.display(...).to_string()) and in the feature-gated trace output
(previously instruction.display(...)). Replace those calls with Debug-style
formatting (e.g. format!("{:?}", instruction) or using the Debug formatter) so
they compile against the current InstructionMetadata trait; ensure the
flame_guard! site produces a String (format! already does) and the trace output
uses the formatted Debug value.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: ab1a606d-72fe-43ac-97bf-03acadd96dc4
⛔ Files ignored due to path filters (12)
Cargo.lockis excluded by!**/*.lockcrates/codegen/src/snapshots/rustpython_codegen__compile__tests__bare_function_annotations_check_attribute_and_subscript_expressions.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_codegen__compile__tests__const_bool_not_op.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_codegen__compile__tests__constant_true_if_pass_keeps_line_anchor_nop.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_codegen__compile__tests__if_ands.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_codegen__compile__tests__if_mixed.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_codegen__compile__tests__if_ors.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_codegen__compile__tests__nested_bool_op.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_codegen__compile__tests__nested_double_async_with.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_compiler_core__compile__tests__if_ands.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_compiler_core__compile__tests__if_mixed.snapis excluded by!**/*.snapcrates/codegen/src/snapshots/rustpython_compiler_core__compile__tests__if_ors.snapis excluded by!**/*.snap
📒 Files selected for processing (8)
Cargo.tomlcrates/codegen/Cargo.tomlcrates/codegen/src/compile.rscrates/codegen/src/ir.rscrates/compiler-core/src/bytecode.rscrates/compiler-core/src/bytecode/instruction.rscrates/vm/src/builtins/code.rsexamples/dis.rs
💤 Files with no reviewable changes (6)
- crates/codegen/Cargo.toml
- crates/vm/src/builtins/code.rs
- Cargo.toml
- examples/dis.rs
- crates/compiler-core/src/bytecode.rs
- crates/codegen/src/compile.rs
| fn test_if_ors() { | ||
| assert_dis_snapshot!(compile_exec( | ||
| "\ | ||
| if True or False or False: | ||
| pass |
There was a problem hiding this comment.
oh.. are these test going to be entirely deleted? This is not desired. Can we replace the snapshot test to other way not depending on internal dis?
There was a problem hiding this comment.
The only way I can think of is to move them under crates/vm or crates/stdlib, then parsing the source code into a PyCode, then run it like:
let module = vm.import("dis", 0)?;
let dis = module.get_attr("dis", vm)?;
let res = dis.call(my_pycode, vm)?;
// <convert res to String and pass to Insta>There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
crates/stdlib/src/_opcode.rs (3)
309-331: Drop the unusedResult<(), ()>return type.The
?on Line 324 operates inside theinterp.enterclosure (which returnsPyResult<String>), and anyErris already converted to a panic by.unwrap()on Line 326. The outer function always returnsOk(()), soResult<(), ()>and the finalOk(())are dead surface area.Proposed simplification
- fn dis_output(source: &str) -> Result<(), ()> { + fn dis_output(source: &str) { let builder = vm::Interpreter::builder(Default::default()); let stdlib_defs = crate::stdlib_module_defs(&builder.ctx); let interp = builder.add_native_modules(&stdlib_defs).build(); let output = interp .enter(|vm| { let pycode = vm - .compile(&source, Mode::Exec, "?".into()) - .map_err(|err| vm.new_syntax_error(&err, Some(&source))) + .compile(source, Mode::Exec, "?".into()) + .map_err(|err| vm.new_syntax_error(&err, Some(source))) .unwrap(); let dis_module = vm.import("dis", 0).unwrap(); let dis = dis_module.get_attr("dis", vm).unwrap(); dis.call((pycode,), vm)?.try_into_value::<String>(vm) }) .unwrap(); insta::assert_snapshot!(insta::internals::AutoName, output, source); - - Ok(()) }(Also drops the unnecessary
&sourcereborrow sincesourceis already&str.)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/stdlib/src/_opcode.rs` around lines 309 - 331, The function dis_output currently returns Result<(), ()> with a final Ok(()) and reborrows source; simplify it by changing the signature of dis_output to return () (unit), remove the final Ok(()) return, and stop reborrowing source when calling vm.compile (use source instead of &source); keep the existing interp.enter closure and its internal error handling as-is (the closure still returns PyResult<String> and unwraps).
310-312: Avoid rebuilding a freshInterpreterper test case.The
dis_outputfunction has 8#[test_case]invocations, each spinning up a newInterpreter, initializing the stdlib, and re-importingdis. This multiplies test runtime and can noticeably slowcargo test. Consider sharing an interpreter across cases viaOnceLock/LazyLock:Sketch
use std::sync::OnceLock; fn shared_interp() -> &'static vm::Interpreter { static INTERP: OnceLock<vm::Interpreter> = OnceLock::new(); INTERP.get_or_init(|| { let builder = vm::Interpreter::builder(Default::default()); let stdlib_defs = crate::stdlib_module_defs(&builder.ctx); builder.add_native_modules(&stdlib_defs).build() }) }Then call
shared_interp().enter(|vm| { … })fromdis_output. SinceVirtualMachinecontainsRefCellandUnsafeCell, verify thread-safety for parallel test execution; if notSync, either useserial_testor pin tests to single-threaded execution.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/stdlib/src/_opcode.rs` around lines 310 - 312, The tests rebuild an Interpreter for every dis_output #[test_case], slowing test runs; create and reuse a shared static interpreter (e.g., a shared_interp function backed by std::sync::OnceLock or LazyLock that initializes vm::Interpreter via vm::Interpreter::builder and crate::stdlib_module_defs once) and call shared_interp().enter(|vm| { … }) inside dis_output instead of rebuilding; verify whether the VM/VirtualMachine types are Sync/Send—if not, either run those tests serially (use serial_test or #[test] with single-threaded execution) or restrict the static to single-threaded use to avoid data races.
328-328: Remove unstableinsta::internals::AutoNameand use simplified public API.The
internalsmodule is not part ofinsta's stable surface. Withtest_casedescriptions driving the snapshot filename suffix, auto-naming works correctly using the simplified syntax:- insta::assert_snapshot!(insta::internals::AutoName, output, source); + insta::assert_snapshot!(output, source);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/stdlib/src/_opcode.rs` at line 328, Replace the unstable internals usage in the snapshot assertion: remove the first argument `insta::internals::AutoName` from the `insta::assert_snapshot!` invocation so it uses the public simplified API (i.e., call `insta::assert_snapshot!(output, source)`), leaving the auto-naming behavior driven by the test_case description intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@crates/stdlib/src/_opcode.rs`:
- Around line 314-326: The disassembly capture currently assumes dis.dis()
returns a string and panics when it returns None; update the dis_output function
so inside interp.enter (the closure passed to interp.enter) you compile the
source as before, create an io.StringIO via vm.import("io") and
io.get_attr("StringIO"), replace sys.stdout by setting sys.stdout to that
StringIO (save the previous stdout), call dis = dis_module.get_attr("dis") and
invoke dis.call((pycode,), vm) checking the call result, restore sys.stdout to
the saved value, then read the captured text via
string_io.call_method("getvalue", (), vm)?.try_into_value::<String>(vm) and
return that String (propagate errors with ?); also simplify the dis_output
signature to fn dis_output(source: &str) -> String (or -> PyResult<String>
inside enter) instead of Result<(), ()>, and remove reliance on
insta::internals::AutoName by switching to the public insta naming API.
---
Nitpick comments:
In `@crates/stdlib/src/_opcode.rs`:
- Around line 309-331: The function dis_output currently returns Result<(), ()>
with a final Ok(()) and reborrows source; simplify it by changing the signature
of dis_output to return () (unit), remove the final Ok(()) return, and stop
reborrowing source when calling vm.compile (use source instead of &source); keep
the existing interp.enter closure and its internal error handling as-is (the
closure still returns PyResult<String> and unwraps).
- Around line 310-312: The tests rebuild an Interpreter for every dis_output
#[test_case], slowing test runs; create and reuse a shared static interpreter
(e.g., a shared_interp function backed by std::sync::OnceLock or LazyLock that
initializes vm::Interpreter via vm::Interpreter::builder and
crate::stdlib_module_defs once) and call shared_interp().enter(|vm| { … })
inside dis_output instead of rebuilding; verify whether the VM/VirtualMachine
types are Sync/Send—if not, either run those tests serially (use serial_test or
#[test] with single-threaded execution) or restrict the static to
single-threaded use to avoid data races.
- Line 328: Replace the unstable internals usage in the snapshot assertion:
remove the first argument `insta::internals::AutoName` from the
`insta::assert_snapshot!` invocation so it uses the public simplified API (i.e.,
call `insta::assert_snapshot!(output, source)`), leaving the auto-naming
behavior driven by the test_case description intact.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 5a7fe94b-c04e-4c9e-abc7-7361c0809423
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (3)
Cargo.tomlcrates/stdlib/Cargo.tomlcrates/stdlib/src/_opcode.rs
🚧 Files skipped from review as they are similar to previous changes (1)
- Cargo.toml
There was a problem hiding this comment.
♻️ Duplicate comments (1)
crates/stdlib/src/_opcode.rs (1)
314-328:⚠️ Potential issue | 🔴 CriticalRuntime panic:
dis.dis()returnsNone, not a string — all test cases will fail.
dis.dis(code)(like CPython) prints to stdout and returnsNone. Thetry_into_value::<String>(vm)on Line 324 will therefore error, and the subsequent.unwrap()on Line 326 will panic for every parametrized case.To capture the disassembly, redirect
sys.stdoutto anio.StringIObefore the call and readgetvalue()afterwards, or invoke a helper that returns a string (e.g., build the output viadis.Bytecode(code).dis()or similar).Additionally,
insta::internals::AutoNameon Line 328 is a non-public API; prefer the public naming surface (e.g., passing the name explicitly or usingassert_snapshot!without an explicit name so insta derives it from the function/test-case).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@crates/stdlib/src/_opcode.rs` around lines 314 - 328, The test currently assumes dis.dis(code) returns a string and calls try_into_value::<String>(vm), which panics because dis.dis prints to stdout and returns None; modify the closure passed to interp.enter to capture the disassembly by redirecting sys.stdout to an io.StringIO (or call a helper like dis.Bytecode(code).dis() that returns a string), then read string_io.getvalue() and return that String instead of trying to convert None; also replace the non-public insta::internals::AutoName usage in the insta::assert_snapshot! invocation with the public API (omit the explicit internal name so insta derives it or pass an explicit name) so snapshots use supported naming.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@crates/stdlib/src/_opcode.rs`:
- Around line 314-328: The test currently assumes dis.dis(code) returns a string
and calls try_into_value::<String>(vm), which panics because dis.dis prints to
stdout and returns None; modify the closure passed to interp.enter to capture
the disassembly by redirecting sys.stdout to an io.StringIO (or call a helper
like dis.Bytecode(code).dis() that returns a string), then read
string_io.getvalue() and return that String instead of trying to convert None;
also replace the non-public insta::internals::AutoName usage in the
insta::assert_snapshot! invocation with the public API (omit the explicit
internal name so insta derives it or pass an explicit name) so snapshots use
supported naming.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: fd1a3b81-c62f-4a02-83dc-cf3537731258
📒 Files selected for processing (1)
crates/stdlib/src/_opcode.rs
There was a problem hiding this comment.
It seems like no matter what I do I can't import "dis". I'd appreciate some help on this.
@fanninpm @youknowone
3c8ae37 to
a207364
Compare
98222d9 to
dabe459
Compare

This was used back when we had a hacky
_dismodule (that was removed at #6690).I guess we kept maintaining the
fmt_dismethod as it was still technicaly used as we would implementDisplayfor PyCode, but since we no longer actually use it anywhere it's dead code.Displayof PyCode was called here:RustPython/crates/stdlib/src/dis.rs
Lines 39 to 43 in 9e225f5
Close #7433
Summary by CodeRabbit
Removed Features
Tests
Chores