Progmasoft Git

tazel

A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.

Clonegit clone https://git.progmasoft.com/tazel

Fix what Codacy found: simpler methods, overloads, plainer loops

- The command dispatcher, Host.Detect, PlanLink, Selector.Select and
  TestRunner.RunOneAsync hand their parts to methods of their own, each of
  them within the complexity limit.
- File names and limits of the text files are read-only properties, and
  optional parameters of Parse, TazelVersion and Plugin.From are overloads.
- The depfile and list readers step through their text without moving the
  loop counter in the body.
- TargetChecks checks each kind of settings in a method of its own; Labels
  and Selector read their choices as conditions.
- CommandLineException is public; the scope of an option is Scope, not
  Commands; Clean takes expunge; a test helper loses an unused parameter.
Commit
bb29c1e19035513e9ac5f63cb70622eeff83837b
Author
Leitwolf11 ·
Parents
39959f09e03d

Files · Download .tar.gz

Changes

 .../Module/Prelude/ModuleDsl.cs                    |   5 +-
 .../Module/Prelude/TazelVersion.cs                 |  25 +++-
 src/Progmasoft.Tazel/Cli/CommandLine.cs            |  22 +++-
 src/Progmasoft.Tazel/Cli/Commands.cs               |  55 ++++----
 src/Progmasoft.Tazel/Cli/Selector.cs               |  68 +++++-----
 src/Progmasoft.Tazel/Driver/Actions.cs             |  28 ++--
 src/Progmasoft.Tazel/Driver/CCPlanner.cs           |  79 ++++++-----
 src/Progmasoft.Tazel/Driver/TestRunner.cs          | 144 +++++++++++++--------
 src/Progmasoft.Tazel/Driver/Toolchains.cs          |  38 ++----
 src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs  |   6 +-
 .../Dsl/Custom/Parser/CustomParser.cs              |   5 +-
 src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs         |   7 +-
 src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs   |  10 +-
 src/Progmasoft.Tazel/Label/Labels.cs               |   8 +-
 src/Progmasoft.Tazel/Project/TargetChecks.cs       | 108 +++++++++-------
 tests/Progmasoft.Tazel.Tests/PlannerTests.cs       |   6 +-
 16 files changed, 347 insertions(+), 267 deletions(-)

diff --git a/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs b/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs
index 6a800d7..f6132e5 100644
--- a/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs
+++ b/src/Progmasoft.Tazel.Dsl/Module/Prelude/ModuleDsl.cs
@@ -295,7 +295,10 @@ public sealed class PluginReference
 public static class Plugin
 {
     /// <summary>The plugin <paramref name="group"/>.<paramref name="name"/>, at a version or the highest.</summary>
-    public static PluginReference From(string group, string name, string? version = null) =>
+    public static PluginReference From(string group, string name) => From(group, name, null);
+
+    /// <inheritdoc cref="From(string, string)"/>
+    public static PluginReference From(string group, string name, string? version) =>
         new(group, name, version, null);
 }
 
diff --git a/src/Progmasoft.Tazel.Dsl/Module/Prelude/TazelVersion.cs b/src/Progmasoft.Tazel.Dsl/Module/Prelude/TazelVersion.cs
index ab75d4a..a60297b 100644
--- a/src/Progmasoft.Tazel.Dsl/Module/Prelude/TazelVersion.cs
+++ b/src/Progmasoft.Tazel.Dsl/Module/Prelude/TazelVersion.cs
@@ -47,23 +47,38 @@ public sealed class TazelVersion
     public Version? Upper { get; }
 
     /// <summary>Only MAJOR.MINOR.PATCH.</summary>
-    public static TazelVersion Exactly(int major, int minor, int patch = 0) =>
+    public static TazelVersion Exactly(int major, int minor) => Exactly(major, minor, 0);
+
+    /// <inheritdoc cref="Exactly(int, int)"/>
+    public static TazelVersion Exactly(int major, int minor, int patch) =>
         new(VersionComparison.Exactly, Make(major, minor, patch), null);
 
     /// <summary>MAJOR.MINOR.PATCH or later.</summary>
-    public static TazelVersion AtLeast(int major, int minor, int patch = 0) =>
+    public static TazelVersion AtLeast(int major, int minor) => AtLeast(major, minor, 0);
+
+    /// <inheritdoc cref="AtLeast(int, int)"/>
+    public static TazelVersion AtLeast(int major, int minor, int patch) =>
         new(VersionComparison.AtLeast, Make(major, minor, patch), null);
 
     /// <summary>Later than MAJOR.MINOR.PATCH.</summary>
-    public static TazelVersion GreaterThan(int major, int minor, int patch = 0) =>
+    public static TazelVersion GreaterThan(int major, int minor) => GreaterThan(major, minor, 0);
+
+    /// <inheritdoc cref="GreaterThan(int, int)"/>
+    public static TazelVersion GreaterThan(int major, int minor, int patch) =>
         new(VersionComparison.GreaterThan, Make(major, minor, patch), null);
 
     /// <summary>MAJOR.MINOR.PATCH or earlier.</summary>
-    public static TazelVersion AtMost(int major, int minor, int patch = 0) =>
+    public static TazelVersion AtMost(int major, int minor) => AtMost(major, minor, 0);
+
+    /// <inheritdoc cref="AtMost(int, int)"/>
+    public static TazelVersion AtMost(int major, int minor, int patch) =>
         new(VersionComparison.AtMost, Make(major, minor, patch), null);
 
     /// <summary>Earlier than MAJOR.MINOR.PATCH.</summary>
-    public static TazelVersion LessThan(int major, int minor, int patch = 0) =>
+    public static TazelVersion LessThan(int major, int minor) => LessThan(major, minor, 0);
+
+    /// <inheritdoc cref="LessThan(int, int)"/>
+    public static TazelVersion LessThan(int major, int minor, int patch) =>
         new(VersionComparison.LessThan, Make(major, minor, patch), null);
 
     /// <summary>From MAJOR.MINOR to MAJOR.MINOR, both included.</summary>
diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs
index 89376a5..0caf9a3 100644
--- a/src/Progmasoft.Tazel/Cli/CommandLine.cs
+++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs
@@ -12,17 +12,20 @@ using Progmasoft.Tazel.Output;
 namespace Progmasoft.Tazel.Cli;
 
 /// <summary>A command line that cannot be taken, with a hint when there is one.</summary>
-internal sealed class CommandLineException : Exception
+public sealed class CommandLineException : Exception
 {
+    /// <summary>What cannot be taken, and how to put it right.</summary>
     public CommandLineException(string message)
         : base(message)
     {
     }
 
+    /// <summary>Nothing to say.</summary>
     public CommandLineException()
     {
     }
 
+    /// <summary>What cannot be taken, and why.</summary>
     public CommandLineException(string message, Exception inner)
         : base(message, inner)
     {
@@ -129,7 +132,7 @@ internal static class CommandLine
         List,
     }
 
-    private sealed record Option(string Long, Kind Kind, IReadOnlyList<string>? Values, params string[] Commands);
+    private sealed record Option(string Long, Kind Kind, IReadOnlyList<string>? Values, params string[] Scope);
 
     private static readonly string[] Building = ["build", "run", "test", "coverage", "cquery", "aquery"];
 
@@ -202,7 +205,7 @@ internal static class CommandLine
         command ??= "help";
         foreach (var (option, _, written) in seen)
         {
-            if (option.Commands.Length > 0 && !option.Commands.Contains(command, StringComparer.Ordinal))
+            if (option.Scope.Length > 0 && !option.Scope.Contains(command, StringComparer.Ordinal))
             {
                 throw new CommandLineException($"{written} is not an option of tazel {command}");
             }
@@ -303,14 +306,17 @@ internal static class CommandLine
         ArgumentNullException.ThrowIfNull(text);
         var items = new List<string>();
         var current = new StringBuilder();
-        for (var i = 0; i < text.Length; i++)
+        var i = 0;
+        while (i < text.Length)
         {
-            if (text[i] == '\\' && i + 1 < text.Length && text[i + 1] == ',')
+            if (text.AsSpan(i).StartsWith("\\,"))
             {
                 current.Append(',');
-                i++;
+                i += 2;
+                continue;
             }
-            else if (text[i] == ',')
+
+            if (text[i] == ',')
             {
                 items.Add(current.ToString());
                 current.Clear();
@@ -319,6 +325,8 @@ internal static class CommandLine
             {
                 current.Append(text[i]);
             }
+
+            i++;
         }
 
         items.Add(current.ToString());
diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs
index ad13661..ada470b 100644
--- a/src/Progmasoft.Tazel/Cli/Commands.cs
+++ b/src/Progmasoft.Tazel/Cli/Commands.cs
@@ -28,9 +28,28 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector
         typeof(Commands).Assembly.GetName().Version is { } version ? new Version(version.Major, version.Minor, version.Build) : new Version(0, 1, 0);
 
     /// <summary>Runs <paramref name="command"/>; the result is the exit status of tazel.</summary>
-    public async Task<int> RunAsync(Command command, CancellationToken cancel)
+    public Task<int> RunAsync(Command command, CancellationToken cancel)
     {
         ArgumentNullException.ThrowIfNull(command);
+        return command switch
+        {
+            BuildCommand build => BuildAsync(build.Labels, build.Flags, BuildKind.Build, null, cancel),
+            TestCommand test => BuildAsync(test.Labels, test.Flags, BuildKind.Test, null, cancel),
+            CoverageCommand coverage => BuildAsync(coverage.Labels, coverage.Flags, BuildKind.Coverage, null, cancel),
+            RunCommand run => BuildAsync(run.Label is null ? [] : [run.Label], run.Flags, BuildKind.Run, run.Arguments, cancel),
+            QueryCommand query => QueryAsync(query, cancel),
+            FetchCommand => FetchAsync(),
+            VendorCommand => VendorAsync(cancel),
+            PortalModulesCommand portal => PortalModulesAsync(portal, cancel),
+            PackageCommand => PackageAsync(),
+            CustomCommandLine custom => CustomAsync(custom, cancel),
+            _ => Task.FromResult(RunAtOnce(command)),
+        };
+    }
+
+    /// <summary>The commands that only print or remove, and need nothing to wait for.</summary>
+    private int RunAtOnce(Command command)
+    {
         switch (command)
         {
             case VersionCommand:
@@ -39,36 +58,16 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector
             case HelpCommand help:
                 reporter.Plain(Help.Text(help.Topic, help.Long));
                 return 0;
-            case CoverageCommand coverage:
-                return await BuildAsync(coverage.Labels, coverage.Flags, BuildKind.Coverage, null, cancel).ConfigureAwait(false);
-            case QueryCommand query:
-                return await QueryAsync(query, cancel).ConfigureAwait(false);
             case ExplainCommand explain:
                 Explain(explain);
                 return 0;
-            case FetchCommand:
-                return await FetchAsync().ConfigureAwait(false);
-            case VendorCommand:
-                return await VendorAsync(cancel).ConfigureAwait(false);
-            case PortalModulesCommand portal:
-                return await PortalModulesAsync(portal, cancel).ConfigureAwait(false);
+            case CleanCommand clean:
+                return Clean(clean.Expunge);
             case DaemonCommand daemon:
-                reporter.Error(ErrorCodes.NoDaemon, $"tazel dotnet {daemon.Action}: this Tazel runs every command in a process of its own and has no daemon", null,
+                reporter.Error(ErrorCodes.NoDaemon,
+                    $"tazel dotnet {daemon.Action}: this Tazel runs every command in a process of its own and has no daemon", null,
                     "Tazel is a morning person: awake at once, every time, no daemon needed.");
                 return 1;
-            case CleanCommand clean:
-                return Clean(clean);
-            case PackageCommand:
-                return await PackageAsync().ConfigureAwait(false);
-            case CustomCommandLine custom:
-                return await CustomAsync(custom, cancel).ConfigureAwait(false);
-            case BuildCommand build:
-                return await BuildAsync(build.Labels, build.Flags, BuildKind.Build, null, cancel).ConfigureAwait(false);
-            case TestCommand test:
-                return await BuildAsync(test.Labels, test.Flags, BuildKind.Test, null, cancel).ConfigureAwait(false);
-            case RunCommand run:
-                return await BuildAsync(run.Label is null ? [] : [run.Label], run.Flags, BuildKind.Run, run.Arguments, cancel)
-                    .ConfigureAwait(false);
             default:
                 throw new InvalidOperationException($"no handler for {command.GetType().Name}");
         }
@@ -116,11 +115,11 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector
         }
     }
 
-    private int Clean(CleanCommand clean)
+    private int Clean(bool expunge)
     {
         var root = ModuleFiles.FindRoot(workingDirectory);
         var state = Path.Combine(root, ModuleFiles.StateDirectory);
-        var removed = clean.Expunge
+        var removed = expunge
             ? [state]
             : new[] { "out", "testlogs", "coverage", "zig-cache", "package", "downloads" }.Select(name => Path.Combine(state, name)).ToArray();
         foreach (var directory in removed.Where(Directory.Exists))
@@ -128,7 +127,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector
             Directory.Delete(directory, recursive: true);
         }
 
-        reporter.Success(clean.Expunge ? $"removed {state}" : "removed the outputs");
+        reporter.Success(expunge ? $"removed {state}" : "removed the outputs");
         return 0;
     }
 
diff --git a/src/Progmasoft.Tazel/Cli/Selector.cs b/src/Progmasoft.Tazel/Cli/Selector.cs
index 43583a2..7332398 100644
--- a/src/Progmasoft.Tazel/Cli/Selector.cs
+++ b/src/Progmasoft.Tazel/Cli/Selector.cs
@@ -53,47 +53,49 @@ internal sealed class Selector(Workspace workspace, Platform platform)
                 throw new ProjectException(error.Message, error);
             }
 
-            switch (selection)
+            if (selection is TargetLabel label)
             {
-                case TargetLabel label:
-                    if (!workspace.Targets.TryGetValue(label, out var target))
-                    {
-                        var package = workspace.Packages.Contains(label.Package)
-                            ? $"its package has no target '{label.Name}'"
-                            : $"there is no package {label.Package}";
-                        throw new ProjectException($"{label} is not a target: {package}");
-                    }
-
-                    if (!wanted(target))
-                    {
-                        throw new ProjectException($"{label} is not {kind}");
-                    }
-
-                    if (Incompatibility(target) is { } reason)
-                    {
-                        throw new ProjectException($"{label} does not build for {platform.Name()}: {reason}");
-                    }
-
-                    if (!selected.Contains(target))
-                    {
-                        selected.Add(target);
-                    }
-
-                    break;
-                case PackagePattern pattern:
-                    if (!workspace.Packages.Any(pattern.Covers))
-                    {
-                        throw new ProjectException($"{pattern} names no package");
-                    }
+                var target = Named(label, wanted, kind);
+                if (!selected.Contains(target))
+                {
+                    selected.Add(target);
+                }
+            }
+            else if (selection is PackagePattern pattern)
+            {
+                if (!workspace.Packages.Any(pattern.Covers))
+                {
+                    throw new ProjectException($"{pattern} names no package");
+                }
 
-                    AddPattern(selected, target => pattern.Covers(target.Label.Package), wanted);
-                    break;
+                AddPattern(selected, target => pattern.Covers(target.Label.Package), wanted);
             }
         }
 
         return selected;
     }
 
+    /// <summary>The target <paramref name="label"/> names, which must be there, wanted and buildable for the platform.</summary>
+    private ProjectTarget Named(TargetLabel label, Func<ProjectTarget, bool> wanted, string kind)
+    {
+        if (!workspace.Targets.TryGetValue(label, out var target))
+        {
+            var package = workspace.Packages.Contains(label.Package)
+                ? $"its package has no target '{label.Name}'"
+                : $"there is no package {label.Package}";
+            throw new ProjectException($"{label} is not a target: {package}");
+        }
+
+        if (!wanted(target))
+        {
+            throw new ProjectException($"{label} is not {kind}");
+        }
+
+        return Incompatibility(target) is { } reason
+            ? throw new ProjectException($"{label} does not build for {platform.Name()}: {reason}")
+            : target;
+    }
+
     /// <summary>Why <paramref name="target"/> does not build for the platform, or null when it does.</summary>
     public string? Incompatibility(ProjectTarget target)
     {
diff --git a/src/Progmasoft.Tazel/Driver/Actions.cs b/src/Progmasoft.Tazel/Driver/Actions.cs
index 9dfd349..45dd149 100644
--- a/src/Progmasoft.Tazel/Driver/Actions.cs
+++ b/src/Progmasoft.Tazel/Driver/Actions.cs
@@ -236,37 +236,41 @@ internal static class Depfiles
         var body = text[(colon + 1)..];
         var inputs = new List<string>();
         var current = new StringBuilder();
-        for (var index = 0; index < body.Length; index++)
+        var index = 0;
+        while (index < body.Length)
         {
-            var c = body[index];
-            if (c == '\\' && index + 1 < body.Length && body[index + 1] == ' ')
+            var rest = body.AsSpan(index);
+            var step = 1;
+            if (rest.StartsWith("\\ "))
             {
                 current.Append(' ');
-                index++;
+                step = 2;
             }
-            else if (c == '\\' && index + 1 < body.Length && body[index + 1] == '\n')
+            else if (rest.StartsWith("\\\n"))
             {
                 Flush();
-                index++;
+                step = 2;
             }
-            else if (c == '\\' && index + 2 < body.Length && body[index + 1] == '\r' && body[index + 2] == '\n')
+            else if (rest.StartsWith("\\\r\n"))
             {
                 Flush();
-                index += 2;
+                step = 3;
             }
-            else if (c == '$' && index + 1 < body.Length && body[index + 1] == '$')
+            else if (rest.StartsWith("$$"))
             {
                 current.Append('$');
-                index++;
+                step = 2;
             }
-            else if (char.IsWhiteSpace(c))
+            else if (char.IsWhiteSpace(rest[0]))
             {
                 Flush();
             }
             else
             {
-                current.Append(c);
+                current.Append(rest[0]);
             }
+
+            index += step;
         }
 
         Flush();
diff --git a/src/Progmasoft.Tazel/Driver/CCPlanner.cs b/src/Progmasoft.Tazel/Driver/CCPlanner.cs
index f07cfe3..d20c164 100644
--- a/src/Progmasoft.Tazel/Driver/CCPlanner.cs
+++ b/src/Progmasoft.Tazel/Driver/CCPlanner.cs
@@ -235,51 +235,62 @@ internal sealed partial class Planner
         products.AlwaysLink = settings.AlwaysLink;
     }
 
-    private void PlanLink(
-        ProjectTarget target, CCToolchain toolchain, IReadOnlyList<Feature> features, TargetProducts products,
-        string directory, List<string> objects, List<BuildAction> compiles, bool shared)
+    /// <summary>The flags and names of a shared library: its file, what dependents link with, its soname links.</summary>
+    private (string Output, Action? After) SharedLibraryOutput(
+        ProjectTarget target, CCSharedLibrarySettings settings, TargetProducts products, string directory, List<string> command)
     {
-        var settings = (CCSettings)target.Settings;
-        var command = new List<string>(toolchain.Linker.Command);
-        command.AddRange(ModeFlags());
-        command.AddRange(Flags(features, shared ? CCAction.CppLinkSharedLibrary : CCAction.CppLinkExecutable));
-        string output;
-        Action? after = null;
-        if (shared)
+        var version = settings.LibraryVersion;
+        var (file, linkWith, soname) = SharedLibraryNames(directory, target.Label.Name, version);
+        var os = Options.Platform.GetOS();
+        if (os == OS.MacOS)
         {
-            var version = ((CCSharedLibrarySettings)settings).LibraryVersion;
-            var (file, linkWith, soname) = SharedLibraryNames(directory, target.Label.Name, version);
-            output = file;
-            var os = Options.Platform.GetOS();
-            command.Add(os == OS.MacOS ? "-dynamiclib" : "-shared");
-            if (os == OS.MacOS)
+            command.AddRange(["-dynamiclib", "-install_name", $"@rpath/{soname}"]);
+            if (version is not null)
             {
-                command.AddRange(["-install_name", $"@rpath/{soname}"]);
-                if (version is not null)
-                {
-                    command.AddRange(["-current_version", version.ToString(Math.Min(3, FieldCount(version))),
-                        "-compatibility_version", $"{version.Major}.0.0"]);
-                }
-            }
-            else if (os != OS.Windows && soname is not null)
-            {
-                command.Add($"-Wl,-soname,{soname}");
+                command.AddRange(["-current_version", version.ToString(Math.Min(3, FieldCount(version))),
+                    "-compatibility_version", $"{version.Major}.0.0"]);
             }
-
-            products.Library = linkWith;
-            products.IsShared = true;
-            after = SonameLinks(file, soname, target.Label.Name);
         }
         else
         {
-            output = $"{directory}/{ExecutableName(target.Label.Name)}";
-            products.Executable = output;
-            if (settings is CCExecutableSettings { LinkingMode: LinkingMode.FullyStatic })
+            command.Add("-shared");
+            if (os != OS.Windows && soname is not null)
             {
-                command.Add("-static");
+                command.Add($"-Wl,-soname,{soname}");
             }
         }
 
+        products.Library = linkWith;
+        products.IsShared = true;
+        return (file, SonameLinks(file, soname, target.Label.Name));
+    }
+
+    /// <summary>The file and flags of an executable.</summary>
+    private string ExecutableOutput(
+        ProjectTarget target, CCSettings settings, TargetProducts products, string directory, List<string> command)
+    {
+        var output = $"{directory}/{ExecutableName(target.Label.Name)}";
+        products.Executable = output;
+        if (settings is CCExecutableSettings { LinkingMode: LinkingMode.FullyStatic })
+        {
+            command.Add("-static");
+        }
+
+        return output;
+    }
+
+    private void PlanLink(
+        ProjectTarget target, CCToolchain toolchain, IReadOnlyList<Feature> features, TargetProducts products,
+        string directory, List<string> objects, List<BuildAction> compiles, bool shared)
+    {
+        var settings = (CCSettings)target.Settings;
+        var command = new List<string>(toolchain.Linker.Command);
+        command.AddRange(ModeFlags());
+        command.AddRange(Flags(features, shared ? CCAction.CppLinkSharedLibrary : CCAction.CppLinkExecutable));
+        var (output, after) = shared
+            ? SharedLibraryOutput(target, (CCSharedLibrarySettings)settings, products, directory, command)
+            : (ExecutableOutput(target, settings, products, directory, command), null);
+
         command.AddRange(["-o", output]);
         command.AddRange(objects);
         var (arguments, inputs, actions, directories) = LinkLibraries(target, directory);
diff --git a/src/Progmasoft.Tazel/Driver/TestRunner.cs b/src/Progmasoft.Tazel/Driver/TestRunner.cs
index d1dcf0a..54993ef 100644
--- a/src/Progmasoft.Tazel/Driver/TestRunner.cs
+++ b/src/Progmasoft.Tazel/Driver/TestRunner.cs
@@ -106,95 +106,127 @@ internal sealed class TestRunner(OutputLayout layout, int jobs, Reporter reporte
         return outcomes.OrderBy(o => o.Label, StringComparer.Ordinal).ToList();
     }
 
+    /// <summary>Where a test's runs go: its runfiles, its log directory, and the file that remembers its pass.</summary>
+    private sealed record TestRun(
+        ProjectTarget Target, ITestSettings Settings, TargetProducts Products, string Runfiles, string Logs, string Passed, string? Key)
+    {
+        public string Label => Target.Label.ToString();
+
+        public string LogFile => Path.Combine(Logs, "test.log");
+    }
+
     private async Task<TestOutcome> RunOneAsync(ProjectTarget target, TargetProducts products, CancellationToken cancel)
     {
         var settings = (ITestSettings)target.Settings;
         var runfiles = Runfiles.Prepare(target, products, layout);
-        var logDirectory = layout.Full($"{layout.TestLogs}/{Sanitize(target.Label.ToString())}");
-        var passedFile = Path.Combine(layout.Full(layout.TestLogs), ".passed", Sanitize(target.Label.ToString()).Replace('/', '_'));
+        var name = Sanitize(target.Label.ToString());
         // Coverage needs the run itself, and a test tagged no-cache runs every time.
         var key = coverage || target.Settings.Tags.Contains("no-cache", StringComparer.Ordinal)
             ? null
             : CacheKey(target, settings, products, runfiles);
-        if (key is not null && File.Exists(passedFile) &&
-            await File.ReadAllTextAsync(passedFile, cancel).ConfigureAwait(false) == key &&
-            File.Exists(Path.Combine(logDirectory, "test.log")))
+        var run = new TestRun(target, settings, products, runfiles, layout.Full($"{layout.TestLogs}/{name}"),
+            Path.Combine(layout.Full(layout.TestLogs), ".passed", name.Replace('/', '_')), key);
+        if (await CachedAsync(run, cancel).ConfigureAwait(false) is { } cached)
         {
-            var previous = await File.ReadAllTextAsync(Path.Combine(logDirectory, "test.log"), cancel).ConfigureAwait(false);
-            return new TestOutcome(target.Label.ToString(), TestStatus.Cached, TimeSpan.Zero, previous);
+            return cached;
         }
 
-        if (File.Exists(passedFile))
+        if (File.Exists(run.Passed))
         {
-            File.Delete(passedFile);
+            File.Delete(run.Passed);
         }
 
-        if (Directory.Exists(logDirectory))
+        if (Directory.Exists(run.Logs))
         {
-            Directory.Delete(logDirectory, recursive: true);
+            Directory.Delete(run.Logs, recursive: true);
         }
 
-        Directory.CreateDirectory(logDirectory);
-        var timeout = settings.Timeout ?? TimeoutOf(settings.TestSize);
+        Directory.CreateDirectory(run.Logs);
         var attempts = settings.Flaky ? 3 : 1;
         var watch = Stopwatch.StartNew();
         var log = new StringBuilder();
+        var timedOut = false;
         for (var attempt = 1; attempt <= attempts; attempt++)
         {
-            var failed = false;
-            var timedOut = false;
-            for (var shard = 0; shard < settings.ShardCount; shard++)
+            var (failed, outOfTime) = await AttemptAsync(run, log, cancel).ConfigureAwait(false);
+            timedOut = outOfTime;
+            await File.WriteAllTextAsync(run.LogFile, log.ToString(), cancel).ConfigureAwait(false);
+            if (!failed)
             {
-                var environment = Environment(target, settings, logDirectory, shard, runfiles);
-                if (coverage)
-                {
-                    // Each process of the test writes its own profile; tazel coverage merges them.
-                    environment["LLVM_PROFILE_FILE"] = System.IO.Path.Combine(logDirectory, $"coverage-{shard}-%p.profraw");
-                }
-
-                Runfiles.AddLibraryPath(environment, products, layout);
-                var command = new List<string> { layout.Full(products.Executable!) };
-                command.AddRange(settings.Arguments);
-                var result = await Processes.RunAsync(command, runfiles, environment, timeout, cancel).ConfigureAwait(false);
-                if (settings.ShardCount > 1)
-                {
-                    log.Append(CultureInfo.InvariantCulture, $"--- shard {shard + 1} of {settings.ShardCount} ---\n");
-                }
-
-                log.Append(result.Output);
-                if (result.TimedOut)
-                {
-                    log.Append(CultureInfo.InvariantCulture, $"the test ran out of its {timeout.TotalSeconds:0} s\n");
-                    timedOut = true;
-                }
-
-                failed |= result.ExitCode != 0;
+                return await PassedAsync(run, attempt == 1 ? TestStatus.Passed : TestStatus.Flaky, watch.Elapsed, log, cancel)
+                    .ConfigureAwait(false);
             }
 
-            await File.WriteAllTextAsync(Path.Combine(logDirectory, "test.log"), log.ToString(), cancel).ConfigureAwait(false);
-            if (!failed)
+            if (attempt < attempts)
+            {
+                log.Append(CultureInfo.InvariantCulture, $"--- attempt {attempt} failed; the test is flaky, so it runs again ---\n");
+            }
+        }
+
+        return new TestOutcome(run.Label, timedOut ? TestStatus.TimedOut : TestStatus.Failed, watch.Elapsed, log.ToString());
+    }
+
+    /// <summary>The outcome of a test that passed with the same key, or null when it has to run.</summary>
+    private static async Task<TestOutcome?> CachedAsync(TestRun run, CancellationToken cancel)
+    {
+        if (run.Key is null || !File.Exists(run.Passed) || !File.Exists(run.LogFile) ||
+            await File.ReadAllTextAsync(run.Passed, cancel).ConfigureAwait(false) != run.Key)
+        {
+            return null;
+        }
+
+        var previous = await File.ReadAllTextAsync(run.LogFile, cancel).ConfigureAwait(false);
+        return new TestOutcome(run.Label, TestStatus.Cached, TimeSpan.Zero, previous);
+    }
+
+    /// <summary>A test that passed; a first-time pass is remembered, a flaky one is not, so the next run shows it.</summary>
+    private static async Task<TestOutcome> PassedAsync(
+        TestRun run, TestStatus status, TimeSpan elapsed, StringBuilder log, CancellationToken cancel)
+    {
+        if (run.Key is not null && status == TestStatus.Passed)
+        {
+            Directory.CreateDirectory(Path.GetDirectoryName(run.Passed)!);
+            await File.WriteAllTextAsync(run.Passed, run.Key, cancel).ConfigureAwait(false);
+        }
+
+        return new TestOutcome(run.Label, status, elapsed, log.ToString());
+    }
+
+    /// <summary>One attempt: every shard of the test, each with its own environment.</summary>
+    private async Task<(bool Failed, bool TimedOut)> AttemptAsync(TestRun run, StringBuilder log, CancellationToken cancel)
+    {
+        var settings = run.Settings;
+        var timeout = settings.Timeout ?? TimeoutOf(settings.TestSize);
+        var failed = false;
+        var timedOut = false;
+        for (var shard = 0; shard < settings.ShardCount; shard++)
+        {
+            var environment = Environment(run.Target, settings, run.Logs, shard, run.Runfiles);
+            if (coverage)
+            {
+                // Each process of the test writes its own profile; tazel coverage merges them.
+                environment["LLVM_PROFILE_FILE"] = Path.Combine(run.Logs, $"coverage-{shard}-%p.profraw");
+            }
+
+            Runfiles.AddLibraryPath(environment, run.Products, layout);
+            List<string> command = [layout.Full(run.Products.Executable!), .. settings.Arguments];
+            var result = await Processes.RunAsync(command, run.Runfiles, environment, timeout, cancel).ConfigureAwait(false);
+            if (settings.ShardCount > 1)
             {
-                var status = attempt == 1 ? TestStatus.Passed : TestStatus.Flaky;
-                // A flaky pass is not remembered: the next run should show whether it is flaky still.
-                if (key is not null && status == TestStatus.Passed)
-                {
-                    Directory.CreateDirectory(Path.GetDirectoryName(passedFile)!);
-                    await File.WriteAllTextAsync(passedFile, key, cancel).ConfigureAwait(false);
-                }
-
-                return new TestOutcome(target.Label.ToString(), status, watch.Elapsed, log.ToString());
+                log.Append(CultureInfo.InvariantCulture, $"--- shard {shard + 1} of {settings.ShardCount} ---\n");
             }
 
-            if (attempt == attempts)
+            log.Append(result.Output);
+            if (result.TimedOut)
             {
-                return new TestOutcome(target.Label.ToString(), timedOut ? TestStatus.TimedOut : TestStatus.Failed,
-                    watch.Elapsed, log.ToString());
+                log.Append(CultureInfo.InvariantCulture, $"the test ran out of its {timeout.TotalSeconds:0} s\n");
+                timedOut = true;
             }
 
-            log.Append(CultureInfo.InvariantCulture, $"--- attempt {attempt} failed; the test is flaky, so it runs again ---\n");
+            failed |= result.ExitCode != 0;
         }
 
-        throw new InvalidOperationException("a test ended without an outcome");
+        return (failed, timedOut);
     }
 
     /// <summary>
diff --git a/src/Progmasoft.Tazel/Driver/Toolchains.cs b/src/Progmasoft.Tazel/Driver/Toolchains.cs
index 0f0ab4b..b13641f 100644
--- a/src/Progmasoft.Tazel/Driver/Toolchains.cs
+++ b/src/Progmasoft.Tazel/Driver/Toolchains.cs
@@ -69,33 +69,19 @@ internal static class Host
     private static Platform Detect()
     {
         var arm = RuntimeInformation.OSArchitecture == Architecture.Arm64;
-        if (OperatingSystem.IsWindows())
-        {
-            return arm ? Platform.WindowsArm64 : Platform.WindowsX64;
-        }
-
-        if (OperatingSystem.IsMacOS())
-        {
-            return arm ? Platform.MacOSArm64 : Platform.MacOSX86_64;
-        }
-
-        if (OperatingSystem.IsFreeBSD())
-        {
-            return arm ? Platform.FreeBSDAarch64 : Platform.FreeBSDAmd64;
-        }
-
         var description = RuntimeInformation.OSDescription;
-        if (description.Contains("OpenBSD", StringComparison.OrdinalIgnoreCase))
-        {
-            return arm ? Platform.OpenBSDAarch64 : Platform.OpenBSDAmd64;
-        }
-
-        if (description.Contains("DragonFly", StringComparison.OrdinalIgnoreCase))
-        {
-            return Platform.DragonFlyBSDAmd64;
-        }
-
-        return arm ? Platform.LinuxAarch64 : Platform.LinuxAmd64;
+        // The first system that is this one names the platform; Linux is what is left.
+        (bool Here, Platform Arm, Platform Other)[] systems =
+        [
+            (OperatingSystem.IsWindows(), Platform.WindowsArm64, Platform.WindowsX64),
+            (OperatingSystem.IsMacOS(), Platform.MacOSArm64, Platform.MacOSX86_64),
+            (OperatingSystem.IsFreeBSD(), Platform.FreeBSDAarch64, Platform.FreeBSDAmd64),
+            (description.Contains("OpenBSD", StringComparison.OrdinalIgnoreCase), Platform.OpenBSDAarch64, Platform.OpenBSDAmd64),
+            (description.Contains("DragonFly", StringComparison.OrdinalIgnoreCase), Platform.DragonFlyBSDAmd64, Platform.DragonFlyBSDAmd64),
+            (true, Platform.LinuxAarch64, Platform.LinuxAmd64),
+        ];
+        var (_, armPlatform, otherPlatform) = systems.First(system => system.Here);
+        return arm ? armPlatform : otherPlatform;
     }
 }
 
diff --git a/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs b/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs
index 9832911..27a6752 100644
--- a/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs
+++ b/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs
@@ -42,13 +42,13 @@ public sealed class CustomCommandsException : Exception
 public static class CustomCommandFiles
 {
     /// <summary>The file that holds the commands of <c>tazel custom</c>, in the directory they run in.</summary>
-    public const string FileName = "tazel_custom.txt";
+    public static string FileName { get; } = "tazel_custom.txt";
 
     /// <summary>The most words <c>tazel custom</c> takes, those of the name of the command included.</summary>
-    public const int MaxArguments = 191;
+    public static int MaxArguments { get; } = 191;
 
     /// <summary>Ends the name of a custom command on the command line; what follows it is arguments.</summary>
-    public const string NameEnd = "--";
+    public static string NameEnd { get; } = "--";
 }
 
 /// <summary>One argument of a program in a custom command.</summary>
diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs
index abe49a2..2970f27 100644
--- a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs
+++ b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs
@@ -13,7 +13,10 @@ namespace Progmasoft.Tazel.Dsl.Custom.Parser;
 public static class CustomParser
 {
     /// <summary>The commands of the text of a <c>tazel_custom.txt</c>, in the order they are written.</summary>
-    public static IReadOnlyList<CustomCommand> Parse(string text, string file = CustomCommandFiles.FileName) =>
+    public static IReadOnlyList<CustomCommand> Parse(string text) => Parse(text, CustomCommandFiles.FileName);
+
+    /// <summary>The commands of <paramref name="text"/>; <paramref name="file"/> names it in messages.</summary>
+    public static IReadOnlyList<CustomCommand> Parse(string text, string file) =>
         new Reader(new CustomLexer(text, file).Tokens(), file, text).Commands();
 
     private sealed class Reader(IReadOnlyList<Token> tokens, string file, string text)
diff --git a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs
index ca42d26..c8c8e5b 100644
--- a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs
+++ b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs
@@ -43,10 +43,13 @@ public sealed record EnvEntry(string Name, EnvValue Value, int Line);
 public static class TazelEnvsFile
 {
     /// <summary>The file, beside the MODULE.csx of a module.</summary>
-    public const string FileName = "tazel_envs.txt";
+    public static string FileName { get; } = "tazel_envs.txt";
+
+    /// <summary>The entries of <paramref name="text"/>, named tazel_envs.txt in messages.</summary>
+    public static IReadOnlyList<EnvEntry> Parse(string text) => Parse(text, FileName);
 
     /// <summary>The entries of <paramref name="text"/>; <paramref name="file"/> names it in messages.</summary>
-    public static IReadOnlyList<EnvEntry> Parse(string text, string file = FileName)
+    public static IReadOnlyList<EnvEntry> Parse(string text, string file)
     {
         ArgumentNullException.ThrowIfNull(text);
         var tokens = new CustomLexer(text, file).Tokens();
diff --git a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs
index 00c8a30..5db7616 100644
--- a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs
+++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs
@@ -24,7 +24,7 @@ public sealed record Allocation(int? Amount)
 public sealed record TazelOptions
 {
     /// <summary>The file of the options of Tazel, in a directory a command runs in or above it.</summary>
-    public const string FileName = "tazel_options.txt";
+    public static string FileName { get; } = "tazel_options.txt";
 
     /// <summary>
     /// Whether what a project brings to run, custom commands and the build among it, runs inside a MicroVM.
@@ -86,10 +86,12 @@ public static class TazelOptionsFile
         ["sandboxing-with-microvm", "microvm-network", "microvm-memory", "microvm-cpus", "platform"];
 
     /// <summary>
-    /// Reads the text of a <c>tazel_options.txt</c>, with the comments and strings of <c>tazel_custom.txt</c>;
-    /// <paramref name="file"/> names it in messages.
+    /// Reads the text of a <c>tazel_options.txt</c>, with the comments and strings of <c>tazel_custom.txt</c>.
     /// </summary>
-    public static TazelOptions Parse(string text, string file = TazelOptions.FileName)
+    public static TazelOptions Parse(string text) => Parse(text, TazelOptions.FileName);
+
+    /// <summary>The options of <paramref name="text"/>; <paramref name="file"/> names it in messages.</summary>
+    public static TazelOptions Parse(string text, string file)
     {
         IReadOnlyList<Token> tokens;
         try
diff --git a/src/Progmasoft.Tazel/Label/Labels.cs b/src/Progmasoft.Tazel/Label/Labels.cs
index 2e6d8b5..4637aac 100644
--- a/src/Progmasoft.Tazel/Label/Labels.cs
+++ b/src/Progmasoft.Tazel/Label/Labels.cs
@@ -76,11 +76,9 @@ public static partial class Labels
 {
     /// <summary>A target label; <c>:name</c> is a target of <paramref name="current"/>. Patterns are refused.</summary>
     public static TargetLabel Target(string text, PackageId current) =>
-        Selection(text, current) switch
-        {
-            TargetLabel label => label,
-            _ => throw new LabelException($"'{text}' names packages, not one target; write //dir:name"),
-        };
+        Selection(text, current) is TargetLabel label
+            ? label
+            : throw new LabelException($"'{text}' names packages, not one target; write //dir:name");
 
     /// <summary>A target label or a package pattern; <c>:name</c> is a target of <paramref name="current"/>.</summary>
     public static Selection Selection(string text, PackageId current)
diff --git a/src/Progmasoft.Tazel/Project/TargetChecks.cs b/src/Progmasoft.Tazel/Project/TargetChecks.cs
index 7e05b43..46e6cdd 100644
--- a/src/Progmasoft.Tazel/Project/TargetChecks.cs
+++ b/src/Progmasoft.Tazel/Project/TargetChecks.cs
@@ -13,69 +13,83 @@ internal static class TargetChecks
 {
     public static void Check(ProjectTarget target)
     {
+        ArgumentNullException.ThrowIfNull(target);
         var place = target.Place;
-        switch (target.Settings)
+        if (target.Settings is ZigModuleSettings zig)
         {
-            case ZigModuleSettings zig:
-                if (zig.RootSourceFile.Length == 0)
-                {
-                    throw new ProjectException($"{place}: {target.Label} needs its RootSourceFile");
-                }
+            CheckZig(target, zig, place);
+        }
+        else if (target.Settings is CCSettings cc)
+        {
+            CheckMacros(cc, place);
+        }
 
-                if (!zig.RootSourceFile.EndsWith(".zig", StringComparison.Ordinal))
-                {
-                    throw new ProjectException($"{place}: the RootSourceFile '{zig.RootSourceFile}' is not a .zig file");
-                }
+        if (target.Settings is ITestSettings test)
+        {
+            CheckTest(test, place);
+        }
 
-                foreach (var name in zig.ModuleImports.Keys)
-                {
-                    if (name.Length == 0 || !name.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'))
-                    {
-                        throw new ProjectException($"{place}: '{name}' cannot be the name of an @import");
-                    }
-                }
+        if (target.Family == Family.Plugin)
+        {
+            CheckStepOutputs((PluginApi.Steps.StepSettings)target.Settings, place);
+        }
 
-                break;
-            case CCSettings cc:
-                foreach (var option in cc.PreprocessorDefinitions.Concat(cc.LocalPreprocessorDefinitions))
-                {
-                    if (option.Length == 0 || option.StartsWith('-'))
-                    {
-                        throw new ProjectException($"{place}: '{option}' is not a macro; write NAME or NAME=value");
-                    }
-                }
+        if (target.Family == Family.Zig && target.Settings is not ZigModuleSettings)
+        {
+            throw new ProjectException($"{place}: {target.Label} has settings of another family");
+        }
+    }
 
-                break;
+    private static void CheckZig(ProjectTarget target, ZigModuleSettings zig, string place)
+    {
+        if (zig.RootSourceFile.Length == 0)
+        {
+            throw new ProjectException($"{place}: {target.Label} needs its RootSourceFile");
         }
 
-        if (target.Settings is ITestSettings test)
+        if (!zig.RootSourceFile.EndsWith(".zig", StringComparison.Ordinal))
         {
-            if (test.ShardCount < 1)
-            {
-                throw new ProjectException($"{place}: ShardCount is at least 1");
-            }
+            throw new ProjectException($"{place}: the RootSourceFile '{zig.RootSourceFile}' is not a .zig file");
+        }
 
-            if (test.Timeout is { } timeout && timeout <= TimeSpan.Zero)
-            {
-                throw new ProjectException($"{place}: Timeout must be longer than nothing");
-            }
+        var bad = zig.ModuleImports.Keys.FirstOrDefault(name => name.Length == 0 || !name.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'));
+        if (bad is not null)
+        {
+            throw new ProjectException($"{place}: '{bad}' cannot be the name of an @import");
         }
+    }
 
-        if (target.Family == Family.Plugin)
+    private static void CheckMacros(CCSettings cc, string place)
+    {
+        var bad = cc.PreprocessorDefinitions.Concat(cc.LocalPreprocessorDefinitions)
+            .FirstOrDefault(option => option.Length == 0 || option.StartsWith('-'));
+        if (bad is not null)
         {
-            foreach (var output in ((PluginApi.Steps.StepSettings)target.Settings).Outputs)
-            {
-                if (output.Length == 0 || System.IO.Path.IsPathRooted(output) || output.Contains('\\', StringComparison.Ordinal) ||
-                    output.Split('/').Any(part => part is "" or "." or ".."))
-                {
-                    throw new ProjectException($"{place}: the output '{output}' must be a path below the step's output directory");
-                }
-            }
+            throw new ProjectException($"{place}: '{bad}' is not a macro; write NAME or NAME=value");
         }
+    }
 
-        if (target.Family == Family.Zig && target.Settings is not ZigModuleSettings)
+    private static void CheckTest(ITestSettings test, string place)
+    {
+        if (test.ShardCount < 1)
         {
-            throw new ProjectException($"{place}: {target.Label} has settings of another family");
+            throw new ProjectException($"{place}: ShardCount is at least 1");
+        }
+
+        if (test.Timeout is { } timeout && timeout <= TimeSpan.Zero)
+        {
+            throw new ProjectException($"{place}: Timeout must be longer than nothing");
+        }
+    }
+
+    private static void CheckStepOutputs(PluginApi.Steps.StepSettings step, string place)
+    {
+        var bad = step.Outputs.FirstOrDefault(output =>
+            output.Length == 0 || System.IO.Path.IsPathRooted(output) || output.Contains('\\', StringComparison.Ordinal) ||
+            output.Split('/').Any(part => part is "" or "." or ".."));
+        if (bad is not null)
+        {
+            throw new ProjectException($"{place}: the output '{bad}' must be a path below the step's output directory");
         }
     }
 }
diff --git a/tests/Progmasoft.Tazel.Tests/PlannerTests.cs b/tests/Progmasoft.Tazel.Tests/PlannerTests.cs
index 45bb2ac..3e1e388 100644
--- a/tests/Progmasoft.Tazel.Tests/PlannerTests.cs
+++ b/tests/Progmasoft.Tazel.Tests/PlannerTests.cs
@@ -18,7 +18,7 @@ namespace Progmasoft.Tazel.Tests;
 /// <summary>The command lines a build makes, for a toolchain of files that are never run, so they are the same everywhere.</summary>
 public sealed class PlannerTests
 {
-    private static string ModuleWithToolchain(string root) => TemporaryModule.ModuleFile + """
+    private static string ModuleWithToolchain() => TemporaryModule.ModuleFile + """
 
         toolchains = Toolchains.Define("//toolchains:fake", "//toolchains:zig");
         """;
@@ -99,7 +99,7 @@ public sealed class PlannerTests
     public async Task TheCommandsOfABuild()
     {
         using var module = new TemporaryModule();
-        module.Write("MODULE.csx", ModuleWithToolchain(module.Root))
+        module.Write("MODULE.csx", ModuleWithToolchain())
             .Write("toolchains/BUILD.csx", Toolchain(module.Root))
             .Write("BUILD.csx", Build)
             .Write("src/a.cpp", "").Write("src/b.cpp", "").Write("src/shared.c", "").Write("src/main.cc", "")
@@ -136,7 +136,7 @@ public sealed class PlannerTests
     public async Task AFeatureATargetNamesMustBeInItsToolchain()
     {
         using var module = new TemporaryModule();
-        module.Write("MODULE.csx", ModuleWithToolchain(module.Root))
+        module.Write("MODULE.csx", ModuleWithToolchain())
             .Write("toolchains/BUILD.csx", Toolchain(module.Root))
             .Write("BUILD.csx", "using Progmasoft.Tazel.Dsl.Build.Prelude;\nCC.StaticLibrary(\"x\", new() { Features = [CC.Enable(\"asan\")] });")
             .Write("tools/cc", "").Write("tools/c++", "").Write("tools/llvm-ar", "").Write("tools/zig", "");