diff --git a/docs/library-api.md b/docs/library-api.md index 25a82c7..fd83120 100644 --- a/docs/library-api.md +++ b/docs/library-api.md @@ -480,15 +480,41 @@ interpreter.AddStatement("exec", SearchMode.StartOfLine, SpaceAround.End, args = ## Tasks -A line ending in `task` runs in a task alongside the script (see the language reference), on a -thread of its own. A task's interpreter gets these from the script's: +A line ending in `task` runs in a task alongside the script (see the language reference). A +task's interpreter gets these from the script's: - its statements: the built-in ones as the host left them, and the custom ones, whose `IStatementContext` is the task's own; -- its host; +- its host and task mode; - the functions the script has already passed, so a task can call a function defined above it. -It also shares the script's global variables. A task goes on after the script ends. +It also shares the script's global variables. + +`TaskMode` says how tasks run: + +| Value | Tasks run… | +| ------------- | ----------------------------------------------------------------------------------------------------------------- | +| `Thread` | Each on a thread of its own, at the same time as the script (the default). A task goes on after the script ends. | +| `Cooperative` | On the thread that steps the script, taking turns with it. For single-threaded hosts. | + +With `Cooperative`: + +- Each step runs a line of the script and a line of each task. +- `IsRunning` stays `true` until the script and all its tasks end. +- Custom statements run on the stepping thread, even in tasks, so they may touch state that + belongs to it (a window, a game object) without locks. +- A task that waits (`sleep`, input) does not hold up the script or the other tasks. + +```csharp +var interpreter = new YesNtInterpreter { TaskMode = TaskMode.Cooperative }; +interpreter.Prepare("game.ynt"); + +void OnFrame() // the game's loop, on its one thread +{ + if (interpreter.IsRunning) + _ = interpreter.RunFor(TimeSpan.FromMilliseconds(2)); +} +``` --- @@ -619,11 +645,14 @@ public void Stop(); // Read-only snapshot of all registered statements public ReadOnlyCollection StatementInformation { get; } -// Whether a prepared script is currently active/running +// Whether a prepared script (or, with TaskMode.Cooperative, one of its tasks) is still running public bool IsRunning { get; } // The script's console and files (default: ConsoleHost); set before the script starts public IYesNtHost Host { get; set; } + +// How task lines run (default: TaskMode.Thread); set before the script starts +public TaskMode TaskMode { get; set; } ``` --- @@ -690,3 +719,10 @@ is pressed, so the script waits without blocking the thread that steps it. | `Ready` | The input is there. | | `Pending` | Not yet: the script waits and asks again when stepped. | | `Closed` | There will be no more input: the script ends. | + +### `TaskMode` + +| Value | Description | +| ------------- | ------------------------------------------------------------- | +| `Thread` | Each task runs on a thread of its own (the default). | +| `Cooperative` | Tasks take turns with the script on the thread that steps it. | diff --git a/src/YesNt.Interpreter.Tests/HostApiTests.cs b/src/YesNt.Interpreter.Tests/HostApiTests.cs index 9ef1eb5..42f1ec6 100644 --- a/src/YesNt.Interpreter.Tests/HostApiTests.cs +++ b/src/YesNt.Interpreter.Tests/HostApiTests.cs @@ -99,10 +99,10 @@ public class HostApiTests } } - private static (YesNtInterpreter Interpreter, TestHost Host) Create() + private static (YesNtInterpreter Interpreter, TestHost Host) Create(TaskMode taskMode = TaskMode.Thread) { TestHost host = new(); - YesNtInterpreter interpreter = new() { Host = host }; + YesNtInterpreter interpreter = new() { Host = host, TaskMode = taskMode }; return (interpreter, host); } @@ -456,4 +456,83 @@ public class HostApiTests string text = WaitForText(host, "in worker"); Assert.IsFalse(text.Contains("not found"), text); } + + // --- Cooperative tasks --- + + [TestMethod] + public void CooperativeTasksRunOnTheSteppingThreadTest() + { + (YesNtInterpreter interpreter, _) = Create(TaskMode.Cooperative); + List threads = []; + interpreter.AddStatement("note_thread", SearchMode.Exact, SpaceAround.None, _ => threads.Add(Environment.CurrentManagedThreadId)); + interpreter.Prepare(["call worker task", "note_thread", "exit", "func worker:", "note_thread", "exit", "end_func"]); + + StepToEnd(interpreter); + + CollectionAssert.AreEqual(new[] { Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId }, threads); + } + + [TestMethod] + public void CooperativeTasksRunWhileTheScriptSleepsTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative); + interpreter.Prepare(["call worker task", "sleep 100", "print_line script", "exit", "func worker:", "print_line worker", "exit", "end_func"]); + + StepToEnd(interpreter); + + string text = host.Text; + StringAssert.StartsWith(text, "worker" + Environment.NewLine); + StringAssert.Contains(text, "script" + Environment.NewLine); + } + + [TestMethod] + public void CooperativeTaskSleepDoesNotHoldUpTheScriptTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative); + interpreter.Prepare(["call worker task", "print_line script", "exit", "func worker:", "sleep 100", "print_line worker", "exit", "end_func"]); + + StepToEnd(interpreter); + + StringAssert.StartsWith(host.Text, "script" + Environment.NewLine); + StringAssert.Contains(host.Text, "worker" + Environment.NewLine); + } + + [TestMethod] + public void CooperativeInterpreterRunsUntilItsTasksEndTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative); + interpreter.Prepare(["call worker task", "exit", "func worker:", "sleep 50", "print_line worker done", "exit", "end_func"]); + + _ = interpreter.Step(10); + Assert.IsTrue(interpreter.IsRunning); + StepToEnd(interpreter); + + StringAssert.Contains(host.Text, "worker done"); + } + + [TestMethod] + public void AbortAllStopsCooperativeTasksTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative); + interpreter.Prepare(["call worker task", "sleep 20", "abort_all", "func worker:", "sleep 100000", "print_line never", "exit", "end_func"]); + + StepToEnd(interpreter); + + Assert.IsFalse(host.Text.Contains("never")); + } + + [TestMethod] + public void CooperativeTaskHasCustomStatementsTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(TaskMode.Cooperative); + interpreter.RemoveStatement("length"); + interpreter.AddStatement("mark", SearchMode.Exact, SpaceAround.None, (_, context) => context.SetOut("marked")); + interpreter.Prepare(["call worker task", "sleep 50", "exit", "func worker:", "mark", "print_line %out", "length abc", "print_line escaped", "exit", "end_func"]); + + StepToEnd(interpreter); + + StringAssert.Contains(host.Text, "marked"); + StringAssert.Contains(host.Text, "Invalid statement"); + Assert.IsFalse(host.Text.Contains("escaped")); + } } diff --git a/src/YesNt.Interpreter/Runtime/TaskMode.cs b/src/YesNt.Interpreter/Runtime/TaskMode.cs new file mode 100644 index 0000000..0e5c661 --- /dev/null +++ b/src/YesNt.Interpreter/Runtime/TaskMode.cs @@ -0,0 +1,22 @@ +namespace YesNt.Interpreter.Runtime; + +/// +/// How a script's task lines run. +/// +public enum TaskMode +{ + /// + /// Each task runs on a thread of its own, at the same time as the script. A task goes on + /// after the script ends. + /// + Thread, + + /// + /// Tasks run on the thread that steps the script, taking turns with it: each step of the + /// interpreter runs a line of the script and a line of each task. For hosts that must keep + /// everything on one thread, such as a game loop or a single-threaded system. The + /// interpreter keeps running () until the script + /// and all its tasks have ended. + /// + Cooperative, +} diff --git a/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs b/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs index e125d5c..b054f6c 100644 --- a/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs +++ b/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs @@ -41,6 +41,10 @@ public class YesNtInterpreter // same ones. A step that disables a statement names it, so enabling it again drops the step. private readonly List configuration = []; + // Tasks run in turns with the script (TaskMode.Cooperative). + private readonly List tasks = []; + + // While the script itself runs (its tasks may outlast it). private bool scriptRunning; private sealed record ConfigurationStep(string DisabledName, Action Apply); @@ -59,10 +63,11 @@ public class YesNtInterpreter /// /// from the moment (or any - /// Execute overload) is called until the script finishes or is stopped. + /// Execute overload) is called until the script finishes or is stopped, and with + /// until its tasks have ended too. /// Use this to drive step/run loops: while (interpreter.IsRunning) interpreter.Step(10); /// - public bool IsRunning => scriptRunning; + public bool IsRunning => scriptRunning || tasks.Count > 0; /// /// Gets or sets the script's console and files: where output goes outside debug mode, where @@ -75,6 +80,13 @@ public class YesNtInterpreter set => runtimeInfo.Host = value ?? throw new ArgumentNullException(nameof(value)); } + /// + /// Gets or sets how the script's task lines run: each on a thread of its own (the + /// default) or taking turns with the script on the thread that steps it. Set it before the + /// script starts; its tasks use the same mode. + /// + public TaskMode TaskMode { get; set; } = TaskMode.Thread; + /// /// Initializes a new and registers all built-in statements. /// @@ -369,6 +381,7 @@ public class YesNtInterpreter runtimeInfo.Reset(); runtimeInfo.IsDebugMode = isDebugMode; scriptRunning = false; + tasks.Clear(); } /// @@ -400,10 +413,10 @@ public class YesNtInterpreter } // Starts a task: the script's lines from the task's line on, run by an interpreter with - // the same statements and host, sharing the script's global variables, on a thread of its own. + // the same statements, host and task mode, sharing the script's global variables. private void StartTask(List lines, int startLine) { - YesNtInterpreter task = new YesNtInterpreter(); + YesNtInterpreter task = new YesNtInterpreter { TaskMode = TaskMode }; task.runtimeInfo.Host = runtimeInfo.Host; foreach (ConfigurationStep step in configuration) @@ -413,7 +426,15 @@ public class YesNtInterpreter } task.PrepareTask(lines, runtimeInfo.GlobalVariables, startLine, runtimeInfo); - _ = Task.Run(task.RunToCompletion); + + if (TaskMode == TaskMode.Cooperative) + { + tasks.Add(task); + } + else + { + _ = Task.Run(task.RunToCompletion); + } } private void PrepareTask(List lines, Dictionary globalVariables, int startLine, RuntimeInformation parentRuntimeInformation) @@ -445,6 +466,8 @@ public class YesNtInterpreter /// Executes up to script lines then pauses, leaving /// so execution can be resumed later. /// Blank lines and comments are skipped transparently and do not consume the budget. + /// With , each line of the script also runs a line of + /// each of its tasks. /// /// Maximum number of executable lines to run. Defaults to 1. /// @@ -514,13 +537,34 @@ public class YesNtInterpreter } } + // A line of the script, then one of each task taking turns with it. private StepResult StepOnce() { - if (!scriptRunning) + StepResult result = scriptRunning ? StepScript() : StepResult.Finished; + + if (tasks.Count == 0) { - return StepResult.Finished; + return result; } + bool taskRan = false; + foreach (YesNtInterpreter task in tasks) + { + taskRan |= task.StepOnce() == StepResult.Continue; + } + + _ = tasks.RemoveAll(task => !task.IsRunning); + + return result switch + { + StepResult.Finished when tasks.Count == 0 => StepResult.Finished, + StepResult.Continue => StepResult.Continue, + _ => taskRan ? StepResult.Continue : StepResult.Waiting, + }; + } + + private StepResult StepScript() + { if (!runtimeInfo.TryEndWait()) { return StepResult.Waiting;