@@ -2,14 +2,24 @@ pub(crate) use decl::make_module;
2
2
3
3
#[ pymodule( name = "dis" ) ]
4
4
mod decl {
5
- use crate :: vm :: {
5
+ use rustpython_vm :: {
6
6
PyObjectRef , PyRef , PyResult , TryFromObject , VirtualMachine ,
7
7
builtins:: { PyCode , PyDictRef , PyStrRef } ,
8
8
bytecode:: CodeFlags ,
9
+ function:: OptionalArg ,
9
10
} ;
10
11
12
+ #[ derive( FromArgs ) ]
13
+ struct DisArgs {
14
+ #[ pyarg( positional) ]
15
+ obj : PyObjectRef ,
16
+ #[ pyarg( any, optional) ]
17
+ file : OptionalArg < PyObjectRef > ,
18
+ }
19
+
11
20
#[ pyfunction]
12
- fn dis ( obj : PyObjectRef , vm : & VirtualMachine ) -> PyResult < ( ) > {
21
+ fn dis ( args : DisArgs , vm : & VirtualMachine ) -> PyResult < ( ) > {
22
+ let DisArgs { obj, file } = args;
13
23
let co = if let Ok ( co) = obj. get_attr ( "__code__" , vm) {
14
24
// Method or function:
15
25
PyRef :: try_from_object ( vm, co) ?
@@ -33,12 +43,41 @@ mod decl {
33
43
} else {
34
44
PyRef :: try_from_object ( vm, obj) ?
35
45
} ;
36
- disassemble ( co)
46
+ disassemble_to_file ( co, file . into_option ( ) , vm )
37
47
}
38
48
39
49
#[ 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
+ }
42
81
Ok ( ( ) )
43
82
}
44
83
0 commit comments