From e3cfcd0332ef72575cc7b171a6b51dd7f8b0380f Mon Sep 17 00:00:00 2001 From: Nick Heyer Date: Mon, 23 Sep 2024 22:09:36 -0700 Subject: [PATCH] Adding halt interupt to env --- duckscript/src/runner.rs | 7 +++++++ duckscript/src/types/env.rs | 18 +++++++++--------- duckscript/src/types/env_test.rs | 4 ++-- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/duckscript/src/runner.rs b/duckscript/src/runner.rs index 2b9c2ba0..1660674d 100644 --- a/duckscript/src/runner.rs +++ b/duckscript/src/runner.rs @@ -18,12 +18,14 @@ use crate::types::instruction::{ use crate::types::runtime::{Context, Runtime, StateValue}; use std::collections::HashMap; use std::io::stdin; +use std::sync::atomic::Ordering; #[derive(Debug)] enum EndReason { ExitCalled, ReachedEnd, Crash(ScriptError), + Halted } /// Executes the provided script with the given context @@ -135,6 +137,11 @@ fn run_instructions( let mut end_reason = EndReason::ReachedEnd; loop { + if runtime.env.halt.load(Ordering::SeqCst) { + end_reason = EndReason::Halted; + break; + } + let (instruction, meta_info) = if instructions.len() > line { let instruction = instructions[line].clone(); let meta_info = instruction.meta_info.clone(); diff --git a/duckscript/src/types/env.rs b/duckscript/src/types/env.rs index 340b53e6..a93575b1 100644 --- a/duckscript/src/types/env.rs +++ b/duckscript/src/types/env.rs @@ -8,6 +8,8 @@ mod env_test; use std::io::{stderr, stdout, Write}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; /// The runtime env pub struct Env { @@ -15,6 +17,8 @@ pub struct Env { pub out: Box, /// The error writer pub err: Box, + /// The halt token - Set to true to exit after current instruction + pub halt: Arc, } impl Env { @@ -23,20 +27,16 @@ impl Env { Env { out: Box::new(stdout()), err: Box::new(stderr()), + halt: Arc::new(AtomicBool::new(false)), } } /// Creates and returns a new instance. - pub fn new(out: Option>, err: Option>) -> Env { + pub fn new(out: Option>, err: Option>, halt: Option>) -> Env { Env { - out: match out { - Some(value) => value, - None => Box::new(stdout()), - }, - err: match err { - Some(value) => value, - None => Box::new(stderr()), - }, + out: out.unwrap_or_else(|| Box::new(stdout())), + err: err.unwrap_or_else(|| Box::new(stderr())), + halt: halt.unwrap_or_else(|| Arc::new(AtomicBool::new(false))), } } } diff --git a/duckscript/src/types/env_test.rs b/duckscript/src/types/env_test.rs index c66ef5fc..471602e3 100644 --- a/duckscript/src/types/env_test.rs +++ b/duckscript/src/types/env_test.rs @@ -13,14 +13,14 @@ fn env_default() { #[test] fn env_new_none() { - let mut env = Env::new(None, None); + let mut env = Env::new(None, None, None); validate_env(&mut env); } #[test] fn env_new_with_values() { - let mut env = Env::new(Some(Box::new(stdout())), Some(Box::new(stdout()))); + let mut env = Env::new(Some(Box::new(stdout())), Some(Box::new(stdout())), None); validate_env(&mut env); }