-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.rs
89 lines (68 loc) · 2.11 KB
/
main.rs
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
extern crate yuk;
extern crate libc;
extern crate term;
use std::{io, env, fs};
use std::io::Write;
use yuk::parser;
use yuk::runtime::Yuk;
fn is_interactive() -> bool {
(unsafe { libc::isatty(libc::STDIN_FILENO as i32) }) != 0
}
fn start_repl() {
let mut yuk = Yuk::create_stdlib();
loop {
print!(">>> ");
io::stdout().flush().unwrap();
let source = {
let mut source = String::new();
io::stdin().read_line(&mut source).unwrap();
while !parser::is_complete(&source) {
print!("... ");
io::stdout().flush().unwrap();
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
source = source + &line;
}
source
};
match yuk.eval(&source) {
Ok(result) => {
let mut t = term::stdout().unwrap();
t.fg(term::color::BRIGHT_BLUE).unwrap();
writeln!(t, "{}", result.debug_string()).unwrap();
t.reset().unwrap();
},
Err(e) => {
let mut t = term::stderr().unwrap();
t.fg(term::color::BRIGHT_RED).unwrap();
writeln!(t, "{}", e.debug_string()).unwrap();
t.reset().unwrap();
}
}
}
}
fn run_script<T: io::Read>(mut file: T) -> bool {
let source = {
let mut s = String::new();
file.read_to_string(&mut s).ok().expect("Could not read file");
s
};
let result = Yuk::create_stdlib().eval(&source);
if let &Err(ref e) = &result {
let mut t = term::stderr().unwrap();
t.fg(term::color::BRIGHT_RED).unwrap();
writeln!(t, "{}", e.debug_string()).unwrap();
t.reset().unwrap();
}
result.is_ok()
}
fn main() {
if let Some(filename) = env::args().nth(1) {
let file = fs::File::open(&filename).ok().expect(&format!("Could not open {}", filename));
run_script(file);
} else if is_interactive() {
start_repl();
} else {
run_script(io::stdin());
}
}