Add context source to on_debug.

This commit is contained in:
Stephen Chung
2020-12-21 22:04:46 +08:00
parent 2955a4ab64
commit 5ac83f0f46
12 changed files with 232 additions and 68 deletions

View File

@@ -55,17 +55,20 @@ fn test_optimizer_parse() -> Result<(), Box<EvalAltResult>> {
let ast = engine.compile("{ const DECISION = false; if DECISION { 42 } else { 123 } }")?;
assert!(format!("{:?}", ast).starts_with(r#"AST { statements: [Block([Const(IdentX { name: "DECISION", pos: 1:9 }, Some(Unit(0:0)), false, 1:3), Expr(IntegerConstant(123, 1:53))], 1:1)]"#));
assert!(format!("{:?}", ast).starts_with(r#"AST { source: None, statements: [Block([Const(IdentX { name: "DECISION", pos: 1:9 }, Some(Unit(0:0)), false, 1:3), Expr(IntegerConstant(123, 1:53))], 1:1)]"#));
let ast = engine.compile("if 1 == 2 { 42 }")?;
assert!(format!("{:?}", ast).starts_with("AST { statements: [], functions: Module("));
assert!(
format!("{:?}", ast).starts_with("AST { source: None, statements: [], functions: Module(")
);
engine.set_optimization_level(OptimizationLevel::Full);
let ast = engine.compile("abs(-42)")?;
assert!(format!("{:?}", ast).starts_with(r"AST { statements: [Expr(IntegerConstant(42, 1:1))]"));
assert!(format!("{:?}", ast)
.starts_with(r"AST { source: None, statements: [Expr(IntegerConstant(42, 1:1))]"));
Ok(())
}

View File

@@ -13,20 +13,28 @@ fn test_print_debug() -> Result<(), Box<EvalAltResult>> {
engine
.on_print(move |s| log1.write().unwrap().push(format!("entry: {}", s)))
.on_debug(move |s, pos| {
log2.write()
.unwrap()
.push(format!("DEBUG at {:?}: {}", pos, s))
.on_debug(move |s, src, pos| {
log2.write().unwrap().push(format!(
"DEBUG of {} at {:?}: {}",
src.unwrap_or("unknown"),
pos,
s
))
});
// Evaluate script
engine.eval::<()>("print(40 + 2)")?;
engine.eval::<()>(r#"let x = "hello!"; debug(x)"#)?;
engine.consume("print(40 + 2)")?;
let mut ast = engine.compile(r#"let x = "hello!"; debug(x)"#)?;
ast.set_source(Some("world"));
engine.consume_ast(&ast)?;
// 'logbook' captures all the 'print' and 'debug' output
assert_eq!(logbook.read().unwrap().len(), 2);
assert_eq!(logbook.read().unwrap()[0], "entry: 42");
assert_eq!(logbook.read().unwrap()[1], r#"DEBUG at 1:19: "hello!""#);
assert_eq!(
logbook.read().unwrap()[1],
r#"DEBUG of world at 1:19: "hello!""#
);
for entry in logbook.read().unwrap().iter() {
println!("{}", entry);