forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdis.rs
More file actions
90 lines (80 loc) · 2.65 KB
/
dis.rs
File metadata and controls
90 lines (80 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//! This an example usage of the rustpython_compiler crate.
//! This program reads, parses, and compiles a file you provide
//! to RustPython bytecode, and then displays the output in the
//! `dis.dis` format.
//!
//! example usage:
//! $ cargo run --release --example dis demo*.py
#[macro_use]
extern crate log;
use core::error::Error;
use lexopt::ValueExt;
use rustpython_compiler as compiler;
use std::fs;
use std::path::{Path, PathBuf};
fn main() -> Result<(), lexopt::Error> {
env_logger::init();
let mut scripts = vec![];
let mut mode = compiler::Mode::Exec;
let mut expand_code_objects = true;
let mut optimize = 0;
let mut parser = lexopt::Parser::from_env();
while let Some(arg) = parser.next()? {
use lexopt::Arg::*;
match arg {
Long("help") | Short('h') => {
let bin_name = parser.bin_name().unwrap_or("dis");
println!(
"usage: {bin_name} <scripts...> [-m,--mode=exec|single|eval] [-x,--no-expand] [-O]"
);
println!(
"Compiles and disassembles python script files for viewing their bytecode."
);
return Ok(());
}
Value(x) => scripts.push(PathBuf::from(x)),
Long("mode") | Short('m') => {
mode = parser
.value()?
.parse_with(|s| s.parse::<compiler::Mode>().map_err(|e| e.to_string()))?
}
Long("no-expand") | Short('x') => expand_code_objects = false,
Short('O') => optimize += 1,
_ => return Err(arg.unexpected()),
}
}
if scripts.is_empty() {
return Err("expected at least one argument".into());
}
let opts = compiler::CompileOpts {
optimize,
debug_ranges: true,
};
for script in &scripts {
if script.exists() && script.is_file() {
let res = display_script(script, mode, opts, expand_code_objects);
if let Err(e) = res {
error!("Error while compiling {script:?}: {e}");
}
} else {
eprintln!("{script:?} is not a file.");
}
}
Ok(())
}
fn display_script(
path: &Path,
mode: compiler::Mode,
opts: compiler::CompileOpts,
expand_code_objects: bool,
) -> Result<(), Box<dyn Error>> {
let source = fs::read_to_string(path)?;
let code = compiler::compile(&source, mode, &path.to_string_lossy(), opts)?;
println!("{}:", path.display());
if expand_code_objects {
println!("{}", code.display_expand_code_objects());
} else {
println!("{code}");
}
Ok(())
}