pub use rhue_vm::{DebugEvent, HookMask};
use crate::{Context, Value};
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct StackFrame {
pub function: String,
pub source: String,
pub line: u32,
}
pub struct Debugger<'a, 'b> {
pub(crate) ctx: &'a mut rhue_vm::DebugCtx<'b>,
}
impl Debugger<'_, '_> {
pub fn depth(&self) -> usize {
self.ctx.depth()
}
pub fn frame(&self, level: usize) -> Option<StackFrame> {
self.ctx.frame(level).map(|f| StackFrame {
function: f.function,
source: f.source.name.to_string(),
line: f.line,
})
}
pub fn stack(&self) -> Vec<StackFrame> {
(0..self.depth()).filter_map(|l| self.frame(l)).collect()
}
pub fn locals(&mut self, level: usize) -> Vec<(String, Value)> {
let raw = self.ctx.locals(level);
let cx = Context::new(self.ctx.vm());
raw.into_iter()
.map(|(n, v)| (n.to_string(), cx.lift(v)))
.collect()
}
pub fn upvalues(&mut self, level: usize) -> Vec<(String, Value)> {
let raw = self.ctx.upvalues(level);
let cx = Context::new(self.ctx.vm());
raw.into_iter()
.map(|(n, v)| (n.to_string(), cx.lift(v)))
.collect()
}
pub fn eval(&mut self, level: usize, expr: &str) -> Result<Vec<Value>, String> {
let mut names: Vec<std::rc::Rc<str>> = Vec::new();
let mut values = Vec::new();
let is_name = |n: &str| {
n.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& n.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
};
let mut visible = self.ctx.locals(level);
visible.reverse();
visible.extend(self.ctx.upvalues(level));
for (n, v) in visible {
if is_name(&n) && !names.contains(&n) {
names.push(n);
values.push(v);
}
}
let prelude = if names.is_empty() {
String::new()
} else {
let list: Vec<&str> = names.iter().map(|n| &**n).collect();
format!("local {} = ...; ", list.join(", "))
};
let vm = self.ctx.vm();
let proto = crate::modules::compile(vm, "<eval>", &format!("{prelude}return {expr}"))
.or_else(|first| {
crate::modules::compile(vm, "<eval>", &format!("{prelude}{expr}"))
.map_err(|_| first)
})
.map_err(|e| e.to_string())?
.0;
let f = vm.load(&proto);
match vm.try_call(f, &values) {
Ok(rets) => {
let cx = Context::new(vm);
Ok(rets.into_iter().map(|v| cx.lift(v)).collect())
}
Err(thrown) => {
Err(crate::ScriptError(crate::context::Repr::Thrown(Box::new(thrown))).message())
}
}
}
pub fn context(&mut self) -> Context<'_> {
Context::new(self.ctx.vm())
}
}