Refactor error display.

This commit is contained in:
Stephen Chung 2020-03-25 11:51:13 +08:00
parent b603a85bca
commit ff8756018b
2 changed files with 30 additions and 41 deletions

View File

@ -1,4 +1,4 @@
use rhai::{Engine, EvalAltResult, Scope, AST};
use rhai::{Engine, EvalAltResult, Position, Scope, AST};
#[cfg(not(feature = "no_optimize"))]
use rhai::OptimizationLevel;
@ -26,27 +26,18 @@ fn print_error(input: &str, err: EvalAltResult) {
};
// Print error
let pos_text = format!(" ({})", err.position());
let pos = err.position();
let pos_text = format!(" ({})", pos);
match err.position() {
p if p.is_eof() => {
// EOF
let pos = if pos.is_eof() {
let last = lines[lines.len() - 1];
println!("{}{}", line_no, last);
let err_text = match err {
EvalAltResult::ErrorRuntime(err, _) if !err.is_empty() => {
format!("Runtime error: {}", err)
}
_ => err.to_string(),
Position::new(lines.len(), last.len() + 1)
} else {
pos
};
println!(
"{}^ {}",
padding(" ", line_no.len() + last.len() - 1),
err_text.replace(&pos_text, "")
);
}
match pos {
p if p.is_eof() => panic!("should not be EOF"),
p if p.is_none() => {
// No position
println!("{}", err);
@ -59,7 +50,7 @@ fn print_error(input: &str, err: EvalAltResult) {
EvalAltResult::ErrorRuntime(err, _) if !err.is_empty() => {
format!("Runtime error: {}", err)
}
_ => err.to_string(),
err => err.to_string(),
};
println!(

View File

@ -1,4 +1,4 @@
use rhai::{Engine, EvalAltResult};
use rhai::{Engine, EvalAltResult, Position};
#[cfg(not(feature = "no_optimize"))]
use rhai::OptimizationLevel;
@ -26,31 +26,29 @@ fn eprint_error(input: &str, err: EvalAltResult) {
let lines: Vec<_> = input.split('\n').collect();
// Print error
match err.position() {
p if p.is_eof() => {
// EOF
let line = lines.len() - 1;
let pos = lines[line - 1].len();
let err_text = match err {
EvalAltResult::ErrorRuntime(err, _) if !err.is_empty() => {
format!("Runtime error: {}", err)
}
_ => err.to_string(),
let pos = if err.position().is_eof() {
let last = lines[lines.len() - 1];
Position::new(lines.len(), last.len() + 1)
} else {
err.position()
};
eprint_line(&lines, line, pos, &err_text);
}
match pos {
p if p.is_eof() => panic!("should not be EOF"),
p if p.is_none() => {
// No position
eprintln!("{}", err);
}
p => {
// Specific position
eprint_line(
&lines,
p.line().unwrap(),
p.position().unwrap(),
&err.to_string(),
)
let err_text = match err {
EvalAltResult::ErrorRuntime(err, _) if !err.is_empty() => {
format!("Runtime error: {}", err)
}
err => err.to_string(),
};
eprint_line(&lines, p.line().unwrap(), p.position().unwrap(), &err_text)
}
}
}