Skip to content

Commit

Permalink
Add debug hook (#38)
Browse files Browse the repository at this point in the history
Adds a debug hook function so embedders of Stack can provide an
appropriate debug print if it makes sense to do so. This allows users of
Stack to have some way to get debug output, even if an alternative is
not available; especially useful once `print` and `pretty` are no-longer
intrinsics and become part of the standard library.
  • Loading branch information
leonskidev authored Jun 1, 2024
1 parent ce19a90 commit b635b79
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion stack-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ fn main() {
}
};

let mut engine = Engine::new();
let mut engine = Engine::new().with_debug_hook(Some(|s| eprintln!("{s}")));
let mut context = new_context();

#[cfg(feature = "stack-std")]
Expand Down
13 changes: 13 additions & 0 deletions stack-core/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub struct Engine {
modules: HashMap<Symbol, Module>,
start_time: Option<Instant>,
timeout: Option<Duration>,
debug_hook: Option<fn(String)>,
}

#[derive(Debug, Clone, PartialEq)]
Expand All @@ -37,6 +38,7 @@ impl Engine {
modules: HashMap::new(),
start_time: None,
timeout: None,
debug_hook: None,
}
}

Expand All @@ -52,11 +54,22 @@ impl Engine {
self
}

#[inline]
pub fn with_debug_hook(mut self, debug_hook: Option<fn(String)>) -> Self {
self.debug_hook = debug_hook;
self
}

#[inline]
pub fn module(&self, symbol: &Symbol) -> Option<&Module> {
self.modules.get(symbol)
}

#[inline]
pub fn debug_hook(&self) -> Option<fn(String)> {
self.debug_hook
}

pub fn run(
&self,
mut context: Context,
Expand Down
19 changes: 19 additions & 0 deletions stack-core/src/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ intrinsics! {
Set => "set",
Get => "get",

Debug => "debug",
// TODO: These will become STD module items.
Print => "print",
Pretty => "pretty",
Recur => "recur",
Expand Down Expand Up @@ -916,6 +918,23 @@ impl Intrinsic {
}
}

// MARK: Debug
Self::Debug => {
if let Some(debug_hook) = engine.debug_hook() {
debug_hook(
context
.stack()
.last()
.cloned()
.unwrap_or(Expr {
kind: ExprKind::Nil,
info: None,
})
.to_string(),
);
}
Ok(context)
}
// MARK: Print
Self::Print => {
let val = context.stack_pop(&expr)?;
Expand Down

0 comments on commit b635b79

Please sign in to comment.