Skip to content

Commit 5ebfd55

Browse files
committed
Add extremely minimal dis module.
1 parent 4b03e6d commit 5ebfd55

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

tests/snippets/dismod.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import dis
2+
3+
dis.disassemble(compile("5 + x + 5 or 2", "", "eval"))
4+
print("\n")
5+
dis.disassemble(compile("def f(x):\n return 1", "", "exec"))
6+
print("\n")
7+
dis.disassemble(compile("if a:\n 1 or 2\nelif x == 'hello':\n 3\nelse:\n 4", "", "exec"))
8+
print("\n")
9+
dis.disassemble(compile("f(x=1, y=2)", "", "eval"))
10+
print("\n")

vm/src/stdlib/dis.rs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
use super::super::obj::objcode;
2+
use super::super::obj::objtype;
3+
use super::super::pyobject::{PyContext, PyFuncArgs, PyObjectRef, PyResult, TypeProtocol};
4+
use super::super::vm::VirtualMachine;
5+
6+
fn dis_disassemble(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
7+
arg_check!(vm, args, required = [(co, Some(vm.ctx.code_type()))]);
8+
9+
let code = objcode::get_value(co);
10+
print!("{}", code);
11+
Ok(vm.get_none())
12+
}
13+
14+
pub fn mk_module(ctx: &PyContext) -> PyObjectRef {
15+
let py_mod = ctx.new_module("dis", ctx.new_scope(None));
16+
ctx.set_attr(&py_mod, "disassemble", ctx.new_rustfunc(dis_disassemble));
17+
py_mod
18+
}

vm/src/stdlib/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
mod ast;
2+
mod dis;
23
pub mod io;
34
mod json;
45
mod keyword;
@@ -21,6 +22,7 @@ pub type StdlibInitFunc = fn(&PyContext) -> PyObjectRef;
2122
pub fn get_module_inits() -> HashMap<String, StdlibInitFunc> {
2223
let mut modules = HashMap::new();
2324
modules.insert("ast".to_string(), ast::mk_module as StdlibInitFunc);
25+
modules.insert("dis".to_string(), dis::mk_module as StdlibInitFunc);
2426
modules.insert("io".to_string(), io::mk_module as StdlibInitFunc);
2527
modules.insert("json".to_string(), json::mk_module as StdlibInitFunc);
2628
modules.insert("keyword".to_string(), keyword::mk_module as StdlibInitFunc);

0 commit comments

Comments
 (0)