Skip to content

Commit 2354102

Browse files
committed
Add interactive shell
1 parent 7d20869 commit 2354102

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+87
-29
lines changed

parser/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#[macro_use]
22
extern crate log;
33

4-
mod parser;
4+
pub mod parser;
55
mod python;
66
pub mod ast;
77
mod token;

src/main.rs

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@ mod compile;
1111
use clap::{Arg, App};
1212
use std::path::Path;
1313
use rustpython_parser::parse;
14+
use rustpython_parser::parser::parse_source;
1415
use rustpython_vm::evaluate;
16+
use rustpython_vm::pyobject::PyObjectRef;
17+
use std::io;
18+
use std::io::prelude::*;
1519

1620

1721
fn main() {
@@ -21,18 +25,24 @@ fn main() {
2125
.author(crate_authors!())
2226
.about("Rust implementation of the Python language")
2327
.arg(Arg::with_name("script")
24-
.required(true)
28+
.required(false)
2529
.index(1))
2630
.arg(Arg::with_name("v")
2731
.short("v")
2832
.multiple(true)
2933
.help("Give the verbosity"))
3034
.get_matches();
3135

32-
// Figure out the filename:
33-
let script_file = matches.value_of("script").unwrap_or("foo");
34-
debug!("Running file {}", script_file);
36+
// Figure out if a script was passed:
37+
match matches.value_of("script") {
38+
None => run_shell(),
39+
Some(filename) => run_script(&filename.to_string()),
40+
}
3541

42+
}
43+
44+
fn run_script(script_file: &String) {
45+
debug!("Running file {}", script_file);
3646
// Parse an ast from it:
3747
let filepath = Path::new(script_file);
3848
match parse(filepath) {
@@ -49,3 +59,31 @@ fn main() {
4959
}
5060
}
5161

62+
fn run_shell() {
63+
println!("Welcome to the magnificent Rust Python interpreter");
64+
// Read a single line:
65+
loop {
66+
let mut input = String::new();
67+
print!(">>>");
68+
io::stdout().flush().ok().expect("Could not flush stdout");
69+
io::stdin().read_line(&mut input);
70+
println!("You entered {:?}", input);
71+
let result = eval(&input);
72+
println!("{:?}", result);
73+
}
74+
}
75+
76+
fn eval(source: &String) -> Result<PyObjectRef, PyObjectRef> {
77+
match parse_source(source) {
78+
Ok(program) => {
79+
debug!("Got ast: {:?}", program);
80+
let bytecode = compile::compile(program);
81+
debug!("Code object: {:?}", bytecode);
82+
evaluate(bytecode)
83+
},
84+
Err(msg) => {
85+
panic!("Parsing went horribly wrong: {}", msg);
86+
},
87+
}
88+
}
89+

0 commit comments

Comments
 (0)