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

@@ -27,7 +27,7 @@ engine.on_print(|x| println!("hello: {}", x));
// Any function or closure that takes a '&str' and a 'Position' argument can be used to
// override 'debug'.
engine.on_debug(|x, pos| println!("DEBUG at {:?}: {}", pos, x));
engine.on_debug(|x, src, pos| println!("DEBUG of {} at {:?}: {}", src.unwrap_or("unknown"), pos, x));
// Example: quick-'n-dirty logging
let logbook = Arc::new(RwLock::new(Vec::<String>::new()));
@@ -37,9 +37,9 @@ let log = logbook.clone();
engine.on_print(move |s| log.write().unwrap().push(format!("entry: {}", s)));
let log = logbook.clone();
engine.on_debug(move |s, pos| log.write().unwrap().push(
format!("DEBUG at {:?}: {}", pos, s)
));
engine.on_debug(move |s, src, pos| log.write().unwrap().push(
format!("DEBUG of {} at {:?}: {}", src.unwrap_or("unknown"), pos, s)
));
// Evaluate script
engine.eval::<()>(script)?;
@@ -49,3 +49,24 @@ for entry in logbook.read().unwrap().iter() {
println!("{}", entry);
}
```
`on_debug` Callback Signature
-----------------------------
The function signature passed to `Engine::on_debug` takes the following form:
> `Fn(text: &str, source: Option<&str>, pos: Position) + 'static`
where:
| Parameter | Type | Description |
| --------- | :------------: | --------------------------------------------------------------- |
| `text` | `&str` | text to display |
| `source` | `Option<&str>` | source of the current evaluation, if any |
| `pos` | `Position` | position (line number and character offset) of the `debug` call |
The _source_ of a script evaluation is any text string provided to an [`AST`] via the `AST::set_source` method.
If a [module] is loaded via an [`import`] statement, then the _source_ of functions defined
within the module will be the module's _path_.