Skip to content

Commit 7d724bb

Browse files
committed
Allow dis.dis to take file
1 parent 93eacda commit 7d724bb

File tree

1 file changed

+44
-5
lines changed

1 file changed

+44
-5
lines changed

stdlib/src/dis.rs

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,24 @@ pub(crate) use decl::make_module;
22

33
#[pymodule(name = "dis")]
44
mod decl {
5-
use crate::vm::{
5+
use rustpython_vm::{
66
PyObjectRef, PyRef, PyResult, TryFromObject, VirtualMachine,
77
builtins::{PyCode, PyDictRef, PyStrRef},
88
bytecode::CodeFlags,
9+
function::OptionalArg,
910
};
1011

12+
#[derive(FromArgs)]
13+
struct DisArgs {
14+
#[pyarg(positional)]
15+
obj: PyObjectRef,
16+
#[pyarg(any, optional)]
17+
file: OptionalArg<PyObjectRef>,
18+
}
19+
1120
#[pyfunction]
12-
fn dis(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
21+
fn dis(args: DisArgs, vm: &VirtualMachine) -> PyResult<()> {
22+
let DisArgs { obj, file } = args;
1323
let co = if let Ok(co) = obj.get_attr("__code__", vm) {
1424
// Method or function:
1525
PyRef::try_from_object(vm, co)?
@@ -33,12 +43,41 @@ mod decl {
3343
} else {
3444
PyRef::try_from_object(vm, obj)?
3545
};
36-
disassemble(co)
46+
disassemble_to_file(co, file.into_option(), vm)
3747
}
3848

3949
#[pyfunction]
40-
fn disassemble(co: PyRef<PyCode>) -> PyResult<()> {
41-
print!("{}", &co.code);
50+
fn disassemble(
51+
co: PyRef<PyCode>,
52+
file: OptionalArg<PyObjectRef>,
53+
vm: &VirtualMachine,
54+
) -> PyResult<()> {
55+
disassemble_to_file(co, file.into_option(), vm)
56+
}
57+
58+
fn disassemble_to_file(
59+
co: PyRef<PyCode>,
60+
file: Option<PyObjectRef>,
61+
vm: &VirtualMachine,
62+
) -> PyResult<()> {
63+
let output = format!("{}", &co.code);
64+
65+
match file {
66+
Some(file_obj) => {
67+
// Write to the provided file object
68+
if let Ok(write_method) = file_obj.get_attr("write", vm) {
69+
write_method.call((output,), vm)?;
70+
} else {
71+
return Err(
72+
vm.new_type_error("file argument must have a write method".to_owned())
73+
);
74+
}
75+
}
76+
None => {
77+
// Write to stdout
78+
print!("{output}");
79+
}
80+
}
4281
Ok(())
4382
}
4483

0 commit comments

Comments
 (0)