generated from zzy/tide-async-graphql-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrhai-run.rs
102 lines (84 loc) · 2.72 KB
/
rhai-run.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
90
91
92
93
94
95
96
97
98
99
100
101
102
use rhai::{Engine, EvalAltResult, Position};
#[cfg(not(feature = "no_optimize"))]
use rhai::OptimizationLevel;
use std::{env, fs::File, io::Read, path::Path, process::exit};
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!(
"{:>1$} {2}",
"^",
line_no.len() + pos.position().unwrap(),
err_msg
);
eprintln!("");
}
let lines: Vec<_> = input.split('\n').collect();
// Print error
let pos = err.take_position();
if pos.is_none() {
// No position
eprintln!("{}", err);
} else {
// Specific position
eprint_line(&lines, pos, &err.to_string())
}
}
fn main() {
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) => f,
};
let mut engine = Engine::new();
#[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,
};
contents.clear();
if let Err(err) = f.read_to_string(&mut contents) {
eprintln!(
"Error reading script file: {}\n{}",
filename.to_string_lossy(),
err
);
exit(1);
}
let contents = if contents.starts_with("#!") {
// Skip shebang
&contents[contents.find('\n').unwrap_or(0)..]
} else {
&contents[..]
};
if let Err(err) = engine
.compile(contents)
.map_err(|err| Box::new(err.into()) as Box<EvalAltResult>)
.and_then(|mut ast| {
ast.set_source(filename.to_string_lossy().to_string());
engine.consume_ast(&ast)
})
{
let filename = filename.to_string_lossy();
eprintln!("{:=<1$}", "", filename.len());
eprintln!("{}", filename);
eprintln!("{:=<1$}", "", filename.len());
eprintln!("");
eprint_error(contents, *err);
}
}
}