rhai/src/eval/debugger.rs

561 lines
18 KiB
Rust
Raw Normal View History

2022-01-24 10:04:40 +01:00
//! Module defining the debugging interface.
#![cfg(feature = "debugging")]
2022-04-16 17:32:14 +02:00
use super::{EvalContext, GlobalRuntimeState};
2022-01-24 10:04:40 +01:00
use crate::ast::{ASTNode, Expr, Stmt};
use crate::{Dynamic, Engine, EvalAltResult, Identifier, Module, Position, RhaiResultOf, Scope};
2022-01-24 10:04:40 +01:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
2022-04-13 04:35:10 +02:00
use std::{fmt, iter::repeat, mem};
2022-01-24 10:04:40 +01:00
2022-01-28 11:59:18 +01:00
/// Callback function to initialize the debugger.
#[cfg(not(feature = "sync"))]
pub type OnDebuggingInit = dyn Fn() -> Dynamic;
/// Callback function to initialize the debugger.
#[cfg(feature = "sync")]
pub type OnDebuggingInit = dyn Fn() -> Dynamic + Send + Sync;
/// Callback function for debugging.
2022-01-24 10:04:40 +01:00
#[cfg(not(feature = "sync"))]
pub type OnDebuggerCallback = dyn Fn(
2022-05-01 18:03:45 +02:00
EvalContext,
DebuggerEvent,
ASTNode,
Option<&str>,
Position,
) -> RhaiResultOf<DebuggerCommand>;
2022-01-28 11:59:18 +01:00
/// Callback function for debugging.
2022-01-24 10:04:40 +01:00
#[cfg(feature = "sync")]
2022-05-01 18:03:45 +02:00
pub type OnDebuggerCallback = dyn Fn(EvalContext, DebuggerEvent, ASTNode, Option<&str>, Position) -> RhaiResultOf<DebuggerCommand>
2022-01-27 16:55:32 +01:00
+ Send
+ Sync;
2022-01-24 10:04:40 +01:00
/// A command for the debugger on the next iteration.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
2022-04-26 10:36:24 +02:00
#[non_exhaustive]
2022-01-24 10:04:40 +01:00
pub enum DebuggerCommand {
// Continue normal execution.
Continue,
// Step into the next expression, diving into functions.
StepInto,
// Run to the next expression or statement, stepping over functions.
2022-01-24 10:04:40 +01:00
StepOver,
// Run to the next statement, skipping over functions.
Next,
// Run to the end of the current function call.
FunctionExit,
}
impl Default for DebuggerCommand {
#[inline(always)]
fn default() -> Self {
Self::Continue
}
}
/// The debugger status.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
2022-04-26 10:36:24 +02:00
#[non_exhaustive]
pub enum DebuggerStatus {
2022-04-26 10:36:24 +02:00
// Script evaluation starts.
Init,
// Stop at the next statement or expression.
Next(bool, bool),
// Run to the end of the current level of function call.
FunctionExit(usize),
2022-04-26 10:36:24 +02:00
// Script evaluation ends.
Terminate,
}
impl DebuggerStatus {
pub const CONTINUE: Self = Self::Next(false, false);
pub const STEP: Self = Self::Next(true, true);
pub const NEXT: Self = Self::Next(true, false);
2022-04-26 10:36:24 +02:00
pub const INTO: Self = Self::Next(false, true);
}
/// A event that triggers the debugger.
#[derive(Debug, Clone, Copy)]
2022-04-26 10:36:24 +02:00
#[non_exhaustive]
pub enum DebuggerEvent<'a> {
2022-04-26 10:36:24 +02:00
// Script evaluation starts.
Start,
// Break on next step.
Step,
// Break on break-point.
BreakPoint(usize),
// Return from a function with a value.
FunctionExitWithValue(&'a Dynamic),
// Return from a function with a value.
FunctionExitWithError(&'a EvalAltResult),
2022-04-26 10:36:24 +02:00
// Script evaluation ends.
End,
2022-01-24 10:04:40 +01:00
}
/// A break-point for debugging.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
2022-04-26 10:36:24 +02:00
#[non_exhaustive]
2022-01-24 10:04:40 +01:00
pub enum BreakPoint {
/// Break at a particular position under a particular source.
2022-01-25 16:59:35 +01:00
///
2022-01-24 10:04:40 +01:00
/// Not available under `no_position`.
///
/// Source is empty if not available.
#[cfg(not(feature = "no_position"))]
2022-01-25 10:29:34 +01:00
AtPosition {
source: Identifier,
pos: Position,
enabled: bool,
},
2022-01-24 10:04:40 +01:00
/// Break at a particular function call.
2022-01-25 10:29:34 +01:00
AtFunctionName { name: Identifier, enabled: bool },
2022-01-24 10:04:40 +01:00
/// Break at a particular function call with a particular number of arguments.
2022-01-25 10:29:34 +01:00
AtFunctionCall {
name: Identifier,
args: usize,
enabled: bool,
},
2022-01-25 11:21:05 +01:00
/// Break at a particular property .
2022-01-25 16:59:35 +01:00
///
/// Not available under `no_object`.
#[cfg(not(feature = "no_object"))]
2022-01-25 11:21:05 +01:00
AtProperty { name: Identifier, enabled: bool },
2022-01-24 10:04:40 +01:00
}
impl fmt::Display for BreakPoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
2022-01-25 16:59:35 +01:00
#[cfg(not(feature = "no_position"))]
2022-01-25 10:29:34 +01:00
Self::AtPosition {
source,
pos,
enabled,
} => {
2022-01-24 10:04:40 +01:00
if !source.is_empty() {
2022-01-25 10:29:34 +01:00
write!(f, "{} @ {:?}", source, pos)?;
2022-01-24 10:04:40 +01:00
} else {
2022-01-25 10:29:34 +01:00
write!(f, "@ {:?}", pos)?;
}
if !*enabled {
f.write_str(" (disabled)")?;
}
Ok(())
}
Self::AtFunctionName {
name: fn_name,
enabled,
} => {
write!(f, "{} (...)", fn_name)?;
if !*enabled {
f.write_str(" (disabled)")?;
2022-01-24 10:04:40 +01:00
}
2022-01-25 10:29:34 +01:00
Ok(())
2022-01-24 10:04:40 +01:00
}
2022-01-25 05:24:30 +01:00
Self::AtFunctionCall {
name: fn_name,
args,
2022-01-25 10:29:34 +01:00
enabled,
} => {
write!(
f,
"{} ({})",
fn_name,
2022-04-13 04:35:10 +02:00
repeat("_").take(*args).collect::<Vec<_>>().join(", ")
2022-01-25 10:29:34 +01:00
)?;
if !*enabled {
f.write_str(" (disabled)")?;
}
Ok(())
}
2022-01-25 16:59:35 +01:00
#[cfg(not(feature = "no_object"))]
2022-01-25 11:21:05 +01:00
Self::AtProperty {
name: prop,
enabled,
} => {
write!(f, ".{}", prop)?;
if !*enabled {
f.write_str(" (disabled)")?;
}
Ok(())
}
2022-01-25 10:29:34 +01:00
}
}
}
impl BreakPoint {
/// Is this [`BreakPoint`] enabled?
#[inline(always)]
pub fn is_enabled(&self) -> bool {
match self {
#[cfg(not(feature = "no_position"))]
Self::AtPosition { enabled, .. } => *enabled,
2022-01-25 16:59:35 +01:00
Self::AtFunctionName { enabled, .. } | Self::AtFunctionCall { enabled, .. } => *enabled,
#[cfg(not(feature = "no_object"))]
Self::AtProperty { enabled, .. } => *enabled,
2022-01-25 10:29:34 +01:00
}
}
/// Enable/disable this [`BreakPoint`].
#[inline(always)]
pub fn enable(&mut self, value: bool) {
match self {
#[cfg(not(feature = "no_position"))]
Self::AtPosition { enabled, .. } => *enabled = value,
2022-01-25 16:59:35 +01:00
Self::AtFunctionName { enabled, .. } | Self::AtFunctionCall { enabled, .. } => {
*enabled = value
}
#[cfg(not(feature = "no_object"))]
Self::AtProperty { enabled, .. } => *enabled = value,
2022-01-24 10:04:40 +01:00
}
}
}
2022-01-25 05:24:30 +01:00
/// A function call.
2022-01-24 10:04:40 +01:00
#[derive(Debug, Clone, Hash)]
pub struct CallStackFrame {
2022-01-25 16:59:35 +01:00
/// Function name.
2022-01-24 10:04:40 +01:00
pub fn_name: Identifier,
2022-01-25 16:59:35 +01:00
/// Copies of function call arguments, if any.
2022-01-25 07:32:07 +01:00
pub args: crate::StaticVec<Dynamic>,
2022-01-25 16:59:35 +01:00
/// Source of the function, empty if none.
2022-01-24 10:04:40 +01:00
pub source: Identifier,
2022-01-25 16:59:35 +01:00
/// [Position][`Position`] of the function call.
2022-01-24 10:04:40 +01:00
pub pos: Position,
}
impl fmt::Display for CallStackFrame {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut fp = f.debug_tuple(&self.fn_name);
for arg in &self.args {
fp.field(arg);
}
fp.finish()?;
if !self.pos.is_none() {
if self.source.is_empty() {
write!(f, " @ {:?}", self.pos)?;
} else {
write!(f, ": {} @ {:?}", self.source, self.pos)?;
}
}
Ok(())
}
}
/// A type providing debugging facilities.
#[derive(Debug, Clone, Hash)]
pub struct Debugger {
2022-01-25 16:59:35 +01:00
/// The current status command.
pub(crate) status: DebuggerStatus,
2022-01-25 16:59:35 +01:00
/// The current set of break-points.
2022-01-24 10:04:40 +01:00
break_points: Vec<BreakPoint>,
2022-01-25 16:59:35 +01:00
/// The current function call stack.
2022-01-24 10:04:40 +01:00
call_stack: Vec<CallStackFrame>,
/// The current state.
state: Dynamic,
2022-01-24 10:04:40 +01:00
}
impl Debugger {
2022-05-03 15:55:01 +02:00
/// Create a new [`Debugger`].
2022-01-28 11:59:18 +01:00
#[inline(always)]
#[must_use]
pub fn new(status: DebuggerStatus, state: Dynamic) -> Self {
2022-01-24 10:04:40 +01:00
Self {
2022-05-03 15:55:01 +02:00
status,
2022-01-24 10:04:40 +01:00
break_points: Vec::new(),
call_stack: Vec::new(),
state,
2022-01-24 10:04:40 +01:00
}
}
2022-01-25 05:24:30 +01:00
/// Get the current call stack.
#[inline(always)]
2022-01-28 11:59:18 +01:00
#[must_use]
2022-01-25 05:24:30 +01:00
pub fn call_stack(&self) -> &[CallStackFrame] {
&self.call_stack
}
2022-01-24 10:04:40 +01:00
/// Rewind the function call stack to a particular depth.
#[inline(always)]
2022-01-25 05:24:30 +01:00
pub(crate) fn rewind_call_stack(&mut self, len: usize) {
2022-01-24 10:04:40 +01:00
self.call_stack.truncate(len);
}
/// Add a new frame to the function call stack.
#[inline(always)]
2022-01-25 05:24:30 +01:00
pub(crate) fn push_call_stack_frame(
2022-01-24 10:04:40 +01:00
&mut self,
fn_name: impl Into<Identifier>,
2022-01-25 07:32:07 +01:00
args: crate::StaticVec<Dynamic>,
2022-01-24 10:04:40 +01:00
source: impl Into<Identifier>,
pos: Position,
) {
2022-01-25 05:24:30 +01:00
self.call_stack.push(CallStackFrame {
2022-01-24 10:04:40 +01:00
fn_name: fn_name.into(),
args,
source: source.into(),
pos,
2022-01-25 05:24:30 +01:00
});
2022-01-24 10:04:40 +01:00
}
2022-02-03 04:56:08 +01:00
/// Change the current status to [`CONTINUE`][DebuggerStatus::CONTINUE] and return the previous status.
pub(crate) fn clear_status_if(
&mut self,
filter: impl Fn(&DebuggerStatus) -> bool,
) -> Option<DebuggerStatus> {
if filter(&self.status) {
Some(mem::replace(&mut self.status, DebuggerStatus::CONTINUE))
} else {
None
}
}
/// Override the status of this [`Debugger`] if it is [`Some`] the current status is
/// [`CONTINUE`][DebuggerStatus::CONTINUE].
2022-01-25 05:24:30 +01:00
#[inline(always)]
pub(crate) fn reset_status(&mut self, status: Option<DebuggerStatus>) {
2022-02-03 04:56:08 +01:00
if self.status == DebuggerStatus::CONTINUE {
if let Some(cmd) = status {
self.status = cmd;
}
2022-01-25 05:24:30 +01:00
}
}
/// Returns the first break-point triggered by a particular [`AST` Node][ASTNode].
2022-01-28 11:59:18 +01:00
#[must_use]
pub fn is_break_point(&self, src: &str, node: ASTNode) -> Option<usize> {
2022-01-25 16:59:35 +01:00
let _src = src;
2022-01-25 10:29:34 +01:00
self.break_points()
.iter()
.enumerate()
2022-02-08 02:02:15 +01:00
.filter(|&(.., bp)| bp.is_enabled())
.find(|&(.., bp)| match bp {
2022-01-25 10:29:34 +01:00
#[cfg(not(feature = "no_position"))]
BreakPoint::AtPosition { pos, .. } if pos.is_none() => false,
#[cfg(not(feature = "no_position"))]
BreakPoint::AtPosition { source, pos, .. } if pos.is_beginning_of_line() => {
2022-01-25 16:59:35 +01:00
node.position().line().unwrap_or(0) == pos.line().unwrap() && _src == source
2022-01-24 10:04:40 +01:00
}
2022-01-25 10:29:34 +01:00
#[cfg(not(feature = "no_position"))]
BreakPoint::AtPosition { source, pos, .. } => {
2022-01-25 16:59:35 +01:00
node.position() == *pos && _src == source
2022-01-24 10:04:40 +01:00
}
2022-01-25 10:29:34 +01:00
BreakPoint::AtFunctionName { name, .. } => match node {
2022-02-16 10:51:14 +01:00
ASTNode::Expr(Expr::FnCall(x, ..)) | ASTNode::Stmt(Stmt::FnCall(x, ..)) => {
x.name == *name
}
ASTNode::Stmt(Stmt::Expr(e)) => match e.as_ref() {
Expr::FnCall(x, ..) => x.name == *name,
_ => false,
},
2022-01-25 10:29:34 +01:00
_ => false,
},
BreakPoint::AtFunctionCall { name, args, .. } => match node {
2022-02-16 10:51:14 +01:00
ASTNode::Expr(Expr::FnCall(x, ..)) | ASTNode::Stmt(Stmt::FnCall(x, ..)) => {
2022-01-25 10:29:34 +01:00
x.args.len() == *args && x.name == *name
}
2022-02-16 10:51:14 +01:00
ASTNode::Stmt(Stmt::Expr(e)) => match e.as_ref() {
Expr::FnCall(x, ..) => x.args.len() == *args && x.name == *name,
_ => false,
},
2022-01-25 10:29:34 +01:00
_ => false,
},
2022-01-25 16:59:35 +01:00
#[cfg(not(feature = "no_object"))]
2022-01-25 11:21:05 +01:00
BreakPoint::AtProperty { name, .. } => match node {
2022-02-08 02:02:15 +01:00
ASTNode::Expr(Expr::Property(x, ..)) => x.2 == *name,
2022-01-25 11:21:05 +01:00
_ => false,
},
2022-01-25 10:29:34 +01:00
})
2022-02-08 02:02:15 +01:00
.map(|(i, ..)| i)
2022-01-24 10:04:40 +01:00
}
/// Get a slice of all [`BreakPoint`]'s.
#[inline(always)]
#[must_use]
2022-01-25 05:24:30 +01:00
pub fn break_points(&self) -> &[BreakPoint] {
2022-01-24 10:04:40 +01:00
&self.break_points
}
/// Get the underlying [`Vec`] holding all [`BreakPoint`]'s.
#[inline(always)]
#[must_use]
pub fn break_points_mut(&mut self) -> &mut Vec<BreakPoint> {
&mut self.break_points
}
/// Get the custom state.
#[inline(always)]
#[must_use]
pub fn state(&self) -> &Dynamic {
&self.state
}
/// Get a mutable reference to the custom state.
#[inline(always)]
#[must_use]
pub fn state_mut(&mut self) -> &mut Dynamic {
&mut self.state
}
/// Set the custom state.
#[inline(always)]
pub fn set_state(&mut self, state: impl Into<Dynamic>) {
self.state = state.into();
}
2022-01-24 10:04:40 +01:00
}
impl Engine {
2022-02-03 04:56:08 +01:00
/// Run the debugger callback if there is a debugging interface registered.
2022-01-25 05:24:30 +01:00
#[inline(always)]
pub(crate) fn run_debugger<'a>(
2022-01-24 10:04:40 +01:00
&self,
scope: &mut Scope,
global: &mut GlobalRuntimeState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
2022-01-25 05:24:30 +01:00
node: impl Into<ASTNode<'a>>,
2022-01-24 10:04:40 +01:00
level: usize,
) -> RhaiResultOf<()> {
2022-02-03 04:56:08 +01:00
if self.debugger.is_some() {
if let Some(cmd) =
2022-04-16 17:32:14 +02:00
self.run_debugger_with_reset_raw(scope, global, lib, this_ptr, node, level)?
2022-02-03 04:56:08 +01:00
{
global.debugger.status = cmd;
}
2022-01-25 05:24:30 +01:00
}
Ok(())
2022-01-25 05:24:30 +01:00
}
2022-02-03 04:56:08 +01:00
/// Run the debugger callback if there is a debugging interface registered.
///
/// Returns `Some` if the debugger needs to be reactivated at the end of the block, statement or
/// function call.
///
/// It is up to the [`Engine`] to reactivate the debugger.
#[inline(always)]
#[must_use]
pub(crate) fn run_debugger_with_reset<'a>(
&self,
scope: &mut Scope,
global: &mut GlobalRuntimeState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
node: impl Into<ASTNode<'a>>,
level: usize,
) -> RhaiResultOf<Option<DebuggerStatus>> {
if self.debugger.is_some() {
2022-04-16 17:32:14 +02:00
self.run_debugger_with_reset_raw(scope, global, lib, this_ptr, node, level)
2022-02-03 04:56:08 +01:00
} else {
Ok(None)
}
}
2022-01-25 05:24:30 +01:00
/// Run the debugger callback.
///
/// Returns `Some` if the debugger needs to be reactivated at the end of the block, statement or
2022-01-25 05:24:30 +01:00
/// function call.
///
/// It is up to the [`Engine`] to reactivate the debugger.
#[inline]
#[must_use]
2022-02-03 04:56:08 +01:00
pub(crate) fn run_debugger_with_reset_raw<'a>(
2022-01-25 05:24:30 +01:00
&self,
scope: &mut Scope,
global: &mut GlobalRuntimeState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
node: impl Into<ASTNode<'a>>,
level: usize,
) -> RhaiResultOf<Option<DebuggerStatus>> {
let node = node.into();
2022-01-25 05:24:30 +01:00
// Skip transitive nodes
match node {
2022-02-08 02:46:14 +01:00
ASTNode::Expr(Expr::Stmt(..)) | ASTNode::Stmt(Stmt::Expr(..)) => return Ok(None),
_ => (),
}
2022-01-26 15:15:47 +01:00
2022-04-26 10:36:24 +02:00
let event = match global.debugger.status {
DebuggerStatus::Init => Some(DebuggerEvent::Start),
DebuggerStatus::CONTINUE => None,
DebuggerStatus::NEXT if matches!(node, ASTNode::Stmt(..)) => Some(DebuggerEvent::Step),
DebuggerStatus::NEXT => None,
DebuggerStatus::INTO if matches!(node, ASTNode::Expr(..)) => Some(DebuggerEvent::Step),
DebuggerStatus::INTO => None,
DebuggerStatus::STEP => Some(DebuggerEvent::Step),
DebuggerStatus::FunctionExit(..) => None,
DebuggerStatus::Terminate => Some(DebuggerEvent::End),
};
2022-01-25 05:24:30 +01:00
2022-04-26 10:36:24 +02:00
let event = match event {
Some(e) => e,
None => {
if let Some(bp) = global.debugger.is_break_point(&global.source, node) {
DebuggerEvent::BreakPoint(bp)
} else {
return Ok(None);
}
2022-01-25 05:24:30 +01:00
}
};
2022-01-25 05:24:30 +01:00
2022-04-16 17:32:14 +02:00
self.run_debugger_raw(scope, global, lib, this_ptr, node, event, level)
}
/// Run the debugger callback unconditionally.
///
/// Returns `Some` if the debugger needs to be reactivated at the end of the block, statement or
/// function call.
///
/// It is up to the [`Engine`] to reactivate the debugger.
#[inline]
#[must_use]
pub(crate) fn run_debugger_raw<'a>(
&self,
scope: &mut Scope,
global: &mut GlobalRuntimeState,
lib: &[&Module],
this_ptr: &mut Option<&mut Dynamic>,
node: ASTNode<'a>,
event: DebuggerEvent,
level: usize,
) -> Result<Option<DebuggerStatus>, Box<crate::EvalAltResult>> {
let source = global.source.clone();
let source = if source.is_empty() {
None
} else {
Some(source.as_str())
};
2022-01-25 05:24:30 +01:00
2022-05-17 10:21:17 +02:00
let context = crate::EvalContext::new(self, scope, global, None, lib, this_ptr, level);
2022-01-25 05:24:30 +01:00
2022-02-08 02:02:15 +01:00
if let Some((.., ref on_debugger)) = self.debugger {
2022-05-01 18:03:45 +02:00
let command = on_debugger(context, event, node, source, node.position())?;
2022-01-25 05:24:30 +01:00
match command {
DebuggerCommand::Continue => {
global.debugger.status = DebuggerStatus::CONTINUE;
Ok(None)
}
DebuggerCommand::Next => {
global.debugger.status = DebuggerStatus::CONTINUE;
Ok(Some(DebuggerStatus::NEXT))
}
DebuggerCommand::StepOver => {
global.debugger.status = DebuggerStatus::CONTINUE;
Ok(Some(DebuggerStatus::STEP))
2022-01-25 05:24:30 +01:00
}
DebuggerCommand::StepInto => {
global.debugger.status = DebuggerStatus::STEP;
Ok(None)
2022-01-25 05:24:30 +01:00
}
DebuggerCommand::FunctionExit => {
// Bump a level if it is a function call
let level = match node {
2022-02-16 10:51:14 +01:00
ASTNode::Expr(Expr::FnCall(..)) | ASTNode::Stmt(Stmt::FnCall(..)) => {
2022-05-01 18:03:45 +02:00
level + 1
2022-02-16 10:51:14 +01:00
}
ASTNode::Stmt(Stmt::Expr(e)) if matches!(e.as_ref(), Expr::FnCall(..)) => {
2022-05-01 18:03:45 +02:00
level + 1
2022-02-16 10:51:14 +01:00
}
2022-05-01 18:03:45 +02:00
_ => level,
};
global.debugger.status = DebuggerStatus::FunctionExit(level);
Ok(None)
2022-01-24 10:04:40 +01:00
}
}
2022-01-25 05:24:30 +01:00
} else {
Ok(None)
2022-01-24 10:04:40 +01:00
}
}
}