rhai/src/bin/rhai-run.rs

107 lines
2.8 KiB
Rust
Raw Normal View History

use rhai::{Engine, EvalAltResult, Position};
2020-03-16 05:41:19 +01:00
#[cfg(not(feature = "no_optimize"))]
use rhai::OptimizationLevel;
2020-03-16 05:41:19 +01:00
use std::{env, fs::File, io::Read, path::Path, process::exit};
2016-02-29 22:43:45 +01:00
2021-01-08 07:29:57 +01:00
fn eprint_error(input: &str, mut err: EvalAltResult) {
fn eprint_line(lines: &[&str], pos: Position, err_msg: &str) {
let line = pos.line().unwrap();
let line_no = format!("{}: ", line);
eprintln!("{}{}", line_no, lines[line - 1]);
eprintln!(
2020-04-02 16:37:35 +02:00
"{:>1$} {2}",
"^",
line_no.len() + pos.position().unwrap(),
2021-01-08 07:29:57 +01:00
err_msg
);
eprintln!("");
}
2020-03-24 10:30:04 +01:00
let lines: Vec<_> = input.split('\n').collect();
// Print error
2021-02-28 07:38:34 +01:00
let pos = err.take_position();
2020-03-25 04:51:13 +01:00
if pos.is_none() {
// No position
eprintln!("{}", err);
} else {
// Specific position
eprint_line(&lines, pos, &err.to_string())
}
}
2016-02-29 22:43:45 +01:00
fn main() {
2020-12-29 15:04:31 +01:00
let mut contents = String::new();
for filename in env::args().skip(1) {
let filename = match Path::new(&filename).canonicalize() {
Err(err) => {
eprintln!("Error script file path: {}\n{}", filename, err);
exit(1);
}
Ok(f) => match f.strip_prefix(std::env::current_dir().unwrap().canonicalize().unwrap())
{
Ok(f) => f.into(),
_ => f,
},
};
let mut engine = Engine::new();
2016-03-02 03:36:46 +01:00
#[cfg(not(feature = "no_optimize"))]
engine.set_optimization_level(OptimizationLevel::Full);
let mut f = match File::open(&filename) {
Err(err) => {
eprintln!(
"Error reading script file: {}\n{}",
filename.to_string_lossy(),
err
);
exit(1);
}
Ok(f) => f,
};
2020-12-29 15:04:31 +01:00
contents.clear();
2020-03-24 10:30:04 +01:00
if let Err(err) = f.read_to_string(&mut contents) {
eprintln!(
"Error reading script file: {}\n{}",
filename.to_string_lossy(),
err
);
2020-03-24 10:30:04 +01:00
exit(1);
}
2021-03-28 10:36:56 +02:00
let contents = if contents.starts_with("#!") {
// Skip shebang
&contents[contents.find('\n').unwrap_or(0)..]
} else {
&contents[..]
};
if let Err(err) = engine
.compile(contents)
2021-06-02 08:29:18 +02:00
.map_err(|err| err.into())
.and_then(|mut ast| {
ast.set_source(filename.to_string_lossy().to_string());
engine.consume_ast(&ast)
})
{
let filename = filename.to_string_lossy();
2020-04-02 16:37:35 +02:00
eprintln!("{:=<1$}", "", filename.len());
eprintln!("{}", filename);
2020-04-02 16:37:35 +02:00
eprintln!("{:=<1$}", "", filename.len());
eprintln!("");
2021-03-28 10:36:56 +02:00
eprint_error(contents, *err);
2016-02-29 22:43:45 +01:00
}
}
}