Give the interpreter a host for its console and files

This commit is contained in:
Stone_Red
2026-11-25 14:24:16 +01:00
parent a0f88fc3ff
commit f5b40002b9
9 changed files with 528 additions and 70 deletions
+109 -5
View File
@@ -12,11 +12,12 @@ to embed the YesNt interpreter and run scripts programmatically.
3. [Running an in-memory script](#running-an-in-memory-script)
4. [Stepwise and time-budgeted execution](#stepwise-and-time-budgeted-execution)
5. [Capturing output (debug mode)](#capturing-output-debug-mode)
6. [Adding custom statements](#adding-custom-statements)
7. [Removing and disabling built-in statements](#removing-and-disabling-built-in-statements)
8. [Stopping a script](#stopping-a-script)
9. [Reading registered statements](#reading-registered-statements)
10. [API reference](#api-reference)
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)
---
@@ -168,6 +169,78 @@ Console.Write(output);
`OnLineExecuted` is invoked with `null` only when execution reaches end-of-file (EOF).
If execution stops via `exit`, `throw`, `error`, or `Stop()`, no terminal `null` event is emitted.
To show output somewhere else without debug mode, give the interpreter a host instead (next section).
---
## Giving the script a console and files
Outside debug mode a script's console and files are its **host**, an `IYesNtHost`. The host
decides:
- where `print` and `print_line` write;
- where `%read_line` and `%read_key` read from;
- what `clear` clears;
- 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.
Derive from `ConsoleHost` to change part of it, for example to check that a script may read a
file before it does:
```csharp
sealed class SandboxedHost(string root) : ConsoleHost
{
public override string[] ReadScript(string path)
{
if (!Path.GetFullPath(path).StartsWith(root, StringComparison.OrdinalIgnoreCase))
throw new UnauthorizedAccessException(path); // import ends with "Could not load file"
return base.ReadScript(path);
}
}
var interpreter = new YesNtInterpreter { Host = new SandboxedHost(@"C:\scripts\") };
```
Or implement `IYesNtHost` to put the script in a window. Input need not be there yet: return
`InputStatus.Pending` and the interpreter asks again shortly. `InputStatus.Closed` ends the
script.
```csharp
sealed class WindowHost(TextBox output, ConcurrentQueue<string> typedLines) : IYesNtHost
{
public void Write(string text) => output.AppendText(text);
public InputStatus TryReadLine(out string line)
{
return typedLines.TryDequeue(out line) ? InputStatus.Ready : InputStatus.Pending;
}
public InputStatus TryReadKey(out char key)
{
key = default;
if (!typedLines.TryDequeue(out string line))
return InputStatus.Pending;
key = line.Length > 0 ? line[0] : ' ';
return InputStatus.Ready;
}
public void Clear() => output.Clear();
public string[] ReadScript(string path) => File.ReadAllLines(path);
}
```
`ReadScript` throws:
- `FileNotFoundException` for a file that is not there. A missing script does not start; a
missing import ends the script with "Could not find file".
- any other `IOException`, or `UnauthorizedAccessException`, for a file that cannot be read.
The script ends with "Could not load file".
---
## Adding custom statements
@@ -461,6 +534,9 @@ public ReadOnlyCollection<StatementInformation> StatementInformation { get; }
// Whether a prepared script is currently active/running
public bool IsRunning { get; }
// The script's console and files (default: ConsoleHost); set before the script starts
public IYesNtHost Host { get; set; }
```
---
@@ -497,3 +573,31 @@ Returned by `Step` and `RunFor` to indicate the outcome of the incremental execu
| `Continue` | A line was executed and more lines remain. |
| `Paused` | The step or time budget was exhausted before the script ended. |
| `Finished` | The script ran to completion (or terminated/exited). |
---
### `IYesNtHost` and `ConsoleHost`
```csharp
public interface IYesNtHost // YesNt.Interpreter.Runtime
{
void Write(string text); // output outside debug mode, line ends included
InputStatus TryReadLine(out string line); // %read_line
InputStatus TryReadKey(out char key); // %read_key
void Clear(); // clear
string[] ReadScript(string path); // the script and its imports
}
public class ConsoleHost : IYesNtHost // the default; every member is virtual
```
`ConsoleHost.TryReadLine` waits for a console line. `TryReadKey` returns `Pending` until a key
is pressed.
### `InputStatus`
| Value | Description |
| --------- | ------------------------------------------------- |
| `Ready` | The input is there. |
| `Pending` | Not yet: the interpreter asks again. |
| `Closed` | There will be no more input: the script ends. |
+195
View File
@@ -0,0 +1,195 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using YesNt.Interpreter.Runtime;
namespace YesNt.Interpreter.Tests;
/// <summary>
/// Tests for what an embedding application gives and gets through the interpreter's API.
/// </summary>
[TestClass]
public class HostApiTests
{
// A console and file system in memory. A null line or key in the queue is "not yet".
private sealed class TestHost : IYesNtHost
{
public StringBuilder Output { get; } = new();
public Queue<string?> Lines { get; } = new();
public Queue<char?> Keys { get; } = new();
public Dictionary<string, string[]> Files { get; } = new(StringComparer.OrdinalIgnoreCase);
public HashSet<string> Forbidden { get; } = new(StringComparer.OrdinalIgnoreCase);
public int Clears { get; private set; }
public void Write(string text)
{
lock (Output)
{
_ = Output.Append(text);
}
}
public InputStatus TryReadLine(out string line)
{
line = string.Empty;
if (Lines.Count == 0)
{
return InputStatus.Closed;
}
string? next = Lines.Dequeue();
if (next is null)
{
return InputStatus.Pending;
}
line = next;
return InputStatus.Ready;
}
public InputStatus TryReadKey(out char key)
{
key = default;
if (Keys.Count == 0)
{
return InputStatus.Closed;
}
char? next = Keys.Dequeue();
if (next is null)
{
return InputStatus.Pending;
}
key = next.Value;
return InputStatus.Ready;
}
public void Clear()
{
Clears++;
}
public string[] ReadScript(string path)
{
string name = Path.GetFileName(path);
if (Forbidden.Contains(name))
{
throw new UnauthorizedAccessException(name);
}
return Files.TryGetValue(name, out string[]? lines) ? lines : throw new FileNotFoundException(name);
}
public string Text
{
get
{
lock (Output)
{
return Output.ToString();
}
}
}
}
private static (YesNtInterpreter Interpreter, TestHost Host) Create()
{
TestHost host = new();
YesNtInterpreter interpreter = new() { Host = host };
return (interpreter, host);
}
// --- Host ---
[TestMethod]
public void OutputGoesToTheHostTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create();
interpreter.Execute(["print hello ", "print_line world"]);
StringAssert.StartsWith(host.Text, "helloworld" + Environment.NewLine);
}
[TestMethod]
public void ClearClearsTheHostTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create();
interpreter.Execute(["clear"]);
Assert.AreEqual(1, host.Clears);
}
[TestMethod]
public void ScriptAndImportsAreReadThroughTheHostTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create();
host.Files["main.ynt"] = ["import lib", "print_line ${greeting}"];
host.Files["lib.ynt"] = ["var greeting = from lib"];
interpreter.Execute("main.ynt");
StringAssert.StartsWith(host.Text, "from lib" + Environment.NewLine);
}
[TestMethod]
public void MissingScriptDoesNotRunTest()
{
(YesNtInterpreter interpreter, _) = Create();
interpreter.Prepare("missing.ynt");
Assert.IsFalse(interpreter.IsRunning);
}
[TestMethod]
public void MissingImportEndsTheScriptTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create();
interpreter.Execute(["import missing"]);
StringAssert.Contains(host.Text, "Could not find file");
}
[TestMethod]
public void ForbiddenImportEndsTheScriptTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create();
host.Files["secret.ynt"] = ["print_line leaked"];
_ = host.Forbidden.Add("secret.ynt");
interpreter.Execute(["import secret"]);
Assert.IsFalse(host.Text.Contains("leaked"));
StringAssert.Contains(host.Text, "Could not load file");
}
[TestMethod]
public void ReadLineTakesTheHostsLineTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create();
host.Lines.Enqueue("Ada");
interpreter.Execute(["var name = %read_line", "print_line Hello ${name}"]);
StringAssert.StartsWith(host.Text, "Hello Ada" + Environment.NewLine);
}
[TestMethod]
public void ClosedInputEndsTheScriptTest()
{
(YesNtInterpreter interpreter, TestHost host) = Create();
interpreter.Execute(["var name = %read_line", "print_line not reached"]);
Assert.IsFalse(host.Text.Contains("not reached"));
StringAssert.Contains(host.Text, "Terminated by external process");
}
}
@@ -0,0 +1,79 @@
using System;
using System.IO;
namespace YesNt.Interpreter.Runtime;
/// <summary>
/// The default <see cref="IYesNtHost"/>: the process's console and file system. Derive from it
/// to change only part, for example to check permissions in <see cref="ReadScript"/>.
/// </summary>
public class ConsoleHost : IYesNtHost
{
/// <inheritdoc/>
public virtual void Write(string text)
{
Console.Write(text);
}
/// <summary>
/// Waits for a line on the console. The end of the console's input ends the script.
/// </summary>
/// <inheritdoc/>
public virtual InputStatus TryReadLine(out string line)
{
line = Console.ReadLine();
return line is null ? InputStatus.Closed : InputStatus.Ready;
}
/// <summary>
/// Takes a key if one was pressed, without waiting.
/// </summary>
/// <inheritdoc/>
public virtual InputStatus TryReadKey(out char key)
{
key = default;
try
{
if (!Console.KeyAvailable)
{
return InputStatus.Pending;
}
}
catch (InvalidOperationException)
{
// Redirected input has no keys: read a character instead.
int read = Console.Read();
if (read < 0)
{
return InputStatus.Closed;
}
key = (char)read;
return InputStatus.Ready;
}
key = Console.ReadKey().KeyChar;
return InputStatus.Ready;
}
/// <summary>Clears the console, unless it is not interactive.</summary>
/// <inheritdoc/>
public virtual void Clear()
{
try
{
Console.Clear();
}
catch (IOException)
{
// Silently fail if the console is not interactive
}
}
/// <inheritdoc/>
public virtual string[] ReadScript(string path)
{
return File.ReadAllLines(path);
}
}
@@ -0,0 +1,62 @@
namespace YesNt.Interpreter.Runtime;
/// <summary>
/// What a script's console and files are: where its output goes, where <c>%read_line</c> and
/// <c>%read_key</c> read from, what <c>clear</c> clears, and how script files are read (the
/// 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.
/// </summary>
public interface IYesNtHost
{
/// <summary>
/// Writes output, as plain text. A line's end is part of it. Not called in debug mode,
/// where output goes to <see cref="YesNtInterpreter.OnDebugOutput"/> instead.
/// </summary>
/// <param name="text">The text to write.</param>
void Write(string text);
/// <summary>
/// Takes a line the user entered, for <c>%read_line</c>. Return
/// <see cref="InputStatus.Pending"/> while there is none yet: the interpreter asks again
/// shortly. A host whose input is a blocking console may simply wait for the line instead.
/// </summary>
/// <param name="line">The line, without its end, when the result is <see cref="InputStatus.Ready"/>.</param>
/// <returns>Whether there is a line, none yet, or no more input (which ends the script).</returns>
InputStatus TryReadLine(out string line);
/// <summary>
/// Takes a key the user pressed, for <c>%read_key</c>, the same way as <see cref="TryReadLine"/>.
/// </summary>
/// <param name="key">The key's character when the result is <see cref="InputStatus.Ready"/>.</param>
/// <returns>Whether there is a key, none yet, or no more input (which ends the script).</returns>
InputStatus TryReadKey(out char key);
/// <summary>Clears the output, for <c>clear</c>.</summary>
void Clear();
/// <summary>
/// Reads a script file's lines: the script given to the interpreter and each file it
/// imports. Throw <see cref="System.IO.FileNotFoundException"/> when there is no such file;
/// any other <see cref="System.IO.IOException"/> or
/// <see cref="System.UnauthorizedAccessException"/> means it could not be read.
/// </summary>
/// <param name="path">The file's full path.</param>
/// <returns>The file's lines.</returns>
string[] ReadScript(string path);
}
/// <summary>
/// Whether a host has the input a script asked for.
/// </summary>
public enum InputStatus
{
/// <summary>The input is there.</summary>
Ready,
/// <summary>Not yet: the script waits and asks again.</summary>
Pending,
/// <summary>There will be no more input: the script ends.</summary>
Closed,
}
@@ -72,6 +72,12 @@ internal sealed class RuntimeInformation : IStatementContext
public bool IsSearching => !string.IsNullOrWhiteSpace(SearchLabel + SearchFunction) || (IsInFunction && FunctionCallStack.Count == 0);
public bool IsLocalSearch { get; set; }
/// <summary>
/// Gets or sets the script's console and files. Kept by <see cref="Reset"/>: it belongs to
/// the interpreter, not to one run.
/// </summary>
public IYesNtHost Host { get; set; } = new ConsoleHost();
public void WriteLine(string output, bool forceWrite = false)
{
if ((Stop && !forceWrite) || (ParentRuntimeInformation?.StopAllTasks == true && !forceWrite))
@@ -92,7 +98,7 @@ internal sealed class RuntimeInformation : IStatementContext
}
else
{
Console.WriteLine(output.FromSafeString());
Host.Write(output.FromSafeString() + Environment.NewLine);
}
}
@@ -116,7 +122,7 @@ internal sealed class RuntimeInformation : IStatementContext
}
else
{
Console.Write(output.FromSafeString());
Host.Write(output.FromSafeString());
}
}
@@ -48,6 +48,17 @@ public class YesNtInterpreter
/// </summary>
public bool IsRunning { get; private set; }
/// <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.
/// </summary>
public IYesNtHost Host
{
get => runtimeInfo.Host;
set => runtimeInfo.Host = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Initializes a new <see cref="YesNtInterpreter"/> and registers all built-in statements.
/// </summary>
@@ -272,6 +283,8 @@ public class YesNtInterpreter
/// When <see langword="true"/>, output is routed through <see cref="OnDebugOutput"/> instead of
/// <see cref="Console"/> and line-execution events are raised via <see cref="OnLineExecuted"/>.
/// </param>
/// <exception cref="IOException">The script could not be read (<see cref="IYesNtHost.ReadScript"/>).</exception>
/// <exception cref="UnauthorizedAccessException">The script may not be read.</exception>
public void Prepare(string path, bool isDebugMode = false)
{
runtimeInfo.Reset();
@@ -575,13 +588,16 @@ public class YesNtInterpreter
{
path = Path.GetFullPath(path);
if (!File.Exists(path))
string[] lines;
try
{
lines = runtimeInfo.Host.ReadScript(path);
}
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
{
return false;
}
string[] lines = File.ReadAllLines(path);
runtimeInfo.WorkingDirectory = Path.GetDirectoryName(path);
for (int i = 0; i < lines.Length; i++)
@@ -1,6 +1,5 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using YesNt.Interpreter.Attributes;
using YesNt.Interpreter.Enums;
@@ -32,43 +31,53 @@ internal class ConsoleStatements : StatementRuntimeInformation
[Statement("%read_line", SearchMode.Contains, SpaceAround.None, ConsoleColor.DarkGreen, KeepStatementInArgs = true, Priority = Priority.Highest)]
public void ReadLine(string args)
{
args += " ";
while (args.Contains("%read_line"))
{
string input = Console.ReadLine();
if (input is null)
{
RuntimeInfo.Exit(ExitMessages.TerminatedByExternalProcess, true);
return;
}
args = args.ReplaceFirstOccurrence("%read_line", input.ToSafeString());
}
RuntimeInfo.CurrentLine = args.TrimEnd();
SubstituteInput(args, "%read_line", (IYesNtHost host, out string input) => host.TryReadLine(out input));
}
[Statement("%read_key", SearchMode.Contains, SpaceAround.None, ConsoleColor.DarkGreen, KeepStatementInArgs = true, Priority = Priority.Highest)]
public void ReadKey(string args)
{
args += " ";
while (args.Contains("%read_key"))
SubstituteInput(args, "%read_key", (IYesNtHost host, out string input) =>
{
string input = ConsoleExtensions.ReadKey(RuntimeInfo).ToString();
args = args.ReplaceFirstOccurrence("%read_key", input.ToSafeString());
}
RuntimeInfo.CurrentLine = args.TrimEnd();
InputStatus status = host.TryReadKey(out char key);
input = key.ToString();
return status;
});
}
[Statement("clear", SearchMode.Exact, SpaceAround.None, ConsoleColor.Magenta)]
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Won't work if static")]
public void Clear(string _)
{
try
RuntimeInfo.Host.Clear();
}
private delegate InputStatus InputReader(IYesNtHost host, out string input);
// Puts input in place of each token, in order, asking the host again until it has some.
private void SubstituteInput(string args, string token, InputReader read)
{
args += " ";
while (args.Contains(token))
{
Console.Clear();
}
catch (IOException)
{
// Silently fail if the console is not interactive
switch (read(RuntimeInfo.Host, out string input))
{
case InputStatus.Ready:
args = args.ReplaceFirstOccurrence(token, input.ToSafeString());
break;
case InputStatus.Pending:
if (RuntimeInfo.Stop)
{
return;
}
Thread.Sleep(10);
break;
default:
RuntimeInfo.Exit(ExitMessages.TerminatedByExternalProcess, true);
return;
}
}
RuntimeInfo.CurrentLine = args.TrimEnd();
}
}
@@ -76,29 +76,30 @@ internal partial class ProcessingStatements : StatementRuntimeInformation
path = Path.ChangeExtension(path, "ynt");
}
if (File.Exists(path))
string[] lines;
try
{
try
{
RuntimeInfo.Lines.RemoveAt(RuntimeInfo.LineNumber);
string[] lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length; i++)
{
RuntimeInfo.Lines.Insert(RuntimeInfo.LineNumber + i, new Line(lines[i], Path.GetFileName(path), i));
}
RuntimeInfo.PreScanLinesAction?.Invoke();
RuntimeInfo.LineNumber--;
}
catch
{
RuntimeInfo.Exit(ExitMessages.CouldNotLoadFile(path), true);
}
lines = RuntimeInfo.Host.ReadScript(path);
}
else
catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException)
{
RuntimeInfo.Exit(ExitMessages.CouldNotFindFile(path), true);
return;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
RuntimeInfo.Exit(ExitMessages.CouldNotLoadFile(path), true);
return;
}
RuntimeInfo.Lines.RemoveAt(RuntimeInfo.LineNumber);
for (int i = 0; i < lines.Length; i++)
{
RuntimeInfo.Lines.Insert(RuntimeInfo.LineNumber + i, new Line(lines[i], Path.GetFileName(path), i));
}
RuntimeInfo.PreScanLinesAction?.Invoke();
RuntimeInfo.LineNumber--;
}
[GeneratedRegex("[0-9*+().,^%/-]+[0-9*+ ().,^%/-]+[0-9*+().,^%/-]+")]
@@ -1,5 +1,4 @@
using System;
using System.Diagnostics;
using System.Diagnostics;
using System.Threading;
using YesNt.Interpreter.Runtime;
@@ -8,19 +7,6 @@ namespace YesNt.Interpreter.Utilities;
internal static class ConsoleExtensions
{
public static char ReadKey(RuntimeInformation runtimeInformation)
{
while (!runtimeInformation.Stop)
{
if (Console.KeyAvailable)
{
return Console.ReadKey().KeyChar;
}
Thread.Sleep(10);
}
return ' ';
}
public static void Sleep(int millisecondsTimeout, RuntimeInformation runtimeInformation)
{
Stopwatch stopwatch = new Stopwatch();