From 4478327fa8515c256bda1b90216238e2644fab91 Mon Sep 17 00:00:00 2001 From: Nat Quayle Nelson Date: Sat, 19 Aug 2023 14:18:16 -0600 Subject: [PATCH] AsyncEmbeddedScript2 use tail recursion for stack management --- src/kiss/AsyncEmbeddedScript2.hx | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/kiss/AsyncEmbeddedScript2.hx b/src/kiss/AsyncEmbeddedScript2.hx index 050b01b..df98657 100644 --- a/src/kiss/AsyncEmbeddedScript2.hx +++ b/src/kiss/AsyncEmbeddedScript2.hx @@ -167,10 +167,7 @@ class AsyncEmbeddedScript2 { public var running(default, null):Bool = false; - public var unwindStack(default, default):Bool = false; - public var alwaysUnwindStack(default, default):Bool = false; - - private function runInstruction(instructionPointer:Int, withBreakPoints = true) { + private function runInstruction(instructionPointer:Int, withBreakPoints = true):Void { running = true; var skipping = false; if (skipTarget != null) { @@ -190,21 +187,19 @@ class AsyncEmbeddedScript2 { onBreak(this, false, () -> runInstruction(instructionPointer, false)); } } + var tryCallNextWithTailRecursion = false; + var nextCalledWithTailRecursion = false; var continuation = if (instructionPointer < instructions.length - 1) { () -> { // runInstruction may be called externally to skip through the script. // When this happens, make sure other scheduled continuations are canceled // by verifying that lastInstructionPointer hasn't changed if (lastInstructionPointer == instructionPointer) { - if (unwindStack || alwaysUnwindStack) { - haxe.Timer.delay(()->{runInstruction(instructionPointer + 1, withBreakPoints);}, 0); - if (!alwaysUnwindStack) - unwindStack = false; - return; - } - else { - runInstruction(instructionPointer + 1, withBreakPoints); - } + tryCallNextWithTailRecursion = true; + haxe.Timer.delay(()->{ + if (!nextCalledWithTailRecursion) + runInstruction(instructionPointer + 1, withBreakPoints); + }, 0); } }; } else { @@ -215,6 +210,11 @@ class AsyncEmbeddedScript2 { } else { instructions[instructionPointer](this, skipping, continuation); } + + if (tryCallNextWithTailRecursion) { + nextCalledWithTailRecursion = true; + runInstruction(instructionPointer + 1, withBreakPoints); + } } public function run(withBreakPoints = true) {