From 6ced348fbef8fbca08cc6fb32fa303e6ea7e6d5d Mon Sep 17 00:00:00 2001 From: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:41:45 +0100 Subject: [PATCH] Give tasks the script's statements, host and functions --- docs/library-api.md | 26 +++- src/YesNt.Interpreter.Tests/HostApiTests.cs | 86 +++++++++++ src/YesNt.Interpreter/Runtime/IYesNtHost.cs | 1 + .../Runtime/RuntimeInformation.cs | 6 + .../Runtime/YesNtInterpreter.cs | 145 +++++++++++++----- .../Statements/ProcessingStatements.cs | 7 +- 6 files changed, 221 insertions(+), 50 deletions(-) diff --git a/docs/library-api.md b/docs/library-api.md index 4fa3b0d..25a82c7 100644 --- a/docs/library-api.md +++ b/docs/library-api.md @@ -15,9 +15,10 @@ to embed the YesNt interpreter and run scripts programmatically. 6. [Giving the script a console and files](#giving-the-script-a-console-and-files) 7. [Adding custom statements](#adding-custom-statements) 8. [Removing and disabling built-in statements](#removing-and-disabling-built-in-statements) -9. [Stopping a script](#stopping-a-script) -10. [Reading registered statements](#reading-registered-statements) -11. [API reference](#api-reference) +9. [Tasks](#tasks) +10. [Stopping a script](#stopping-a-script) +11. [Reading registered statements](#reading-registered-statements) +12. [API reference](#api-reference) --- @@ -205,7 +206,7 @@ decides: - how script files are read: the script given to `Execute`/`Prepare`, and every file it `import`s. The default, `ConsoleHost`, uses the process's console and file system. Set `Host` before the -script starts. +script starts; tasks the script starts share it. Derive from `ConsoleHost` to change part of it, for example to check that a script may read a file before it does: @@ -448,6 +449,9 @@ interpreter.Execute(new List Restores the original handlers saved when `DisableStatement` was called. Has no effect if the statement is not currently disabled. +Tasks the script starts (`task`) get every statement added, removed, disabled and enabled +again, so removing `exec` keeps it out of tasks too. + ```csharp interpreter.DisableStatement("sleep"); // ... configure other things ... @@ -474,6 +478,20 @@ 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: + +- its statements: the built-in ones as the host left them, and the custom ones, whose + `IStatementContext` is the task's own; +- its host; +- 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. + +--- + ## Stopping a script Call `Stop()` from any thread to request graceful termination. The script stops at the next line diff --git a/src/YesNt.Interpreter.Tests/HostApiTests.cs b/src/YesNt.Interpreter.Tests/HostApiTests.cs index bea3903..9ef1eb5 100644 --- a/src/YesNt.Interpreter.Tests/HostApiTests.cs +++ b/src/YesNt.Interpreter.Tests/HostApiTests.cs @@ -370,4 +370,90 @@ public class HostApiTests Assert.AreEqual(StepResult.Finished, interpreter.Step(10)); } + + // --- Tasks inherit the script's setup --- + + // Waits for a task on its own thread to write the text (never more than a few seconds). + private static string WaitForText(TestHost host, string text) + { + DateTime giveUp = DateTime.UtcNow.AddSeconds(5); + while (!host.Text.Contains(text) && DateTime.UtcNow < giveUp) + { + Thread.Sleep(5); + } + + StringAssert.Contains(host.Text, text); + return host.Text; + } + + [TestMethod] + public void TaskHasCustomStatementsTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(); + using ManualResetEventSlim taskRan = new(); + interpreter.AddStatement("mark", SearchMode.Exact, SpaceAround.None, _ => taskRan.Set()); + + interpreter.Execute(["call worker task", "exit", "func worker:", "mark", "exit", "end_func"]); + + Assert.IsTrue(taskRan.Wait(TimeSpan.FromSeconds(3)), host.Text); + } + + [TestMethod] + public void TaskGetsItsOwnContextTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(); + interpreter.AddStatement("where", SearchMode.Exact, SpaceAround.None, (_, context) => context.SetOut(context.Variables.ContainsKey("inside") ? "task" : "script")); + + interpreter.Execute(["call worker task", "where", "print_line script sees %out", "exit", "func worker:", "var inside = 1", "where", "print_line task sees %out", "exit", "end_func"]); + + _ = WaitForText(host, "task sees task"); + StringAssert.Contains(host.Text, "script sees script"); + } + + [TestMethod] + public void TaskCannotUseARemovedStatementTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(); + interpreter.RemoveStatement("length"); + + interpreter.Execute(["call worker task", "exit", "func worker:", "length abc", "print_line escaped", "exit", "end_func"]); + + string text = WaitForText(host, "Invalid statement"); + Assert.IsFalse(text.Contains("escaped")); + } + + [TestMethod] + public void TaskKeepsADisabledStatementDisabledTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(); + interpreter.DisableStatement("print_line"); + + interpreter.Execute(["call worker task", "exit", "func worker:", "print_line from worker", "exit", "end_func"]); + + string text = WaitForText(host, "Task "); + Assert.IsFalse(text.Contains("from worker")); + } + + [TestMethod] + public void TaskHasAStatementEnabledAgainTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(); + interpreter.DisableStatement("print_line"); + interpreter.EnableStatement("print_line"); + + interpreter.Execute(["call worker task", "exit", "func worker:", "print_line from worker", "exit", "end_func"]); + + _ = WaitForText(host, "from worker"); + } + + [TestMethod] + public void TaskCallsAFunctionDefinedAboveItTest() + { + (YesNtInterpreter interpreter, TestHost host) = Create(); + + interpreter.Execute(["func worker:", "print_line in worker", "end_func", "call worker task"]); + + string text = WaitForText(host, "in worker"); + Assert.IsFalse(text.Contains("not found"), text); + } } diff --git a/src/YesNt.Interpreter/Runtime/IYesNtHost.cs b/src/YesNt.Interpreter/Runtime/IYesNtHost.cs index 2d83311..5002339 100644 --- a/src/YesNt.Interpreter/Runtime/IYesNtHost.cs +++ b/src/YesNt.Interpreter/Runtime/IYesNtHost.cs @@ -6,6 +6,7 @@ namespace YesNt.Interpreter.Runtime; /// script itself and each import). The default, , uses the /// process's console and file system; an application embedding YesNt gives its own, for /// example to show output in a window or to check a script may read a file before it does. +/// Tasks started by the script share their parent's host. /// public interface IYesNtHost { diff --git a/src/YesNt.Interpreter/Runtime/RuntimeInformation.cs b/src/YesNt.Interpreter/Runtime/RuntimeInformation.cs index e562258..c2c4e7c 100644 --- a/src/YesNt.Interpreter/Runtime/RuntimeInformation.cs +++ b/src/YesNt.Interpreter/Runtime/RuntimeInformation.cs @@ -78,6 +78,12 @@ internal sealed class RuntimeInformation : IStatementContext /// public IYesNtHost Host { get; set; } = new ConsoleHost(); + /// + /// Gets or sets how the interpreter starts a task from the given lines at the given line + /// (set by the interpreter, which knows its statements, host and task mode). + /// + internal Action, int> StartTaskAction { get; set; } + /// /// Gets what the script waits for before it goes on (, /// ); when it does not wait. diff --git a/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs b/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs index da2abe7..e125d5c 100644 --- a/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs +++ b/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using YesNt.Interpreter.Attributes; using YesNt.Interpreter.Enums; @@ -36,6 +37,14 @@ public class YesNtInterpreter private readonly List> staticStatements; private readonly Dictionary>>> disabledStatements = []; + // Every change the host made to the statements, in order, so a task's interpreter gets the + // same ones. A step that disables a statement names it, so enabling it again drops the step. + private readonly List configuration = []; + + private bool scriptRunning; + + private sealed record ConfigurationStep(string DisabledName, Action Apply); + /// /// How long (and so Execute) sleeps between looks /// while the script waits. @@ -53,12 +62,12 @@ public class YesNtInterpreter /// Execute overload) is called until the script finishes or is stopped. /// Use this to drive step/run loops: while (interpreter.IsRunning) interpreter.Step(10); /// - public bool IsRunning { get; private set; } + public bool IsRunning => scriptRunning; /// /// Gets or sets the script's console and files: where output goes outside debug mode, where /// input comes from, what clear clears and how script files are read. Defaults to - /// a . Set it before the script starts. + /// a . Set it before the script starts; its tasks share it. /// public IYesNtHost Host { @@ -74,6 +83,7 @@ public class YesNtInterpreter GeneratedStatementRegistry.Register(runtimeInfo, out statements, out staticStatements); UpdateStatementHandlers(); runtimeInfo.PreScanLinesAction = PreScanLines; + runtimeInfo.StartTaskAction = StartTask; runtimeInfo.OnDebugOutput += (s) => OnDebugOutput?.Invoke(s); runtimeInfo.OnLineExecuted += e => OnLineExecuted?.Invoke(e); @@ -100,7 +110,8 @@ public class YesNtInterpreter /// otherwise a new entry is added. Built-in statements use distinct attribute instances, so passing a /// newly constructed attribute with the same name will add a second handler rather than replacing /// the built-in. Use first to replace a built-in keyword. - /// The statement list is re-sorted by priority after insertion. + /// The statement list is re-sorted by priority after insertion. Tasks the script starts get + /// the statement too. /// /// The attribute describing the keyword, search mode, and priority. /// @@ -109,24 +120,8 @@ public class YesNtInterpreter /// public void AddStatement(StatementInformation attribute, Action handler) { - statements[attribute] = handler; - - List>> entries = [.. statements]; - entries.Sort((a, b) => - { - int cmp = a.Key.Priority.CompareTo(b.Key.Priority); - return cmp != 0 ? cmp : b.Key.Name.Length.CompareTo(a.Key.Name.Length); - }); - - statements = []; - - foreach (KeyValuePair> entry in entries) - { - statements.Add(entry.Key, entry.Value); - } - - UpdateStatementHandlers(); - PreScanLines(); + configuration.Add(new ConfigurationStep(null, interpreter => interpreter.AddStatementCore(attribute, handler))); + AddStatementCore(attribute, handler); } /// @@ -140,7 +135,9 @@ public class YesNtInterpreter /// public void AddStatement(StatementInformation attribute, Action handler) { - AddStatement(attribute, args => handler(args, runtimeInfo)); + // A task's interpreter hands the handler its own context. + configuration.Add(new ConfigurationStep(null, interpreter => interpreter.AddStatementCore(attribute, args => handler(args, interpreter.runtimeInfo)))); + AddStatementCore(attribute, args => handler(args, runtimeInfo)); } /// @@ -201,11 +198,39 @@ public class YesNtInterpreter AddStatement(new StatementInformation(name, searchMode, spaceAround, consoleColor), handler); } + private void AddStatementCore(StatementInformation attribute, Action handler) + { + statements[attribute] = handler; + + List>> entries = [.. statements]; + entries.Sort((a, b) => + { + int cmp = a.Key.Priority.CompareTo(b.Key.Priority); + return cmp != 0 ? cmp : b.Key.Name.Length.CompareTo(a.Key.Name.Length); + }); + + statements = []; + + foreach (KeyValuePair> entry in entries) + { + statements.Add(entry.Key, entry.Value); + } + + UpdateStatementHandlers(); + PreScanLines(); + } + /// /// Unregisters all handlers matching the specified keyword . /// /// The keyword to remove. public void RemoveStatement(string name) + { + configuration.Add(new ConfigurationStep(null, interpreter => interpreter.RemoveStatementCore(name))); + RemoveStatementCore(name); + } + + private void RemoveStatementCore(string name) { foreach (StatementInformation key in statements.Keys.Where(k => k.Name == name).ToList()) { @@ -224,10 +249,18 @@ public class YesNtInterpreter /// /// The keyword of the statement(s) to disable. public void DisableStatement(string name) + { + if (DisableStatementCore(name)) + { + configuration.Add(new ConfigurationStep(name, interpreter => interpreter.DisableStatementCore(name))); + } + } + + private bool DisableStatementCore(string name) { if (disabledStatements.ContainsKey(name)) { - return; + return false; } List>> matching = @@ -235,7 +268,7 @@ public class YesNtInterpreter if (matching.Count == 0) { - return; + return false; } disabledStatements[name] = matching; @@ -246,6 +279,7 @@ public class YesNtInterpreter } UpdateStatementHandlers(); PreScanLines(); + return true; } /// @@ -269,6 +303,13 @@ public class YesNtInterpreter _ = disabledStatements.Remove(name); UpdateStatementHandlers(); PreScanLines(); + + // Tasks need neither the disabling nor this. + int disabled = configuration.FindLastIndex(step => step.DisabledName == name); + if (disabled >= 0) + { + configuration.RemoveAt(disabled); + } } /// @@ -294,12 +335,8 @@ public class YesNtInterpreter /// The script may not be read. public void Prepare(string path, bool isDebugMode = false) { - runtimeInfo.Reset(); - runtimeInfo.IsDebugMode = isDebugMode; - if (LoadFile(path)) - { - IsRunning = true; - } + PrepareRun(isDebugMode); + scriptRunning = LoadFile(path); } /// @@ -314,8 +351,7 @@ public class YesNtInterpreter /// public void Prepare(IEnumerable lines, bool isDebugMode = false) { - runtimeInfo.Reset(); - runtimeInfo.IsDebugMode = isDebugMode; + PrepareRun(isDebugMode); int i = 0; foreach (string line in lines) @@ -325,7 +361,14 @@ public class YesNtInterpreter } PreScanLines(); - IsRunning = true; + scriptRunning = true; + } + + private void PrepareRun(bool isDebugMode) + { + runtimeInfo.Reset(); + runtimeInfo.IsDebugMode = isDebugMode; + scriptRunning = false; } /// @@ -356,15 +399,38 @@ public class YesNtInterpreter RunToCompletion(); } - internal void Execute(List lines, Dictionary globalVariables, int startLine, RuntimeInformation parentRuntimeInformation) + // 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. + private void StartTask(List lines, int startLine) { - runtimeInfo.Reset(); - runtimeInfo.IsDebugMode = parentRuntimeInformation.IsDebugMode; + YesNtInterpreter task = new YesNtInterpreter(); + task.runtimeInfo.Host = runtimeInfo.Host; + + foreach (ConfigurationStep step in configuration) + { + step.Apply(task); + task.configuration.Add(step); + } + + task.PrepareTask(lines, runtimeInfo.GlobalVariables, startLine, runtimeInfo); + _ = Task.Run(task.RunToCompletion); + } + + private void PrepareTask(List lines, Dictionary globalVariables, int startLine, RuntimeInformation parentRuntimeInformation) + { + PrepareRun(parentRuntimeInformation.IsDebugMode); runtimeInfo.Lines = lines; runtimeInfo.LineNumber = startLine; runtimeInfo.ParentRuntimeInformation = parentRuntimeInformation; runtimeInfo.GlobalVariables = globalVariables; + // The task's lines are a copy of the script's, so the functions the script already + // passed are at the same lines; without them the task could only call functions below it. + foreach (KeyValuePair function in parentRuntimeInformation.Functions) + { + runtimeInfo.Functions[function.Key] = function.Value; + } + if (parentRuntimeInformation.StopAllTasks) { runtimeInfo.Exit(ExitMessages.TerminatedByParentTask, parentRuntimeInformation.StopAllTasks); @@ -372,8 +438,7 @@ public class YesNtInterpreter } PreScanLines(); - IsRunning = true; - RunToCompletion(); + scriptRunning = true; } /// @@ -451,7 +516,7 @@ public class YesNtInterpreter private StepResult StepOnce() { - if (!IsRunning) + if (!scriptRunning) { return StepResult.Finished; } @@ -582,7 +647,7 @@ public class YesNtInterpreter private StepResult FinishExecution() { - IsRunning = false; + scriptRunning = false; if (!runtimeInfo.Stop) { diff --git a/src/YesNt.Interpreter/Statements/ProcessingStatements.cs b/src/YesNt.Interpreter/Statements/ProcessingStatements.cs index b63fdfe..d53fe0a 100644 --- a/src/YesNt.Interpreter/Statements/ProcessingStatements.cs +++ b/src/YesNt.Interpreter/Statements/ProcessingStatements.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; -using System.Threading.Tasks; using YesNt.Interpreter.Attributes; using YesNt.Interpreter.Enums; @@ -35,11 +34,7 @@ internal partial class ProcessingStatements : StatementRuntimeInformation Line oldLine = lines[lineNumber]; lines[lineNumber] = new Line(line, oldLine.FileName, oldLine.LineNumber); - _ = Task.Run(() => - { - YesNtInterpreter interpreter = new YesNtInterpreter(); - interpreter.Execute(lines, RuntimeInfo.GlobalVariables, lineNumber, RuntimeInfo); - }); + RuntimeInfo.StartTaskAction(lines, lineNumber); RuntimeInfo.CurrentLine = string.Empty; }