mirror of
https://github.com/Stone-Red-Code/YesNt-Interpreter.git
synced 2026-11-26 07:18:29 +01:00
Give tasks the script's statements, host and functions
This commit is contained in:
+22
-4
@@ -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<string>
|
||||
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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace YesNt.Interpreter.Runtime;
|
||||
/// script itself and each <c>import</c>). The default, <see cref="ConsoleHost"/>, 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.
|
||||
/// </summary>
|
||||
public interface IYesNtHost
|
||||
{
|
||||
|
||||
@@ -78,6 +78,12 @@ internal sealed class RuntimeInformation : IStatementContext
|
||||
/// </summary>
|
||||
public IYesNtHost Host { get; set; } = new ConsoleHost();
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
internal Action<List<Line>, int> StartTaskAction { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets what the script waits for before it goes on (<see cref="WaitUntil"/>,
|
||||
/// <see cref="RetryLine"/>); <see langword="null"/> when it does not wait.
|
||||
|
||||
@@ -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<KeyValuePair<StaticStatementInformation, Action>> staticStatements;
|
||||
private readonly Dictionary<string, List<KeyValuePair<StatementInformation, Action<string>>>> 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<ConfigurationStep> configuration = [];
|
||||
|
||||
private bool scriptRunning;
|
||||
|
||||
private sealed record ConfigurationStep(string DisabledName, Action<YesNtInterpreter> Apply);
|
||||
|
||||
/// <summary>
|
||||
/// How long <see cref="RunToCompletion"/> (and so <c>Execute</c>) sleeps between looks
|
||||
/// while the script waits.
|
||||
@@ -53,12 +62,12 @@ public class YesNtInterpreter
|
||||
/// <c>Execute</c> overload) is called until the script finishes or is stopped.
|
||||
/// Use this to drive step/run loops: <c>while (interpreter.IsRunning) interpreter.Step(10);</c>
|
||||
/// </summary>
|
||||
public bool IsRunning { get; private set; }
|
||||
public bool IsRunning => scriptRunning;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the script's console and files: where output goes outside debug mode, where
|
||||
/// input comes from, what <c>clear</c> clears and how script files are read. Defaults to
|
||||
/// a <see cref="ConsoleHost"/>. Set it before the script starts.
|
||||
/// a <see cref="ConsoleHost"/>. Set it before the script starts; its tasks share it.
|
||||
/// </summary>
|
||||
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 <b>add</b> a second handler rather than replacing
|
||||
/// the built-in. Use <see cref="RemoveStatement"/> 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.
|
||||
/// </summary>
|
||||
/// <param name="attribute">The attribute describing the keyword, search mode, and priority.</param>
|
||||
/// <param name="handler">
|
||||
@@ -109,24 +120,8 @@ public class YesNtInterpreter
|
||||
/// </param>
|
||||
public void AddStatement(StatementInformation attribute, Action<string> handler)
|
||||
{
|
||||
statements[attribute] = handler;
|
||||
|
||||
List<KeyValuePair<StatementInformation, Action<string>>> 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<StatementInformation, Action<string>> entry in entries)
|
||||
{
|
||||
statements.Add(entry.Key, entry.Value);
|
||||
}
|
||||
|
||||
UpdateStatementHandlers();
|
||||
PreScanLines();
|
||||
configuration.Add(new ConfigurationStep(null, interpreter => interpreter.AddStatementCore(attribute, handler)));
|
||||
AddStatementCore(attribute, handler);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -140,7 +135,9 @@ public class YesNtInterpreter
|
||||
/// </param>
|
||||
public void AddStatement(StatementInformation attribute, Action<string, IStatementContext> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -201,11 +198,39 @@ public class YesNtInterpreter
|
||||
AddStatement(new StatementInformation(name, searchMode, spaceAround, consoleColor), handler);
|
||||
}
|
||||
|
||||
private void AddStatementCore(StatementInformation attribute, Action<string> handler)
|
||||
{
|
||||
statements[attribute] = handler;
|
||||
|
||||
List<KeyValuePair<StatementInformation, Action<string>>> 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<StatementInformation, Action<string>> entry in entries)
|
||||
{
|
||||
statements.Add(entry.Key, entry.Value);
|
||||
}
|
||||
|
||||
UpdateStatementHandlers();
|
||||
PreScanLines();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters all handlers matching the specified keyword <paramref name="name"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">The keyword to remove.</param>
|
||||
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
|
||||
/// </summary>
|
||||
/// <param name="name">The keyword of the statement(s) to disable.</param>
|
||||
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<KeyValuePair<StatementInformation, Action<string>>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -294,12 +335,8 @@ public class YesNtInterpreter
|
||||
/// <exception cref="UnauthorizedAccessException">The script may not be read.</exception>
|
||||
public void Prepare(string path, bool isDebugMode = false)
|
||||
{
|
||||
runtimeInfo.Reset();
|
||||
runtimeInfo.IsDebugMode = isDebugMode;
|
||||
if (LoadFile(path))
|
||||
{
|
||||
IsRunning = true;
|
||||
}
|
||||
PrepareRun(isDebugMode);
|
||||
scriptRunning = LoadFile(path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -314,8 +351,7 @@ public class YesNtInterpreter
|
||||
/// </param>
|
||||
public void Prepare(IEnumerable<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -356,15 +399,38 @@ public class YesNtInterpreter
|
||||
RunToCompletion();
|
||||
}
|
||||
|
||||
internal void Execute(List<Line> lines, Dictionary<string, string> 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<Line> 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<Line> lines, Dictionary<string, string> 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<string, int> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user