use crate::{Statement, Value};
use std::{
cell::{Cell, RefCell},
collections::{BTreeMap, BTreeSet},
};
use xrack_mlir::OperationRef;
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct Location {
pub file: String,
pub line: usize,
pub column: usize,
}
impl Location {
pub(crate) fn from_operation(op: OperationRef<'_>) -> Option<Self> {
let file = op.source_file()?;
let span = op.span();
(std::path::Path::new(file)
.extension()
.is_some_and(|ext| ext == "xr")
&& span.line != 0)
.then(|| Self {
file: file.to_owned(),
line: span.line,
column: span.column,
})
}
}
#[derive(Clone)]
pub(crate) struct LocatedStatement {
pub statement: Statement,
location: Location,
locals: Vec<String>,
}
impl LocatedStatement {
pub(crate) fn new(statement: Statement, location: Location, locals: Vec<String>) -> Self {
Self {
statement,
location,
locals,
}
}
}
pub type Breakpoints = BTreeMap<String, Vec<usize>>;
#[derive(Clone, Copy, Debug)]
pub enum Action {
Continue,
StepIn,
Next,
StepOut,
Disconnect,
}
#[derive(Clone, Debug)]
pub struct Frame {
pub name: String,
pub location: Option<Location>,
}
#[derive(Debug)]
pub struct Stop {
pub breakpoint: bool,
pub frames: Vec<Frame>,
pub locals: Vec<(String, String)>,
pub properties: Vec<(String, String)>,
}
#[derive(Clone, Copy)]
enum Run {
Continue,
Into,
Over(usize),
Out(usize),
}
pub struct Debugger {
stack: RefCell<Vec<Frame>>,
breakpoints: RefCell<Breakpoints>,
run: Cell<Run>,
connected: Cell<bool>,
locations: RefCell<BTreeMap<String, BTreeSet<usize>>>,
on_stop: Box<StopHandler>,
}
type StopHandler = dyn Fn(&Debugger, Stop) -> Action;
impl Debugger {
pub fn new(on_stop: impl Fn(&Self, Stop) -> Action + 'static) -> Self {
Self {
stack: RefCell::default(),
breakpoints: RefCell::default(),
run: Cell::new(Run::Continue),
connected: Cell::new(true),
locations: RefCell::default(),
on_stop: Box::new(on_stop),
}
}
pub fn set_breakpoints(&self, breakpoints: Breakpoints) {
*self.breakpoints.borrow_mut() = breakpoints;
}
pub fn locations(&self) -> Breakpoints {
self.locations
.borrow()
.iter()
.map(|(file, lines)| (file.clone(), lines.iter().copied().collect()))
.collect()
}
pub(crate) fn register_location(&self, location: &Location) {
self.locations
.borrow_mut()
.entry(location.file.clone())
.or_default()
.insert(location.line);
}
pub(crate) fn enter(&self, instance: &str, name: &str) -> FrameGuard<'_> {
self.stack.borrow_mut().push(Frame {
name: format!("{instance}.{name}"),
location: None,
});
FrameGuard(self)
}
pub(crate) fn before(
&self,
statement: &LocatedStatement,
values: &[Value],
properties: impl FnOnce() -> Vec<(String, String)>,
) {
if !self.connected.get() {
return;
}
let location = &statement.location;
let mut stack = self.stack.borrow_mut();
let depth = stack.len();
let Some(frame) = stack.last_mut() else {
return;
};
frame.location = Some(location.clone());
let breakpoint = self
.breakpoints
.borrow()
.get(&location.file)
.is_some_and(|lines| lines.contains(&location.line));
let stepping = match self.run.get() {
Run::Continue => false,
Run::Into => true,
Run::Over(previous) => depth <= previous,
Run::Out(previous) => depth < previous,
};
if !breakpoint && !stepping {
return;
}
let frames = stack.iter().rev().cloned().collect();
drop(stack);
let stop = Stop {
breakpoint,
frames,
locals: statement
.locals
.iter()
.zip(values)
.rev()
.take(128)
.map(|(name, value)| (name.clone(), describe(value)))
.collect(),
properties: properties(),
};
self.run.set(match (self.on_stop)(self, stop) {
Action::Continue => Run::Continue,
Action::StepIn => Run::Into,
Action::Next => Run::Over(depth),
Action::StepOut => Run::Out(depth),
Action::Disconnect => {
self.connected.set(false);
Run::Continue
}
});
}
}
pub(crate) struct FrameGuard<'a>(&'a Debugger);
impl Drop for FrameGuard<'_> {
fn drop(&mut self) {
let mut stack = self.0.stack.borrow_mut();
stack.pop();
if stack.is_empty() {
self.0.run.set(Run::Continue);
}
}
}
pub(crate) fn describe(value: &Value) -> String {
match value {
Value::Bool(value) => value.to_string(),
Value::Int(value) => value.to_string(),
Value::Float(value) => value.to_string(),
Value::Length(value) => format!("{}px", value.0),
Value::String(value) => {
let prefix = value.chars().take(256).collect::<String>();
if prefix.len() < value.len() {
format!("{prefix:?}…")
} else {
format!("{prefix:?}")
}
}
_ => "<complex value>".into(),
}
}