diff --git a/docs/library-api.md b/docs/library-api.md index 3c8c539..4a51037 100644 --- a/docs/library-api.md +++ b/docs/library-api.md @@ -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 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 { 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. | diff --git a/src/YesNt.Interpreter.Tests/HostApiTests.cs b/src/YesNt.Interpreter.Tests/HostApiTests.cs new file mode 100644 index 0000000..89aef75 --- /dev/null +++ b/src/YesNt.Interpreter.Tests/HostApiTests.cs @@ -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; + +/// +/// Tests for what an embedding application gives and gets through the interpreter's API. +/// +[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 Lines { get; } = new(); + public Queue Keys { get; } = new(); + public Dictionary Files { get; } = new(StringComparer.OrdinalIgnoreCase); + public HashSet 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"); + } +} diff --git a/src/YesNt.Interpreter/Runtime/ConsoleHost.cs b/src/YesNt.Interpreter/Runtime/ConsoleHost.cs new file mode 100644 index 0000000..c245d76 --- /dev/null +++ b/src/YesNt.Interpreter/Runtime/ConsoleHost.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; + +namespace YesNt.Interpreter.Runtime; + +/// +/// The default : the process's console and file system. Derive from it +/// to change only part, for example to check permissions in . +/// +public class ConsoleHost : IYesNtHost +{ + /// + public virtual void Write(string text) + { + Console.Write(text); + } + + /// + /// Waits for a line on the console. The end of the console's input ends the script. + /// + /// + public virtual InputStatus TryReadLine(out string line) + { + line = Console.ReadLine(); + return line is null ? InputStatus.Closed : InputStatus.Ready; + } + + /// + /// Takes a key if one was pressed, without waiting. + /// + /// + 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; + } + + /// Clears the console, unless it is not interactive. + /// + public virtual void Clear() + { + try + { + Console.Clear(); + } + catch (IOException) + { + // Silently fail if the console is not interactive + } + } + + /// + public virtual string[] ReadScript(string path) + { + return File.ReadAllLines(path); + } +} diff --git a/src/YesNt.Interpreter/Runtime/IYesNtHost.cs b/src/YesNt.Interpreter/Runtime/IYesNtHost.cs new file mode 100644 index 0000000..09dec20 --- /dev/null +++ b/src/YesNt.Interpreter/Runtime/IYesNtHost.cs @@ -0,0 +1,62 @@ +namespace YesNt.Interpreter.Runtime; + +/// +/// What a script's console and files are: where its output goes, where %read_line and +/// %read_key read from, what clear clears, and how script files are read (the +/// 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. +/// +public interface IYesNtHost +{ + /// + /// Writes output, as plain text. A line's end is part of it. Not called in debug mode, + /// where output goes to instead. + /// + /// The text to write. + void Write(string text); + + /// + /// Takes a line the user entered, for %read_line. Return + /// 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. + /// + /// The line, without its end, when the result is . + /// Whether there is a line, none yet, or no more input (which ends the script). + InputStatus TryReadLine(out string line); + + /// + /// Takes a key the user pressed, for %read_key, the same way as . + /// + /// The key's character when the result is . + /// Whether there is a key, none yet, or no more input (which ends the script). + InputStatus TryReadKey(out char key); + + /// Clears the output, for clear. + void Clear(); + + /// + /// Reads a script file's lines: the script given to the interpreter and each file it + /// imports. Throw when there is no such file; + /// any other or + /// means it could not be read. + /// + /// The file's full path. + /// The file's lines. + string[] ReadScript(string path); +} + +/// +/// Whether a host has the input a script asked for. +/// +public enum InputStatus +{ + /// The input is there. + Ready, + + /// Not yet: the script waits and asks again. + Pending, + + /// There will be no more input: the script ends. + Closed, +} diff --git a/src/YesNt.Interpreter/Runtime/RuntimeInformation.cs b/src/YesNt.Interpreter/Runtime/RuntimeInformation.cs index c058f79..97b55a1 100644 --- a/src/YesNt.Interpreter/Runtime/RuntimeInformation.cs +++ b/src/YesNt.Interpreter/Runtime/RuntimeInformation.cs @@ -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; } + /// + /// Gets or sets the script's console and files. Kept by : it belongs to + /// the interpreter, not to one run. + /// + 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()); } } diff --git a/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs b/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs index 1745131..39a6d8e 100644 --- a/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs +++ b/src/YesNt.Interpreter/Runtime/YesNtInterpreter.cs @@ -48,6 +48,17 @@ public class YesNtInterpreter /// public bool IsRunning { get; private set; } + /// + /// 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. + /// + public IYesNtHost Host + { + get => runtimeInfo.Host; + set => runtimeInfo.Host = value ?? throw new ArgumentNullException(nameof(value)); + } + /// /// Initializes a new and registers all built-in statements. /// @@ -272,6 +283,8 @@ public class YesNtInterpreter /// When , output is routed through instead of /// and line-execution events are raised via . /// + /// The script could not be read (). + /// The script may not be read. 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++) diff --git a/src/YesNt.Interpreter/Statements/ConsoleStatements.cs b/src/YesNt.Interpreter/Statements/ConsoleStatements.cs index bc9ec62..0ab74d5 100644 --- a/src/YesNt.Interpreter/Statements/ConsoleStatements.cs +++ b/src/YesNt.Interpreter/Statements/ConsoleStatements.cs @@ -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(); } } \ No newline at end of file diff --git a/src/YesNt.Interpreter/Statements/ProcessingStatements.cs b/src/YesNt.Interpreter/Statements/ProcessingStatements.cs index c94aa83..4deab21 100644 --- a/src/YesNt.Interpreter/Statements/ProcessingStatements.cs +++ b/src/YesNt.Interpreter/Statements/ProcessingStatements.cs @@ -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*+().,^%/-]+")] diff --git a/src/YesNt.Interpreter/Utilities/ConsoleExtensions.cs b/src/YesNt.Interpreter/Utilities/ConsoleExtensions.cs index f401e52..28a5ad6 100644 --- a/src/YesNt.Interpreter/Utilities/ConsoleExtensions.cs +++ b/src/YesNt.Interpreter/Utilities/ConsoleExtensions.cs @@ -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();