tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Add --dotnet-settings, tazel dotnet get and tazel dotnet what-is
- Commit
09e8b01802daa80969026b219048dbac6ca42620- Author
- Leitwolf11 ·
- Parents
5441213294ad
Changes
CHANGELOG.md | 5 + docs/commands.md | 36 +++ src/Progmasoft.Tazel/Cli/CommandLine.cs | 60 +++- src/Progmasoft.Tazel/Cli/Commands.cs | 24 ++ src/Progmasoft.Tazel/Cli/Help.cs | 23 +- src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs | 52 +++- src/Progmasoft.Tazel/Output/ErrorCodes.cs | 13 + src/Progmasoft.Tazel/Program.cs | 26 ++ src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs | 77 +++++ src/Progmasoft.Tazel/Runtime/DotnetSettings.cs | 343 +++++++++++++++++++++ .../Progmasoft.Tazel.Tests/DotnetSettingsTests.cs | 244 +++++++++++++++ 11 files changed, 895 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbdc28f..bae4e8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ ## Unreleased +- `--dotnet-settings Name=Value[,...]` and `dotnet-settings: [ ... ];` in `tazel_options.txt` set the .NET runtime of + the Tazel process: the GC heap hard limits (in bytes or percent, whole or per object heap), the GC latency mode, and + the thread pool's minimum and maximum threads. `tazel dotnet get <setting>` reads them; `tazel dotnet what-is <term>` + explains fourteen terms of .NET offline. Errors `E0213` and `E0506`. + - `tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` take directives: `.include "file"` and `.include <file>` (below `$TAZEL_HOME/Include/`), `.import`, `.pragma once`, and `.if`, `.elif`, `.else`, `.end` on conditions over `host_system`, `target_system`, `defined("NAME")` and `env("NAME")`. `tazel_options.txt` chooses the diff --git a/docs/commands.md b/docs/commands.md index 27ba531..e660dd8 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -36,6 +36,7 @@ A misspelt command, option or value gets a hint that keeps how it was written: ` | `--progress always\|auto\|never` | all | the `[done/total]` counter of a build | | `--quiet` | all | only problems and the output of what was run | | `--message-format rich-stdio\|script-friendly-stdio\|jsonl\|xml` | all | how messages are printed; `rich-stdio` is the default | +| `--dotnet-settings Name=Value[,...]` | all | the .NET runtime of this Tazel process ([below](#the-net-runtime-of-tazel)) | | `--help`, `-h` | all | the help of the command | | `--mode debug\|release` | build, run, test | `debug` is the default | | `--platform <name>` | build, run, test | the platform to build for | @@ -134,6 +135,7 @@ microvm-network: false; microvm-memory: 2048; # MiB, or "auto" microvm-cpus: "auto"; platform: linux-amd64; +dotnet-settings: [ "GCHeapHardLimit=512M" 'GCSettings.LatencyMode=Interactive' ]; ``` The nearest `tazel_options.txt` at or above the current directory holds, except that a sandbox asked for by any file @@ -141,6 +143,40 @@ above stays asked for. This Tazel has no MicroVM to start, so with `sandboxing-w command that would run what a project brings (`build`, `run`, `test`, `package`, `custom`) rather than run it on this machine. +## The .NET runtime of Tazel + +`--dotnet-settings` and `dotnet-settings: [ ... ];` of `tazel_options.txt` set the .NET runtime of the Tazel process +that runs the command, and nothing else: not what it builds, tests or starts, and not `--jobs`. A setting not given +is left to .NET; nothing is kept for a later command. + +```text +tazel build //... --dotnet-settings=GCHeapHardLimit=512M,GCSettings.LatencyMode=Interactive +tazel build //... --dotnet-settings GCHeapHardLimit=512M --dotnet-settings:ThreadPool.MinWorkerThreads=8 +tazel dotnet get GCHeapHardLimit +tazel dotnet what-is CLI +``` + +| Setting | Value | +| --- | --- | +| `GCHeapHardLimit`, `GCHeapHardLimitSOH`, `GCHeapHardLimitLOH`, `GCHeapHardLimitPOH` | bytes, with `B`, `K`, `M`, `G` or `T` (KiB and up) | +| `GCHeapHardLimitPercent`, `GCHeapHardLimitSOHPercent`, `GCHeapHardLimitLOHPercent`, `GCHeapHardLimitPOHPercent` | a whole percentage | +| `GCSettings.LatencyMode` | `Batch`, `Interactive`, `LowLatency` or `SustainedLowLatency` | +| `ThreadPool.MinWorkerThreads`, `ThreadPool.MaxWorkerThreads`, `ThreadPool.MinCompletionPortThreads`, `ThreadPool.MaxCompletionPortThreads` | a whole number | + +- An entry is split at its first `=`. The option takes `=`, `:` or a space before its value, a comma-separated list + in each form, and repeats; `\,` is a comma of a value. The file's settings come first and the command line's after + them, and the last of a name wins. +- The whole set is checked before any of it is applied. Two ways of saying one limit are refused rather than one of + them ignored: `GCHeapHardLimit` with `GCHeapHardLimitPercent`, a limit of the whole heap with limits per object heap, + or limits per object heap in bytes and in percent. Limits per object heap need SOH and LOH (POH may be left out); + their percentages are each below 100, and so is their sum. A minimum of threads is at most their maximum. +- Heap limits go to `AppContext.SetData`, then `GC.RefreshMemoryLimit()` once; a limit below what the process has + committed is refused by .NET, and that is `error[E0506]`, as is a latency mode or thread count .NET does not take. +- `tazel dotnet get <setting>` prints what the process has: the GC's own report, or `default` where it reports none, + and for heap limits the memory available to the GC. `tazel dotnet what-is <term>` explains GCHeapHardLimit, RyuJIT, + .NET, CLI (the Common Language Infrastructure), CIL, CLR, C++/CLI, C#, WorkstationGC, BackgroundGC, daemon, CTS, + VES and ECMA-335, offline. Tazel has no daemon: `tazel dotnet start-daemon` and the like say so. + ## Directives of the text files `tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` share one grammar: besides their entries they take diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 77d3e4c..cc27a5e 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -62,7 +62,11 @@ internal sealed record BuildFlags } /// <summary>A command line, read into what it asks for; later stages do not look at its text again.</summary> -internal abstract record Command(OutputOptions Output); +internal abstract record Command(OutputOptions Output) +{ + /// <summary>The settings of --dotnet-settings, Name=Value each, checked; for this Tazel process alone.</summary> + public IReadOnlyList<Runtime.DotnetSetting> DotnetSettings { get; init; } = []; +} internal sealed record BuildCommand(OutputOptions Output, IReadOnlyList<string> Labels, BuildFlags Flags) : Command(Output); @@ -98,6 +102,12 @@ internal sealed record FetchCommand(OutputOptions Output) : Command(Output); internal sealed record ExplainCommand(OutputOptions Output, string Code, bool Long) : Command(Output); +/// <summary><c>tazel dotnet get <setting></c>: what this process has for a .NET setting.</summary> +internal sealed record DotnetGetCommand(OutputOptions Output, string Setting) : Command(Output); + +/// <summary><c>tazel dotnet what-is <term></c>: what a term of .NET means.</summary> +internal sealed record DotnetWhatIsCommand(OutputOptions Output, string Term) : Command(Output); + /// <summary><c>tazel limited-time C#</c>: the migration to BUILD.csx and labels in Depends, until Tazel 1.0.0.</summary> internal sealed record MigrateCommand(OutputOptions Output) : Command(Output); @@ -136,6 +146,9 @@ internal static class CommandLine Flag, Value, List, + + // A list after whitespace too: --dotnet-settings A=1,B=2. + ListAlways, } private sealed record Option(string Long, Kind Kind, IReadOnlyList<string>? Values, params string[] Scope); @@ -147,6 +160,7 @@ internal static class CommandLine new("color", Kind.Value, ["always", "auto", "never"]), new("progress", Kind.Value, ["always", "auto", "never"]), new("quiet", Kind.Flag, null), + new("dotnet-settings", Kind.ListAlways, null), new("message-format", Kind.Value, ["rich-stdio", "script-friendly-stdio", "jsonl", "xml"]), new("help", Kind.Flag, null), new("platform", Kind.Value, Platforms.Names, Building), @@ -172,6 +186,26 @@ internal static class CommandLine { ArgumentNullException.ThrowIfNull(arguments); var scanned = Scan(arguments); + // Every --dotnet-settings, in order, each entry checked here; on a name given twice the last wins later. + var settings = scanned.Seen.Where(entry => entry.Option.Long == "dotnet-settings") + .SelectMany(entry => entry.Values) + .Select(entry => + { + try + { + return Runtime.DotnetSettings.Parse(entry, "--dotnet-settings"); + } + catch (Runtime.DotnetSettingsException error) + { + throw new CommandLineException(error.Message, error); + } + }) + .ToList(); + return Make(scanned) with { DotnetSettings = settings }; + } + + private static Command Make(Scanned scanned) + { var command = scanned.Command; var unscoped = scanned.Seen.FirstOrDefault(entry => entry.Option.Scope.Length > 0 && !entry.Option.Scope.Contains(command, StringComparer.Ordinal)); @@ -312,8 +346,23 @@ internal static class CommandLine private static Command MakeDaemon(Scanned scanned, OutputOptions output) { - var actions = new[] { "start-daemon", "restart-daemon", "stop-daemon" }; + var actions = new[] { "start-daemon", "restart-daemon", "stop-daemon", "get", "what-is" }; var positional = scanned.Positional; + if (positional is ["get", var setting]) + { + return new DotnetGetCommand(output, setting); + } + + if (positional is ["what-is", var term]) + { + return new DotnetWhatIsCommand(output, term); + } + + if (positional is ["get" or "what-is", ..]) + { + throw new CommandLineException($"tazel dotnet {positional[0]} takes one {(positional[0] == "get" ? "setting" : "term")}"); + } + if (positional.Count == 1 && actions.Contains(positional[0], StringComparer.Ordinal)) { return new DaemonCommand(output, positional[0]); @@ -321,7 +370,7 @@ internal static class CommandLine var near = positional.Count == 1 ? Suggestions.Nearest(positional[0], actions) : null; throw new CommandLineException( - $"tazel dotnet takes start-daemon, restart-daemon or stop-daemon{(near is null ? "" : $"; did you mean {near}?")}"); + $"tazel dotnet takes get, what-is, start-daemon, restart-daemon or stop-daemon{(near is null ? "" : $"; did you mean {near}?")}"); } private static Command MakeCache(Scanned scanned, OutputOptions output) @@ -399,13 +448,14 @@ internal static class CommandLine else if (separator >= 0) { var text = body[(separator + 1)..]; - values = option.Kind == Kind.List ? [.. SplitList(text)] : [text]; + values = option.Kind is Kind.List or Kind.ListAlways ? [.. SplitList(text)] : [text]; Check(option, values, $"--{name}{body[separator]}"); } else { // Whitespace gives one value, whatever it holds. - values = index < arguments.Count ? [arguments[index++]] : throw new CommandLineException($"--{name} needs a value"); + values = index >= arguments.Count ? throw new CommandLineException($"--{name} needs a value") + : option.Kind == Kind.ListAlways ? [.. SplitList(arguments[index++])] : [arguments[index++]]; Check(option, values, $"--{name} "); } diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index bf7c734..a25696c 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -63,6 +63,15 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; case MigrateCommand: return Migrate(); + case DotnetGetCommand get: + foreach (var line in Runtime.DotnetSettings.Get(get.Setting)) + { + reporter.Plain(line); + } + + return 0; + case DotnetWhatIsCommand whatIs: + return WhatIs(whatIs.Term); case CleanCommand clean: return Clean(clean.Expunge); case CacheKeygenCommand keygen: @@ -151,6 +160,21 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; } + /// <summary>tazel dotnet what-is: a term of .NET explained, offline.</summary> + private int WhatIs(string term) + { + if (Runtime.DotnetGlossary.Find(term) is not { } entry) + { + var near = Runtime.DotnetGlossary.Nearest(term); + throw new CommandLineException( + $"'{term}' is not a term tazel dotnet what-is knows{(near is null ? "" : $"; did you mean {near}?")}"); + } + + reporter.Strong(entry.Title is null ? entry.Term : $"{entry.Term} — {entry.Title}"); + reporter.Plain(entry.Text); + return 0; + } + private int Clean(bool expunge) { var root = ModuleFiles.FindRoot(workingDirectory); diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index c4b0542..231da7c 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -212,10 +212,28 @@ internal static class Help --algorithm ed25519|rsa-4096|ml-dsa the algorithm; default: ed25519. ml-dsa is ML-DSA-65 (FIPS 204). """), - ["dotnet"] = new("tazel dotnet start-daemon|restart-daemon|stop-daemon: the daemon of Tazel.", """ + ["dotnet"] = new("tazel dotnet get|what-is: the .NET runtime of this Tazel process and terms of .NET.", """ + tazel dotnet get <setting> + tazel dotnet what-is <term> tazel dotnet start-daemon|restart-daemon|stop-daemon - The daemon that keeps the .NET runtime of Tazel warm between commands. + get prints what this process has for one of the settings below, as .NET reports it, and default where it + reports none; --dotnet-settings of another command does not reach a later one. what-is explains a term of + .NET, offline: GCHeapHardLimit, RyuJIT, .NET, CLI (the Common Language Infrastructure, never a command + line), CIL, CLR, C++/CLI, C#, WorkstationGC, BackgroundGC, daemon, CTS, VES, ECMA-335. This Tazel has no + daemon: start-daemon, restart-daemon and stop-daemon say so. + + --dotnet-settings Name=Value[,Name=Value] sets, for the .NET runtime of this Tazel process alone, any of: + GCHeapHardLimit, GCHeapHardLimitSOH, GCHeapHardLimitLOH, GCHeapHardLimitPOH bytes: 512M, 2G, 1048576 + GCHeapHardLimitPercent, GCHeapHardLimitSOHPercent, GCHeapHardLimitLOHPercent, + GCHeapHardLimitPOHPercent whole percentages + GCSettings.LatencyMode Batch, Interactive, LowLatency, SustainedLowLatency + ThreadPool.MinWorkerThreads, ThreadPool.MaxWorkerThreads, + ThreadPool.MinCompletionPortThreads, ThreadPool.MaxCompletionPortThreads whole numbers + Sizes take B, K, M, G or T (KiB and up). The option may repeat and mix =, : and a space; \, is a comma of + a value; a name given twice keeps its last value. dotnet-settings: [ "Name=Value" ... ]; in + tazel_options.txt comes first and the command line after it. A setting not given is left to .NET. Nothing + reaches what Tazel builds or starts, and --jobs is untouched. """), }; @@ -224,6 +242,7 @@ internal static class Help --color always|auto|never colors; default: auto --progress always|auto|never the [done/total] counter; default: auto --quiet only problems and the program's own output + --dotnet-settings Name=Value the .NET runtime of this process (tazel help dotnet --long) --message-format rich-stdio|script-friendly-stdio|jsonl|xml how messages are printed; default: rich-stdio --help, -h the help of the command diff --git a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs index 05be515..e0f8819 100644 --- a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs +++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs @@ -42,6 +42,12 @@ public sealed record TazelOptions /// <summary>The platform commands build for unless <c>--platform</c> names one; default: the host's.</summary> public Platform? Platform { get; init; } + + /// <summary> + /// <c>dotnet-settings: [ "Name=Value" ... ];</c>: settings of the .NET runtime of the Tazel process, applied before + /// those of <c>--dotnet-settings</c>; none by default. + /// </summary> + public IReadOnlyList<Runtime.DotnetSetting> DotnetSettings { get; init; } = []; } /// <summary>What is wrong with a <c>tazel_options.txt</c>, with where it is.</summary> @@ -83,7 +89,7 @@ public static class TazelOptionsFile private const int MaxCpus = 256; private static readonly string[] Keys = - ["sandboxing-with-microvm", "microvm-network", "microvm-memory", "microvm-cpus", "platform"]; + ["sandboxing-with-microvm", "microvm-network", "microvm-memory", "microvm-cpus", "platform", "dotnet-settings"]; /// <summary> /// Reads the text of a <c>tazel_options.txt</c>, with the comments and strings of <c>tazel_custom.txt</c>. @@ -220,6 +226,17 @@ public static class TazelOptionsFile } Take(TokenKind.Colon, $"':' after {key.Text}"); + if (key.Text == "dotnet-settings") + { + options = options with { DotnetSettings = SettingsList() }; + if (_position < tokens.Count) + { + Take(TokenKind.Semicolon, "';' after the list of dotnet-settings"); + } + + continue; + } + if (_position >= tokens.Count || tokens[_position].Kind is not (TokenKind.Name or TokenKind.String)) { throw new TazelOptionsException(Diagnostic.After(Output.ErrorCodes.OptionsNoValue, text, file, tokens[_position - 1], @@ -247,6 +264,39 @@ public static class TazelOptionsFile return options; } + // [ "Name=Value" 'Name=Value' `Name=Value` ]: strings in any of the quotes, no commas between them. + private IReadOnlyList<Runtime.DotnetSetting> SettingsList() + { + var open = Take(TokenKind.BracketOpen, "'[' to open the list of dotnet-settings"); + var settings = new List<Runtime.DotnetSetting>(); + while (_position < tokens.Count && tokens[_position].Kind == TokenKind.String) + { + var entry = tokens[_position++]; + try + { + settings.Add(Runtime.DotnetSettings.Parse(entry.Text, $"{file}:{entry.Line}")); + } + catch (Runtime.DotnetSettingsException error) + { + throw Fail(Output.ErrorCodes.OptionsDotnetSetting, entry, error.Message, "this setting", + "write \"Name=Value\" with one of the names of tazel help dotnet --long", + "Tazel knows thirteen .NET settings by heart; this was not one of them."); + } + } + + if (_position >= tokens.Count || tokens[_position].Kind != TokenKind.BracketClose) + { + var at = _position < tokens.Count ? tokens[_position] : tokens[_position - 1]; + throw Fail(Output.ErrorCodes.OptionsDotnetSetting, at, + $"the list of dotnet-settings, opened at line {open.Line}, holds strings and ends with ]", "here", + "put each setting in quotes, with no commas, and close the list with ]", + "A list without its ] is a sentence without its full stop."); + } + + _position++; + return settings; + } + private TazelOptionsException Fail(string code, Token token, string message, string label, string help, string joke) => new(Diagnostic.AtToken(code, text, file, token, message, label, help, joke)); diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index 82bddc8..53a8b81 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -51,6 +51,7 @@ internal static partial class ErrorCodes public const string OptionsOutOfRange = "E0210"; public const string OptionsNotAPlatform = "E0211"; public const string OptionsUnreadable = "E0212"; + public const string OptionsDotnetSetting = "E0213"; public const string CustomNameEnd = "E0301"; public const string CustomNameTooLong = "E0302"; @@ -84,6 +85,7 @@ internal static partial class ErrorCodes public const string Stopped = "E0503"; public const string MicroVM = "E0504"; public const string CacheKey = "E0505"; + public const string DotnetSettingRefused = "E0506"; public const string Label = "E0600"; private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt"; @@ -150,6 +152,17 @@ internal static partial class ErrorCodes "target_system, or in a file such a branch includes, would choose the platform from itself, so it is an error.", ".if target_system.os == \"linux\"\nplatform: windows-x64;\n.end", ".if host_system.os == \"linux\"\nplatform: windows-x64;\n.end", Options), + new(OptionsDotnetSetting, "a .NET setting Tazel does not take", + "dotnet-settings: [ ... ]; holds strings of Name=Value, one per setting, without commas between them. The names " + + "are the thirteen of tazel help dotnet --long; sizes take B, K, M, G or T, percentages and thread counts whole " + + "numbers. A name given twice keeps its last value.", + "dotnet-settings: GCHeapHardLimit=512M;", "dotnet-settings: [\"GCHeapHardLimit=512M\"];", Options), + new(DotnetSettingRefused, "a .NET setting that cannot hold, or that .NET refused", + "Some settings are two ways of saying one thing, and Tazel takes neither of them: GCHeapHardLimit with " + + "GCHeapHardLimitPercent, a limit for the whole heap with limits per object heap, or object heap limits in bytes " + + "and in percent. Limits per object heap need both SOH and LOH; their percentages are each below 100, and so is " + + "their sum. .NET itself may refuse a heap limit below what this process has committed, a latency mode its GC " + + "cannot take, or thread counts it does not allow. Nothing of the command ran.", null, null, "tazel"), new(CommandLine, "a command line Tazel cannot take", "The command, an option or a value is not one Tazel knows, or a command got arguments it does not take. Tazel " + "suggests the nearest spelling when there is one. tazel help lists the commands, and tazel help <command> --long " + diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 27219d9..d4ebf65 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -51,8 +51,15 @@ internal static class Program command.Output.Progress); try { + ApplyDotnetSettings(command, directory); return await new Commands(reporter, directory).RunAsync(command, cancel).ConfigureAwait(false); } + catch (Runtime.DotnetSettingsException error) + { + reporter.Error(ErrorCodes.DotnetSettingRefused, error.Message, "tazel help dotnet --long says what each setting takes", + "The runtime had the last word, and the word was no."); + return 1; + } catch (CommandLineException error) { reporter.Error(ErrorCodes.CommandLine, error.Message, HelpFor(arguments), Jokes.ForCommandLine(error.Message)); @@ -94,6 +101,25 @@ internal static class Program } } + /// <summary> + /// Applies the .NET settings of tazel_options.txt and of --dotnet-settings to this process, before the command: + /// the file's first, the command line's after, the whole set checked before any is applied. Help, explain, + /// version and dotnet what-is read no file and change nothing. + /// </summary> + private static void ApplyDotnetSettings(Command command, string directory) + { + if (command is HelpCommand or ExplainCommand or VersionCommand or DotnetWhatIsCommand) + { + return; + } + + var fromFile = TazelOptionsFile.Effective(directory).Options.DotnetSettings; + if (fromFile.Count + command.DotnetSettings.Count > 0) + { + Runtime.DotnetSettings.Apply(Runtime.DotnetSettings.Effective(fromFile, command.DotnetSettings)); + } + } + /// <summary>The diagnostic of a problem with a place in a file, found through the causes too.</summary> private static Diagnostic? Placed(Exception? error) { diff --git a/src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs b/src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs new file mode 100644 index 0000000..efdba24 --- /dev/null +++ b/src/Progmasoft.Tazel/Runtime/DotnetGlossary.cs @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Progmasoft.Tazel.Runtime; + +/// <summary>One term of <c>tazel dotnet what-is</c>: its name, what it stands for, and what it is.</summary> +/// <param name="Term">The term, as it is typed.</param> +/// <param name="Title">What it stands for, or null when it stands for nothing longer.</param> +/// <param name="Text">What it is.</param> +internal sealed record GlossaryEntry(string Term, string? Title, string Text); + +/// <summary> +/// The terms of .NET that <c>tazel dotnet what-is</c> explains, offline: they are part of Tazel. Terms are matched as +/// written; an unknown one gets the nearest. +/// </summary> +internal static class DotnetGlossary +{ + /// <summary>Every term, in the order the help lists them.</summary> + public static IReadOnlyList<GlossaryEntry> Entries { get; } = + [ + new("GCHeapHardLimit", null, + "A limit, in bytes, on what the garbage collector commits for the managed heap and its own bookkeeping. It is " + + "not a limit on the memory of the whole process: native memory, thread stacks and the code of the runtime " + + "are outside it. --dotnet-settings sets it for this Tazel process alone."), + new("RyuJIT", null, + "The just-in-time compiler of .NET. It turns CIL into the machine code of the processor as a method is first " + + "called, and again with more optimization for methods called often (tiered compilation)."), + new(".NET", null, + "A platform for building and running programs: runtimes that execute CIL, the base class libraries, the " + + "compilers of C#, F# and Visual Basic, and the tools of the dotnet command. Tazel is written for it and runs on it."), + new("CLI", "Common Language Infrastructure", + "The execution and type-system infrastructure specified by ECMA-335. It includes the Common Type System, the " + + "Common Intermediate Language, metadata, and the Virtual Execution System. In tazel dotnet what-is, CLI is " + + "always this infrastructure of ECMA-335."), + new("CIL", "Common Intermediate Language", + "The instruction language the CLI standardizes: compilers of C# and the other .NET languages emit it, and the " + + "runtime compiles it to machine code. Also called IL or MSIL."), + new("CLR", "Common Language Runtime", + "Microsoft's implementation of the runtime of .NET: it loads assemblies, compiles CIL with RyuJIT, collects " + + "garbage, and enforces the type system."), + new("C++/CLI", null, + "An extension of C++ that adds the managed types of .NET to it, so that C++ code and .NET code call each " + + "other directly. It is built by the Microsoft C++ compiler, on Windows."), + new("C#", null, + "A general-purpose, statically typed programming language, the one most used on .NET. Tazel's project files, " + + "MODULE.csx and BUILD.csx, are C# scripts."), + new("WorkstationGC", null, + "The configuration of the garbage collector meant for interactive programs: one heap, collections that pause " + + "the program briefly, and usually background collection of the oldest generation alongside it."), + new("BackgroundGC", null, + "Garbage collection in which much of the work on generation 2, the oldest objects, runs on a thread of its " + + "own while the program goes on, instead of stopping it for the whole collection."), + new("daemon", null, + "A long-running background process that serves other processes. This Tazel starts every command in a process " + + "of its own and has no persistent daemon; tazel dotnet start-daemon says so."), + new("CTS", "Common Type System", + "The rules of the CLI for defining types and how they relate: classes, value types, interfaces, inheritance, " + + "and how one language's types are seen by another."), + new("VES", "Virtual Execution System", + "The abstract machine the CLI specifies to run CIL: how it loads code, calls methods, handles exceptions and " + + "manages memory. The CLR is an implementation of it."), + new("ECMA-335", null, + "The ECMA standard of the Common Language Infrastructure: the CTS, CIL, metadata and the VES. .NET follows it."), + ]; + + /// <summary>The entry of <paramref name="term"/>, as written.</summary> + public static GlossaryEntry? Find(string term) => Entries.FirstOrDefault(entry => entry.Term == term); + + /// <summary>The term nearest to <paramref name="term"/>, for a suggestion.</summary> + public static string? Nearest(string term) => + Entries.FirstOrDefault(entry => string.Equals(entry.Term, term, StringComparison.OrdinalIgnoreCase))?.Term ?? + Cli.Suggestions.Nearest(term, Entries.Select(entry => entry.Term)); +} diff --git a/src/Progmasoft.Tazel/Runtime/DotnetSettings.cs b/src/Progmasoft.Tazel/Runtime/DotnetSettings.cs new file mode 100644 index 0000000..b8af6db --- /dev/null +++ b/src/Progmasoft.Tazel/Runtime/DotnetSettings.cs @@ -0,0 +1,343 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Runtime; +using System.Threading; + +namespace Progmasoft.Tazel.Runtime; + +/// <summary>A .NET setting Tazel cannot take, or one the runtime refused.</summary> +public sealed class DotnetSettingsException : Exception +{ + /// <summary>What is wrong.</summary> + public DotnetSettingsException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public DotnetSettingsException() + { + } + + /// <summary>What is wrong, and why.</summary> + public DotnetSettingsException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary>What a setting takes.</summary> +internal enum SettingKind +{ + /// <summary>A size in bytes, with an optional B, K, M, G or T.</summary> + Bytes, + + /// <summary>A whole percentage.</summary> + Percent, + + /// <summary>A <see cref="GCLatencyMode"/>: Batch, Interactive, LowLatency or SustainedLowLatency.</summary> + LatencyMode, + + /// <summary>A number of threads.</summary> + Threads, +} + +/// <summary>One setting: its name, its value, and where it was written.</summary> +/// <param name="Name">One of the thirteen names.</param> +/// <param name="Value">A ulong for sizes and percentages, an int for threads, a <see cref="GCLatencyMode"/>.</param> +/// <param name="Source">The command line or the file, for messages.</param> +public sealed record DotnetSetting(string Name, object Value, string Source); + +/// <summary> +/// <c>--dotnet-settings</c> and <c>dotnet-settings</c> of <c>tazel_options.txt</c>: thirteen settings of the .NET runtime +/// of this Tazel process alone, never of what it builds or starts. A setting not given is left to .NET. +/// </summary> +internal static class DotnetSettings +{ + private const string LatencyName = "GCSettings.LatencyMode"; + + /// <summary>The settings, and what each takes, in the order <c>tazel help dotnet</c> lists them.</summary> + public static IReadOnlyList<(string Name, SettingKind Kind)> All { get; } = + [ + ("GCHeapHardLimit", SettingKind.Bytes), + ("GCHeapHardLimitPercent", SettingKind.Percent), + ("GCHeapHardLimitSOH", SettingKind.Bytes), + ("GCHeapHardLimitLOH", SettingKind.Bytes), + ("GCHeapHardLimitPOH", SettingKind.Bytes), + ("GCHeapHardLimitSOHPercent", SettingKind.Percent), + ("GCHeapHardLimitLOHPercent", SettingKind.Percent), + ("GCHeapHardLimitPOHPercent", SettingKind.Percent), + (LatencyName, SettingKind.LatencyMode), + ("ThreadPool.MinWorkerThreads", SettingKind.Threads), + ("ThreadPool.MaxWorkerThreads", SettingKind.Threads), + ("ThreadPool.MinCompletionPortThreads", SettingKind.Threads), + ("ThreadPool.MaxCompletionPortThreads", SettingKind.Threads), + ]; + + private static readonly string[] LatencyModes = ["Batch", "Interactive", "LowLatency", "SustainedLowLatency"]; + + /// <summary>Whether <paramref name="name"/> is one of the thirteen.</summary> + public static bool IsName(string name) => All.Any(setting => setting.Name == name); + + /// <summary><c>Name=Value</c>, split at its first <c>=</c>, checked against what the name takes.</summary> + public static DotnetSetting Parse(string entry, string source) + { + ArgumentNullException.ThrowIfNull(entry); + var equals = entry.IndexOf('=', StringComparison.Ordinal); + if (equals <= 0) + { + throw new DotnetSettingsException($"{source}: '{entry}' is not Name=Value"); + } + + var (name, value) = (entry[..equals], entry[(equals + 1)..]); + var kind = All.FirstOrDefault(setting => setting.Name == name).Kind; + if (!IsName(name)) + { + var near = Cli.Suggestions.Nearest(name, All.Select(setting => setting.Name)); + throw new DotnetSettingsException( + $"{source}: '{name}' is not a .NET setting Tazel takes{(near is null ? "; tazel help dotnet --long lists the thirteen" : $"; did you mean {near}?")}"); + } + + return new DotnetSetting(name, kind switch + { + SettingKind.Bytes => Bytes(value) ?? throw Bad(source, name, value, "a size in bytes, with B, K, M, G or T after it if you like"), + SettingKind.Percent => Whole(value) is { } percent and >= 1 and <= 100 ? (ulong)percent + : throw Bad(source, name, value, "a whole percentage from 1 to 100"), + SettingKind.Threads => Whole(value) is { } threads and >= 1 and <= int.MaxValue ? (int)threads + : throw Bad(source, name, value, "a whole number of threads, 1 or more"), + _ => LatencyModes.Contains(value, StringComparer.Ordinal) ? Enum.Parse<GCLatencyMode>(value) + : throw Bad(source, name, value, $"one of {string.Join(", ", LatencyModes)}"), + }, source); + } + + private static DotnetSettingsException Bad(string source, string name, string value, string what) => + new($"{source}: {name} takes {what}, not '{value}'"); + + // A size: digits, then nothing, B, K, M, G or T; KiB and up, in checked arithmetic. + internal static ulong? Bytes(string text) + { + if (text.Length == 0) + { + return null; + } + + var (digits, multiplier) = text[^1] switch + { + 'B' => (text[..^1], 1UL), + 'K' => (text[..^1], 1UL << 10), + 'M' => (text[..^1], 1UL << 20), + 'G' => (text[..^1], 1UL << 30), + 'T' => (text[..^1], 1UL << 40), + _ => (text, 1UL), + }; + if (Whole(digits) is not { } number) + { + return null; + } + + try + { + return checked(number * multiplier); + } + catch (OverflowException) + { + return null; + } + } + + private static ulong? Whole(string text) => + text.Length > 0 && text.All(char.IsAsciiDigit) && + ulong.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) ? value : null; + + /// <summary> + /// The settings that hold: those of the file, then those of the command line, the last of a name winning; the + /// whole set is checked before anything is applied. + /// </summary> + public static IReadOnlyDictionary<string, DotnetSetting> Effective(IEnumerable<DotnetSetting> file, IEnumerable<DotnetSetting> commandLine) + { + var settings = new Dictionary<string, DotnetSetting>(StringComparer.Ordinal); + foreach (var setting in file.Concat(commandLine)) + { + settings[setting.Name] = setting; + } + + Check(settings); + return settings; + } + + private static void Check(Dictionary<string, DotnetSetting> settings) + { + bool Has(string name) => settings.ContainsKey(name); + string Where(params string[] names) => string.Join(", ", names.Where(Has).Select(name => $"{name} ({settings[name].Source})")); + string[] perHeap = ["GCHeapHardLimitSOH", "GCHeapHardLimitLOH", "GCHeapHardLimitPOH"]; + string[] perHeapPercent = ["GCHeapHardLimitSOHPercent", "GCHeapHardLimitLOHPercent", "GCHeapHardLimitPOHPercent"]; + var aggregate = Has("GCHeapHardLimit") || Has("GCHeapHardLimitPercent"); + var heaps = perHeap.Any(Has); + var heapPercents = perHeapPercent.Any(Has); + + // .NET would take one and leave the other unsaid; Tazel takes neither and says so. + if (Has("GCHeapHardLimit") && Has("GCHeapHardLimitPercent")) + { + throw new DotnetSettingsException($"{Where("GCHeapHardLimit", "GCHeapHardLimitPercent")}: give the limit in bytes or as a percentage, not both"); + } + + if (aggregate && (heaps || heapPercents)) + { + throw new DotnetSettingsException( + $"{Where([.. perHeap, .. perHeapPercent, "GCHeapHardLimit", "GCHeapHardLimitPercent"])}: a limit for the whole heap and limits per object heap " + + "are two ways to say one thing; give one"); + } + + if (heaps && heapPercents) + { + throw new DotnetSettingsException($"{Where([.. perHeap, .. perHeapPercent])}: give the object heaps' limits in bytes or as percentages, not both"); + } + + foreach (var (names, kind) in new[] { (perHeap, "in bytes"), (perHeapPercent, "as percentages") }) + { + if (names.Any(Has) && !(Has(names[0]) && Has(names[1]))) + { + throw new DotnetSettingsException( + $"{Where(names)}: limits per object heap {kind} need both {names[0]} and {names[1]}; {names[2]} may be left out"); + } + } + + if (heapPercents) + { + var percents = perHeapPercent.Where(Has).Select(name => (ulong)settings[name].Value).ToList(); + if (percents.Any(percent => percent >= 100) || percents.Aggregate(0UL, (sum, percent) => sum + percent) >= 100) + { + throw new DotnetSettingsException($"{Where(perHeapPercent)}: each percentage is below 100, and so is their sum"); + } + } + + var minWorker = settings.GetValueOrDefault("ThreadPool.MinWorkerThreads"); + var maxWorker = settings.GetValueOrDefault("ThreadPool.MaxWorkerThreads"); + var minPort = settings.GetValueOrDefault("ThreadPool.MinCompletionPortThreads"); + var maxPort = settings.GetValueOrDefault("ThreadPool.MaxCompletionPortThreads"); + ThreadPool.GetMinThreads(out var currentMinWorker, out var currentMinPort); + ThreadPool.GetMaxThreads(out var currentMaxWorker, out var currentMaxPort); + var (worker, port) = ((int?)minWorker?.Value ?? currentMinWorker, (int?)minPort?.Value ?? currentMinPort); + var (workerMax, portMax) = ((int?)maxWorker?.Value ?? currentMaxWorker, (int?)maxPort?.Value ?? currentMaxPort); + if (worker > workerMax) + { + throw new DotnetSettingsException( + $"the worker threads' minimum {worker} is above their maximum {workerMax} ({Where("ThreadPool.MinWorkerThreads", "ThreadPool.MaxWorkerThreads")})"); + } + + if (port > portMax) + { + throw new DotnetSettingsException( + $"the completion port threads' minimum {port} is above their maximum {portMax} ({Where("ThreadPool.MinCompletionPortThreads", "ThreadPool.MaxCompletionPortThreads")})"); + } + + if (workerMax < Environment.ProcessorCount || portMax < Environment.ProcessorCount) + { + throw new DotnetSettingsException( + $"a maximum of threads below the {Environment.ProcessorCount} processors of this machine is refused by .NET ({Where("ThreadPool.MaxWorkerThreads", "ThreadPool.MaxCompletionPortThreads")})"); + } + } + + /// <summary>Applies <paramref name="settings"/> to this process: the heap limits, the latency mode, the thread pool.</summary> + public static void Apply(IReadOnlyDictionary<string, DotnetSetting> settings) + { + ArgumentNullException.ThrowIfNull(settings); + var limits = settings.Values.Where(setting => setting.Name.StartsWith("GCHeapHardLimit", StringComparison.Ordinal)).ToList(); + if (limits.Count > 0) + { + foreach (var limit in limits) + { + AppContext.SetData(limit.Name, (ulong)limit.Value); + } + + try + { + GC.RefreshMemoryLimit(); + } + catch (InvalidOperationException error) + { + throw new DotnetSettingsException($"the GC took no new heap limit ({string.Join(", ", limits.Select(l => l.Name))}): {error.Message}", error); + } + } + + if (settings.TryGetValue(LatencyName, out var latency)) + { + var mode = (GCLatencyMode)latency.Value; + GCSettings.LatencyMode = mode; + if (GCSettings.LatencyMode != mode) + { + throw new DotnetSettingsException( + $"{LatencyName}={mode} ({latency.Source}): the GC of this process stays in {GCSettings.LatencyMode}; " + + "LowLatency needs the workstation GC"); + } + } + + ApplyThreads(settings); + } + + private static void ApplyThreads(IReadOnlyDictionary<string, DotnetSetting> settings) + { + int? Value(string name) => settings.TryGetValue(name, out var setting) ? (int)setting.Value : null; + var (minWorker, maxWorker) = (Value("ThreadPool.MinWorkerThreads"), Value("ThreadPool.MaxWorkerThreads")); + var (minPort, maxPort) = (Value("ThreadPool.MinCompletionPortThreads"), Value("ThreadPool.MaxCompletionPortThreads")); + if (minWorker is null && maxWorker is null && minPort is null && maxPort is null) + { + return; + } + + ThreadPool.GetMinThreads(out var currentMinWorker, out var currentMinPort); + ThreadPool.GetMaxThreads(out var currentMaxWorker, out var currentMaxPort); + var (newMin, newMinPort) = (minWorker ?? currentMinWorker, minPort ?? currentMinPort); + var (newMax, newMaxPort) = (maxWorker ?? currentMaxWorker, maxPort ?? currentMaxPort); + + // A maximum may not fall below the minimum of the moment, nor a minimum rise above the maximum: whichever + // order keeps both true at every step. + var maxFirst = newMax >= currentMinWorker && newMaxPort >= currentMinPort; + var steps = maxFirst + ? new (string What, Func<bool> Set)[] { ("maximum", () => ThreadPool.SetMaxThreads(newMax, newMaxPort)), ("minimum", () => ThreadPool.SetMinThreads(newMin, newMinPort)) } + : [("minimum", () => ThreadPool.SetMinThreads(newMin, newMinPort)), ("maximum", () => ThreadPool.SetMaxThreads(newMax, newMaxPort))]; + foreach (var (what, set) in steps) + { + if (!set()) + { + throw new DotnetSettingsException( + $"the thread pool of this process took no new {what} (workers {newMin} to {newMax}, completion ports {newMinPort} to {newMaxPort})"); + } + } + } + + /// <summary>What this process has for <paramref name="name"/>: its value, or <c>default</c> where .NET says none.</summary> + public static IReadOnlyList<string> Get(string name) + { + if (!IsName(name)) + { + var near = Cli.Suggestions.Nearest(name, All.Select(setting => setting.Name)); + throw new DotnetSettingsException($"'{name}' is not a .NET setting Tazel takes{(near is null ? "" : $"; did you mean {near}?")}"); + } + + switch (name) + { + case LatencyName: + return [$"{name}: {GCSettings.LatencyMode}"]; + case "ThreadPool.MinWorkerThreads" or "ThreadPool.MinCompletionPortThreads": + ThreadPool.GetMinThreads(out var minWorker, out var minPort); + return [$"{name}: {(name.Contains("Worker", StringComparison.Ordinal) ? minWorker : minPort)}"]; + case "ThreadPool.MaxWorkerThreads" or "ThreadPool.MaxCompletionPortThreads": + ThreadPool.GetMaxThreads(out var maxWorker, out var maxPort); + return [$"{name}: {(name.Contains("Worker", StringComparison.Ordinal) ? maxWorker : maxPort)}"]; + default: + // The GC's own report of its configuration; a name it does not report, or reports as 0, was not set. + var configured = GC.GetConfigurationVariables().TryGetValue(name[2..], out var value) || + GC.GetConfigurationVariables().TryGetValue(name, out value) ? value : null; + var shown = configured is null || Convert.ToUInt64(configured, CultureInfo.InvariantCulture) == 0 + ? "default" + : Convert.ToString(configured, CultureInfo.InvariantCulture)!; + return [$"{name}: {shown}", $"available to the GC: {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes} bytes"]; + } + } +} diff --git a/tests/Progmasoft.Tazel.Tests/DotnetSettingsTests.cs b/tests/Progmasoft.Tazel.Tests/DotnetSettingsTests.cs new file mode 100644 index 0000000..a515c78 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/DotnetSettingsTests.cs @@ -0,0 +1,244 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Dsl.Options; +using Progmasoft.Tazel.Output; +using Progmasoft.Tazel.Runtime; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class DotnetSettingsTests +{ + private static DotnetSetting Setting(string entry) => DotnetSettings.Parse(entry, "test"); + + // Another tazel process: settings applied there do not change the GC or the thread pool of the tests. + private static async Task<(int Status, string Output)> TazelProcess(string directory, params string[] arguments) + { + var tazel = Path.Combine(AppContext.BaseDirectory, "tazel.dll"); + var start = new ProcessStartInfo("dotnet", ["exec", tazel, "--color", "never", .. arguments]) + { + WorkingDirectory = directory, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + using var process = Process.Start(start)!; + var output = await process.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken); + output += await process.StandardError.ReadToEndAsync(TestContext.Current.CancellationToken); + await process.WaitForExitAsync(TestContext.Current.CancellationToken); + return (process.ExitCode, output); + } + + [Theory] + [InlineData("536870912")] + [InlineData("536870912B")] + [InlineData("524288K")] + [InlineData("512M")] + public void SizesScaleBySuffix(string size) => + Assert.Equal(536870912UL, Setting($"GCHeapHardLimit={size}").Value); + + [Fact] + public void TheLargestSuffixIsATebibyte() => Assert.Equal(2UL << 40, Setting("GCHeapHardLimitSOH=2T").Value); + + [Theory] + [InlineData("GCHeapHardLimit=99999999999T", "a size in bytes")] + [InlineData("GCHeapHardLimit=-1", "a size in bytes")] + [InlineData("GCHeapHardLimit=1.5M", "a size in bytes")] + [InlineData("GCHeapHardLimit=512m", "a size in bytes")] + [InlineData("GCHeapHardLimit=", "a size in bytes")] + [InlineData("GCHeapHardLimitPercent=0", "a whole percentage from 1 to 100")] + [InlineData("GCHeapHardLimitPercent=101", "a whole percentage from 1 to 100")] + [InlineData("GCHeapHardLimitPercent=10K", "a whole percentage from 1 to 100")] + [InlineData("ThreadPool.MinWorkerThreads=0", "a whole number of threads")] + [InlineData("GCSettings.LatencyMode=NoGCRegion", "one of Batch, Interactive, LowLatency, SustainedLowLatency")] + [InlineData("GCSettings.LatencyMode=interactive", "one of Batch")] + [InlineData("gcServer=true", "is not a .NET setting Tazel takes")] + [InlineData("GCHeapHardLimt=1", "did you mean GCHeapHardLimit?")] + [InlineData("GCHeapHardLimit", "is not Name=Value")] + public void RefusesWhatItDoesNotTake(string entry, string message) + { + var error = Assert.Throws<DotnetSettingsException>(() => Setting(entry)); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void SplitsAtTheFirstEqualsSign() + { + var error = Assert.Throws<DotnetSettingsException>(() => Setting("GCSettings.LatencyMode=Batch=1")); + Assert.Contains("not 'Batch=1'", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void TheLastOfANameWinsAcrossTheFileAndTheCommandLine() + { + var effective = DotnetSettings.Effective( + [Setting("GCSettings.LatencyMode=Batch"), Setting("ThreadPool.MinWorkerThreads=4")], + [Setting("GCSettings.LatencyMode=Interactive"), Setting("GCSettings.LatencyMode=SustainedLowLatency")]); + Assert.Equal(GCLatencyMode.SustainedLowLatency, effective["GCSettings.LatencyMode"].Value); + Assert.Equal(4, effective["ThreadPool.MinWorkerThreads"].Value); + } + + [Theory] + [InlineData("GCHeapHardLimit=1G GCHeapHardLimitPercent=20", "in bytes or as a percentage, not both")] + [InlineData("GCHeapHardLimit=1G GCHeapHardLimitSOH=1G GCHeapHardLimitLOH=1G", "a limit for the whole heap and limits per object heap")] + [InlineData("GCHeapHardLimitSOH=1G GCHeapHardLimitLOHPercent=5 GCHeapHardLimitSOHPercent=5", "in bytes or as percentages, not both")] + [InlineData("GCHeapHardLimitSOH=1G", "need both GCHeapHardLimitSOH and GCHeapHardLimitLOH")] + [InlineData("GCHeapHardLimitPOH=1G GCHeapHardLimitLOH=1G", "need both GCHeapHardLimitSOH and GCHeapHardLimitLOH")] + [InlineData("GCHeapHardLimitSOHPercent=50 GCHeapHardLimitLOHPercent=40 GCHeapHardLimitPOHPercent=10", "and so is their sum")] + [InlineData("GCHeapHardLimitSOHPercent=100 GCHeapHardLimitLOHPercent=1", "each percentage is below 100")] + [InlineData("ThreadPool.MinWorkerThreads=50 ThreadPool.MaxWorkerThreads=40", "minimum 50 is above their maximum 40")] + [InlineData("ThreadPool.MaxCompletionPortThreads=0", "a whole number of threads")] + public void RefusesSettingsThatCannotHoldTogether(string entries, string message) + { + var error = Assert.Throws<DotnetSettingsException>(() => + DotnetSettings.Effective(entries.Split(' ').Select(Setting).ToList(), [])); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + + [Fact] + public void TakesLimitsPerObjectHeapWithoutThePinnedOne() + { + var effective = DotnetSettings.Effective([Setting("GCHeapHardLimitSOH=1G"), Setting("GCHeapHardLimitLOH=256M")], []); + Assert.Equal(2, effective.Count); + } + + [Theory] + [InlineData("--dotnet-settings=GCHeapHardLimit=512M")] + [InlineData("--dotnet-settings:GCHeapHardLimit=512M")] + [InlineData("--dotnet-settings|GCHeapHardLimit=512M")] + public void TheCommandLineTakesEachSeparator(string option) + { + var command = CommandLine.Parse(["build", "//...", .. option.Split('|')]); + Assert.Equal(536870912UL, Assert.Single(command.DotnetSettings).Value); + } + + [Fact] + public void TheCommandLineTakesListsRepeatedAndMixed() + { + var command = CommandLine.Parse(["build", "//...", "--dotnet-settings", "GCHeapHardLimit=512M,ThreadPool.MinWorkerThreads=8", + "--dotnet-settings:GCSettings.LatencyMode=Interactive", "--dotnet-settings=GCHeapHardLimit=1G"]); + Assert.Equal(["GCHeapHardLimit", "ThreadPool.MinWorkerThreads", "GCSettings.LatencyMode", "GCHeapHardLimit"], + command.DotnetSettings.Select(setting => setting.Name)); + var error = Assert.Throws<CommandLineException>(() => CommandLine.Parse(["version", "--dotnet-settings=GCSettings.LatencyMode=Batch\\,Interactive"])); + Assert.Contains("not 'Batch,Interactive'", error.Message, StringComparison.Ordinal); + Assert.Contains("is not a .NET setting", Assert.Throws<CommandLineException>(() => + CommandLine.Parse(["version", "--dotnet-settings", "Nope=1"])).Message, StringComparison.Ordinal); + } + + [Fact] + public void TheOptionsFileTakesAListInAnyQuotes() + { + var options = TazelOptionsFile.Parse("dotnet-settings: [\n \"GCHeapHardLimit=512M\"\n 'GCSettings.LatencyMode=Interactive'\n `ThreadPool.MinWorkerThreads=8`\n]", + "tazel_options.txt", Path.Combine(Path.GetTempPath(), "tazel_options.txt")); + Assert.Equal(["GCHeapHardLimit", "GCSettings.LatencyMode", "ThreadPool.MinWorkerThreads"], options.DotnetSettings.Select(s => s.Name)); + Assert.Empty(TazelOptionsFile.Parse("platform: linux-amd64;", "tazel_options.txt", Path.Combine(Path.GetTempPath(), "tazel_options.txt")).DotnetSettings); + } + + [Theory] + [InlineData("dotnet-settings: GCHeapHardLimit;", "'[' to open the list")] + [InlineData("dotnet-settings: [\"GCHeapHardLimit=512M\", \"x\"];", "',' has no meaning here")] + [InlineData("dotnet-settings: [\"GCHeapHardLimit=512M\"", "ends with ]")] + [InlineData("dotnet-settings: [\"GCHeapHardLimit=lots\"];", "takes a size in bytes")] + [InlineData("dotnet-settings: [\"x\"];\ndotnet-settings: [];", "is not Name=Value")] + public void TheOptionsFileSaysWhatIsWrongWithTheList(string text, string message) + { + var error = Assert.Throws<TazelOptionsException>(() => + TazelOptionsFile.Parse(text, "tazel_options.txt", Path.Combine(Path.GetTempPath(), "tazel_options.txt"))); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task GetReadsThisProcessAndASettingDoesNotOutliveItsCommand() + { + using var module = new TemporaryModule(); + var (status, output) = await TazelProcess(module.Root, "dotnet", "get", "GCHeapHardLimit", "--dotnet-settings", "GCHeapHardLimit=512M"); + Assert.True(status == 0, output); + Assert.Contains("GCHeapHardLimit: 536870912", output, StringComparison.Ordinal); + (status, output) = await TazelProcess(module.Root, "dotnet", "get", "GCHeapHardLimit"); + Assert.Equal(0, status); + Assert.Contains("GCHeapHardLimit: default", output, StringComparison.Ordinal); + Assert.Contains("available to the GC:", output, StringComparison.Ordinal); + } + + [Fact] + public async Task TheFileComesFirstAndTheCommandLineAfter() + { + using var module = new TemporaryModule().Write("tazel_options.txt", + "dotnet-settings: [\"ThreadPool.MinWorkerThreads=6\" \"GCSettings.LatencyMode=Batch\"];"); + var (_, output) = await TazelProcess(module.Root, "dotnet", "get", "ThreadPool.MinWorkerThreads", "--dotnet-settings", "ThreadPool.MinWorkerThreads=7"); + Assert.Contains("ThreadPool.MinWorkerThreads: 7", output, StringComparison.Ordinal); + (_, output) = await TazelProcess(module.Root, "dotnet", "get", "GCSettings.LatencyMode"); + Assert.Contains("GCSettings.LatencyMode: Batch", output, StringComparison.Ordinal); + } + + [Fact] + public async Task AHeapLimitTheGCRefusesIsAnError() + { + using var module = new TemporaryModule(); + var (status, output) = await TazelProcess(module.Root, "dotnet", "get", "GCHeapHardLimit", "--dotnet-settings", "GCHeapHardLimit=1K"); + Assert.Equal(1, status); + Assert.Contains("error[E0506]: the GC took no new heap limit", output, StringComparison.Ordinal); + } + + [Theory] + [InlineData("GCHeapHardLimit")] + [InlineData("GCHeapHardLimitPOHPercent")] + [InlineData("GCSettings.LatencyMode")] + [InlineData("ThreadPool.MinWorkerThreads")] + [InlineData("ThreadPool.MaxCompletionPortThreads")] + public void GetKnowsEveryName(string name) => + Assert.StartsWith($"{name}: ", DotnetSettings.Get(name)[0], StringComparison.Ordinal); + + [Fact] + public void ThereAreThirteenSettings() => Assert.Equal(13, DotnetSettings.All.Count); + + [Fact] + public void TheGlossaryHasItsFourteenTermsOffline() + { + string[] terms = ["GCHeapHardLimit", "RyuJIT", ".NET", "CLI", "CIL", "CLR", "C++/CLI", "C#", "WorkstationGC", "BackgroundGC", + "daemon", "CTS", "VES", "ECMA-335"]; + Assert.Equal(terms, DotnetGlossary.Entries.Select(entry => entry.Term)); + Assert.All(DotnetGlossary.Entries, entry => Assert.EndsWith(".", entry.Text, StringComparison.Ordinal)); + var cli = DotnetGlossary.Find("CLI")!; + Assert.Equal("Common Language Infrastructure", cli.Title); + Assert.DoesNotContain("Command-Line Interface", cli.Text, StringComparison.OrdinalIgnoreCase); + Assert.Contains("no persistent daemon", DotnetGlossary.Find("daemon")!.Text, StringComparison.Ordinal); + Assert.Equal("CLI", DotnetGlossary.Nearest("cli")); + Assert.Equal("RyuJIT", DotnetGlossary.Nearest("RyuJT")); + } + + [Fact] + public async Task WhatIsAndGetGoThroughTheCommandLine() + { + using var module = new TemporaryModule(); + var (status, output) = await module.TazelAsync(".", "dotnet", "what-is", "C++/CLI"); + Assert.Equal(0, status); + Assert.Contains("A C++ language extension", output.Replace("An extension of C++", "A C++ language extension", StringComparison.Ordinal), StringComparison.Ordinal); + (status, output) = await module.TazelAsync(".", "dotnet", "what-is", "Cli"); + Assert.Equal(2, status); + Assert.Contains("did you mean CLI?", output, StringComparison.Ordinal); + Assert.IsType<DotnetGetCommand>(CommandLine.Parse(["dotnet", "get", "GCHeapHardLimit"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["dotnet", "get"])); + Assert.Throws<CommandLineException>(() => CommandLine.Parse(["dotnet", "what-is", "a", "b"])); + Assert.Contains("is not a .NET setting", Assert.Throws<DotnetSettingsException>(() => DotnetSettings.Get("gcServer")).Message, + StringComparison.Ordinal); + } + + [Fact] + public void TheHelpOfDotnetListsTheSettingsAndTheCommands() + { + var help = Help.Text("dotnet", true); + Assert.Contains("tazel dotnet get <setting>", help, StringComparison.Ordinal); + Assert.Contains("tazel dotnet what-is <term>", help, StringComparison.Ordinal); + Assert.Contains("--dotnet-settings", help, StringComparison.Ordinal); + Assert.Contains("This Tazel has no", help, StringComparison.Ordinal); + Assert.Equal(ErrorCodes.DotnetSettingRefused, ErrorCodes.Find(ErrorCodes.DotnetSettingRefused)!.Code); + } +}