rhai/examples/repl.rs

67 lines
1.6 KiB
Rust
Raw Normal View History

use rhai::{Engine, EvalAltResult, Scope};
use std::{
io::{stdin, stdout, Write},
iter,
};
2017-10-15 17:50:39 +02:00
fn print_error(input: &str, err: EvalAltResult) {
fn padding(pad: &str, len: usize) -> String {
iter::repeat(pad).take(len).collect::<String>()
}
let lines: Vec<_> = input.split("\n").collect();
// Print error
match err.position() {
p if p.is_eof() => {
// EOF
let last = lines[lines.len() - 2];
println!("{}", last);
println!("{}^ {}", padding(" ", last.len() - 1), err);
}
p if p.is_none() => {
// No position
println!("{}", err);
}
p => {
// Specific position
let pos_text = format!(
" (line {}, position {})",
p.line().unwrap(),
p.position().unwrap()
);
println!("{}", lines[p.line().unwrap() - 1]);
println!(
"{}^ {}",
padding(" ", p.position().unwrap() - 1),
err.to_string().replace(&pos_text, "")
);
}
}
}
fn main() {
2017-12-20 12:16:14 +01:00
let mut engine = Engine::new();
let mut scope = Scope::new();
2017-10-15 17:50:39 +02:00
let mut input = String::new();
2017-10-15 17:50:39 +02:00
2017-12-20 12:16:14 +01:00
loop {
print!("rhai> ");
2017-12-20 12:16:14 +01:00
stdout().flush().expect("couldn't flush stdout");
2020-03-02 08:19:59 +01:00
input.clear();
if let Err(err) = stdin().read_line(&mut input) {
println!("input error: {}", err);
2017-12-20 12:16:14 +01:00
}
2017-10-15 17:50:39 +02:00
if let Err(err) = engine.consume_with_scope(&mut scope, true, &input) {
println!("");
print_error(&input, err);
println!("");
2017-12-20 12:16:14 +01:00
}
}
2017-10-15 17:50:39 +02:00
}