tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Split the remaining long methods and fix the smaller findings
- Commit
78b26633272a1d6bc0b8aea436c7a457435171e1- Author
- Leitwolf11 ·
- Parents
7c7bd3be645e
Changes
src/Progmasoft.Tazel.Guest/Agent.cs | 5 + src/Progmasoft.Tazel.Guest/Libc.cs | 13 +- src/Progmasoft.Tazel.Guest/VsockStream.cs | 10 +- src/Progmasoft.Tazel/Archive/ModuleArchive.cs | 70 +++++--- src/Progmasoft.Tazel/Cli/Commands.cs | 43 ++--- src/Progmasoft.Tazel/Cli/MoreCommands.cs | 136 +++++++++------ src/Progmasoft.Tazel/Driver/Toolchains.cs | 64 +++---- src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs | 20 ++- .../Dsl/Custom/Lexer/CustomLexer.cs | 13 +- .../Dsl/Custom/Parser/CustomParser.cs | 2 +- src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs | 185 +++++++++++---------- src/Progmasoft.Tazel/Label/Labels.cs | 39 +++-- src/Progmasoft.Tazel/Output/Reporter.cs | 30 ++-- 13 files changed, 353 insertions(+), 277 deletions(-) diff --git a/src/Progmasoft.Tazel.Guest/Agent.cs b/src/Progmasoft.Tazel.Guest/Agent.cs index 363bbec..9e7da91 100644 --- a/src/Progmasoft.Tazel.Guest/Agent.cs +++ b/src/Progmasoft.Tazel.Guest/Agent.cs @@ -213,6 +213,9 @@ internal sealed class Agent(IReadOnlyList<Share> shares) case MessageKind.PowerOff: off.Set(); break; + default: + // A connection opens with Hello, Run or PowerOff; anything else is closed unanswered. + break; } } catch (Exception error) when (error is IOException or InvalidDataException or EndOfStreamException) @@ -284,6 +287,8 @@ internal sealed class Agent(IReadOnlyList<Share> shares) } catch (Exception error) when (error is IOException or InvalidDataException or EndOfStreamException) { + // The host went away: that is a stop too. + Console.Error.WriteLine($"tazel-guest: the host left while {program} ran: {error.Message}"); } if (!process.HasExited) diff --git a/src/Progmasoft.Tazel.Guest/Libc.cs b/src/Progmasoft.Tazel.Guest/Libc.cs index 90a5494..e49a605 100644 --- a/src/Progmasoft.Tazel.Guest/Libc.cs +++ b/src/Progmasoft.Tazel.Guest/Libc.cs @@ -68,12 +68,23 @@ internal static partial class Libc /// <summary><c>struct sockaddr_vm</c>.</summary> [StructLayout(LayoutKind.Sequential)] - public struct SockaddrVM + public struct SockaddrVM : IEquatable<SockaddrVM> { public ushort Family; public ushort Reserved; public uint Port; public uint Cid; public uint Zero; + + public static bool operator ==(SockaddrVM left, SockaddrVM right) => left.Equals(right); + + public static bool operator !=(SockaddrVM left, SockaddrVM right) => !left.Equals(right); + + public readonly bool Equals(SockaddrVM other) => + Family == other.Family && Reserved == other.Reserved && Port == other.Port && Cid == other.Cid && Zero == other.Zero; + + public override readonly bool Equals(object? obj) => obj is SockaddrVM other && Equals(other); + + public override readonly int GetHashCode() => HashCode.Combine(Family, Reserved, Port, Cid, Zero); } } diff --git a/src/Progmasoft.Tazel.Guest/VsockStream.cs b/src/Progmasoft.Tazel.Guest/VsockStream.cs index 833f12b..bd3f454 100644 --- a/src/Progmasoft.Tazel.Guest/VsockStream.cs +++ b/src/Progmasoft.Tazel.Guest/VsockStream.cs @@ -10,10 +10,10 @@ namespace Progmasoft.Tazel.Guest; /// <summary>A connected vsock socket as a stream, over read and write; .NET has no vsock address family.</summary> [System.Runtime.Versioning.SupportedOSPlatform("linux")] -internal sealed class VsockStream(int fd) : Stream +internal sealed class VsockStream(int socket) : Stream { private readonly Lock _writing = new(); - private int _fd = fd; + private int _fd = socket; public override bool CanRead => true; @@ -116,10 +116,10 @@ internal sealed class VsockStream(int fd) : Stream protected override void Dispose(bool disposing) { - var fd = Interlocked.Exchange(ref _fd, -1); - if (fd >= 0) + var closing = Interlocked.Exchange(ref _fd, -1); + if (closing >= 0) { - Libc.Close(fd); + Libc.Close(closing); } base.Dispose(disposing); diff --git a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs index 7f0cb9a..61306b0 100644 --- a/src/Progmasoft.Tazel/Archive/ModuleArchive.cs +++ b/src/Progmasoft.Tazel/Archive/ModuleArchive.cs @@ -78,12 +78,51 @@ internal static class ModuleArchive public static void Write(string root, string baseName, string archive, IReadOnlyList<string> files) => ReproducibleArchive.Write(root, baseName, archive, files); + /// <summary>The parts of the path of an entry, which must stay inside the archive.</summary> + private static string[] PartsOf(TarEntry entry, string shown) + { + var name = entry.Name.TrimEnd('/'); + var parts = name.Split('/'); + return name.Length == 0 || name.StartsWith('/') || name.Contains('\\', StringComparison.Ordinal) || + parts.Any(part => part is "" or "." or "..") + ? throw new ProjectException($"{shown}: '{entry.Name}' is not a path inside the archive") + : parts; + } + + /// <summary>Writes a directory or a file of the archive; anything else is refused. Returns the bytes written.</summary> + private static long Extract(TarEntry entry, string target, string shown) + { + if (entry.EntryType == TarEntryType.Directory) + { + Directory.CreateDirectory(target); + return 0; + } + + if (entry.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) + { + throw new ProjectException($"{shown}: '{entry.Name}' is a {entry.EntryType}; an archive holds only files"); + } + + // The size is checked before the bytes are written, so a huge entry is refused unwritten. + if (entry.Length > MaxUnpackedBytes) + { + throw new ProjectException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); + } + + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + entry.ExtractToFile(target, overwrite: false); + return entry.Length; + } + /// <summary> /// Unpacks <paramref name="archive"/> into <paramref name="destination"/>, which must not exist, and returns the /// directory of the module in it. Every entry must be below one top directory; links, devices, absolute paths and /// <c>..</c> are refused, as are archives over <see cref="MaxUnpackedBytes"/> or <see cref="MaxEntries"/>. /// </summary> - public static string Unpack(string archive, string destination, string requiredFile = ModuleFiles.ModuleFile) + public static string Unpack(string archive, string destination) => Unpack(archive, destination, ModuleFiles.ModuleFile); + + /// <inheritdoc cref="Unpack(string, string)"/> + public static string Unpack(string archive, string destination, string requiredFile) { var shown = Path.GetFileName(archive); var parent = Path.GetDirectoryName(Path.GetFullPath(destination))!; @@ -106,38 +145,17 @@ internal static class ModuleArchive throw new ProjectException($"{shown} holds more than {MaxEntries} entries"); } - var name = entry.Name.TrimEnd('/'); - var parts = name.Split('/'); - if (name.Length == 0 || name.StartsWith('/') || name.Contains('\\', StringComparison.Ordinal) || - parts.Any(part => part is "" or "." or "..")) - { - throw new ProjectException($"{shown}: '{entry.Name}' is not a path inside the archive"); - } - + var parts = PartsOf(entry, shown); top ??= parts[0]; if (parts[0] != top) { throw new ProjectException($"{shown}: '{entry.Name}' is not below {top}/"); } - var target = Path.Combine(work, Path.Combine(parts)); - switch (entry.EntryType) + total += Extract(entry, Path.Combine(work, Path.Combine(parts)), shown); + if (total > MaxUnpackedBytes) { - case TarEntryType.Directory: - Directory.CreateDirectory(target); - break; - case TarEntryType.RegularFile or TarEntryType.V7RegularFile: - total += entry.Length; - if (total > MaxUnpackedBytes) - { - throw new ProjectException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); - } - - Directory.CreateDirectory(Path.GetDirectoryName(target)!); - entry.ExtractToFile(target, overwrite: false); - break; - default: - throw new ProjectException($"{shown}: '{entry.Name}' is a {entry.EntryType}; an archive holds only files"); + throw new ProjectException($"{shown} unpacks to more than {MaxUnpackedBytes} bytes"); } } } diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index e8dd0c1..614c30b 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -37,7 +37,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector 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), + QueryCommand query => QueryAsync(query), FetchCommand => FetchAsync(), VendorCommand => VendorAsync(cancel), PortalModulesCommand portal => PortalModulesAsync(portal, cancel), @@ -151,6 +151,15 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector private async Task<int> CustomAsync(CustomCommandLine custom, CancellationToken cancel) { var (options, sandboxFile) = TazelOptionsFile.Effective(workingDirectory); + var (command, arguments) = FindCustom(custom.Words); + return sandboxFile is null + ? CustomOnHost(command, arguments) + : await CustomInMicroVMAsync(command, arguments, options, sandboxFile, cancel).ConfigureAwait(false); + } + + /// <summary>The command of tazel_custom.txt the words name, and its arguments, which must fit what it takes.</summary> + private (CustomCommand Command, IReadOnlyList<string> Arguments) FindCustom(IReadOnlyList<string> words) + { var file = Path.Combine(workingDirectory, CustomCommandFiles.FileName); if (!File.Exists(file)) { @@ -158,30 +167,24 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector } var commands = CustomParser.Parse(File.ReadAllText(file)); - if (custom.Words.Count > CustomCommandFiles.MaxArguments) + if (words.Count > CustomCommandFiles.MaxArguments) { throw new CommandLineException($"tazel custom takes at most {CustomCommandFiles.MaxArguments} words"); } - var match = commands.Matching(custom.Words) ?? throw new CustomCommandsException( - $"{CustomCommandFiles.FileName} has no command '{string.Join(' ', custom.Words.TakeWhile(w => w != CustomCommandFiles.NameEnd))}'" + - (Suggestions.Nearest(string.Join(' ', custom.Words), commands.Select(c => c.Name)) is { } near ? $"; did you mean '{near}'?" : "")); - var (command, arguments) = match; - if (arguments.Count < command.Required) - { - throw new CommandLineException($"'{command.Name}' needs {command.Required} arguments, and {arguments.Count} were given"); - } - - if (arguments.Count > command.Required && !command.TakesAll) - { - throw new CommandLineException($"'{command.Name}' takes {command.Required} arguments, and {arguments.Count} were given"); - } - - if (sandboxFile is not null) - { - return await CustomInMicroVMAsync(command, arguments, options, sandboxFile, cancel).ConfigureAwait(false); - } + var (command, arguments) = commands.Matching(words) ?? throw new CustomCommandsException( + $"{CustomCommandFiles.FileName} has no command '{string.Join(' ', words.TakeWhile(w => w != CustomCommandFiles.NameEnd))}'" + + (Suggestions.Nearest(string.Join(' ', words), commands.Select(c => c.Name)) is { } near ? $"; did you mean '{near}'?" : "")); + var fits = arguments.Count == command.Required || (arguments.Count > command.Required && command.TakesAll); + return fits + ? (command, arguments) + : throw new CommandLineException( + $"'{command.Name}' {(arguments.Count < command.Required ? "needs" : "takes")} {command.Required} arguments, and {arguments.Count} were given"); + } + /// <summary>Runs the steps on this machine, in order, until one fails.</summary> + private int CustomOnHost(CustomCommand command, IReadOnlyList<string> arguments) + { var environment = Processes.Inherited(); foreach (var step in command.Steps) { diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs index dcd67e7..bb17493 100644 --- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -24,7 +24,7 @@ namespace Progmasoft.Tazel.Cli; /// <summary>The queries, fetching and vendoring, and Tazel Portal Modules.</summary> internal sealed partial class Commands { - private async Task<int> QueryAsync(QueryCommand query, CancellationToken cancel) + private async Task<int> QueryAsync(QueryCommand query) { RefuseWithoutSandbox(); var (options, _) = TazelOptionsFile.Effective(workingDirectory); @@ -131,36 +131,46 @@ internal sealed partial class Commands private void Explain(ExplainCommand command) { var entry = ErrorCodes.Find(command.Code)!; - var console = reporter.Console; - var fancy = console.Profile.Capabilities.Unicode; - console.MarkupLine($"[red bold]{(fancy ? "✖ " : "")}{Markup.Escape(entry.Code)}[/]: [bold]{Markup.Escape(entry.Title)}[/] [grey]({Markup.Escape(entry.Where)})[/]"); - if (!command.Long) + var fancy = reporter.Console.Profile.Capabilities.Unicode; + reporter.Console.MarkupLine( + $"[red bold]{(fancy ? "✖ " : "")}{Markup.Escape(entry.Code)}[/]: [bold]{Markup.Escape(entry.Title)}[/] [grey]({Markup.Escape(entry.Where)})[/]"); + if (command.Long) { - var first = entry.Explanation.IndexOf(". ", StringComparison.Ordinal); - console.WriteLine(first < 0 ? entry.Explanation : entry.Explanation[..(first + 1)]); - if (entry.Right is not null) - { - console.MarkupLine($"[green]{(fancy ? "✔ " : "")}for example:[/] {Markup.Escape(entry.Right.Replace("\n", " ", StringComparison.Ordinal))}"); - } + ExplainLong(entry, fancy); + } + else + { + ExplainShort(entry, fancy); + } + } - console.MarkupLine($"[grey]More: tazel explain {entry.Code} --long[/]"); - return; + /// <summary>The first sentence of the explanation and the fixed text.</summary> + private void ExplainShort(ErrorCode entry, bool fancy) + { + var console = reporter.Console; + var first = entry.Explanation.IndexOf(". ", StringComparison.Ordinal); + console.WriteLine(first < 0 ? entry.Explanation : entry.Explanation[..(first + 1)]); + if (entry.Right is not null) + { + console.MarkupLine($"[green]{(fancy ? "✔ " : "")}for example:[/] {Markup.Escape(entry.Right.Replace("\n", " ", StringComparison.Ordinal))}"); } + console.MarkupLine($"[grey]More: tazel explain {entry.Code} --long[/]"); + } + + /// <summary>The whole explanation, the wrong and right text side by side, and the other codes of the same file.</summary> + private void ExplainLong(ErrorCode entry, bool fancy) + { + var console = reporter.Console; console.WriteLine(); console.WriteLine(entry.Explanation); if (entry.Wrong is not null && entry.Right is not null) { console.WriteLine(); - var wrong = new Panel(new Text(entry.Wrong)).Header(fancy ? " ✖ wrong " : " wrong ").BorderColor(Color.Red); - var right = new Panel(new Text(entry.Right)).Header(fancy ? " ✔ right " : " right ").BorderColor(Color.Green); - if (!fancy) + console.Write(new Columns(Example(entry.Wrong, "wrong", "✖", Color.Red, fancy), Example(entry.Right, "right", "✔", Color.Green, fancy)) { - wrong.Border = BoxBorder.Ascii; - right.Border = BoxBorder.Ascii; - } - - console.Write(new Columns(wrong, right) { Expand = false }); + Expand = false, + }); } var related = ErrorCodes.Codes.Where(other => other.Where == entry.Where && other.Code != entry.Code).Select(other => other.Code).ToList(); @@ -171,6 +181,14 @@ internal sealed partial class Commands } } + private static Panel Example(string text, string title, string mark, Color color, bool fancy) => + new Panel(new Text(text)) + { + Header = new PanelHeader(fancy ? $" {mark} {title} " : $" {title} "), + BorderStyle = new Style(color), + Border = fancy ? BoxBorder.Rounded : BoxBorder.Ascii, + }; + /// <summary> /// Runs the steps of a custom command inside a MicroVM that sees the module, or the directory of the command when /// it is in no module, and the host's /usr read-only; a shell step goes to the guest's /bin/sh. @@ -282,44 +300,57 @@ internal sealed partial class Commands var name = colon < 0 ? command.Query : command.Query[(colon + 1)..]; if (command.Action == PortalAction.Search) { - var catalog = await client.CatalogAsync(cancel).ConfigureAwait(false); - var found = catalog.Modules.Where(entry => command.Exact - ? entry.Group == group && entry.Module == name - : $"{entry.Group}:{entry.Module}".Contains(command.Query, StringComparison.OrdinalIgnoreCase)) - .OrderBy(entry => entry.Group, StringComparer.Ordinal).ThenBy(entry => entry.Module, StringComparer.Ordinal).ToList(); - if (found.Count == 0) - { - reporter.Warning($"Tazel Portal Modules has no module that matches {command.Query}"); - return 1; - } + return await SearchAsync(client, command, group, name, cancel).ConfigureAwait(false); + } - var table = new Table().Border(TableBorder.Rounded).AddColumn("Module").AddColumn("Latest").AddColumn("Description"); - foreach (var entry in found) - { - table.AddRow(Markup.Escape($"{entry.Group}:{entry.Module}"), Markup.Escape(entry.Latest ?? ""), - Markup.Escape(entry.Description ?? "")); - } + group ??= await GroupOfAsync(client, name, cancel).ConfigureAwait(false); + var index = await client.IndexAsync(group, name, cancel).ConfigureAwait(false) + ?? throw new ProjectException($"Tazel Portal Modules has no module {group}:{name}"); + ShowModule(index); + return 0; + } - reporter.Console.Write(table); - return 0; + private async Task<int> SearchAsync( + PortalModulesClient client, PortalModulesCommand command, string? group, string name, CancellationToken cancel) + { + var catalog = await client.CatalogAsync(cancel).ConfigureAwait(false); + var found = catalog.Modules.Where(entry => command.Exact + ? entry.Group == group && entry.Module == name + : $"{entry.Group}:{entry.Module}".Contains(command.Query, StringComparison.OrdinalIgnoreCase)) + .OrderBy(entry => entry.Group, StringComparer.Ordinal).ThenBy(entry => entry.Module, StringComparer.Ordinal).ToList(); + if (found.Count == 0) + { + reporter.Warning($"Tazel Portal Modules has no module that matches {command.Query}"); + return 1; } - if (group is null) + var table = new Table().Border(TableBorder.Rounded).AddColumn("Module").AddColumn("Latest").AddColumn("Description"); + foreach (var entry in found) { - // Without a group, the name must be one module's alone. - var catalog = await client.CatalogAsync(cancel).ConfigureAwait(false); - var groups = catalog.Modules.Where(entry => entry.Module == name).Select(entry => entry.Group).Distinct().Order().ToList(); - group = groups.Count switch - { - 0 => throw new ProjectException($"Tazel Portal Modules has no module {name}"), - 1 => groups[0], - _ => throw new CommandLineException( - $"{name} is a module of {string.Join(", ", groups)}; write the group: group:{name}"), - }; + table.AddRow(Markup.Escape($"{entry.Group}:{entry.Module}"), Markup.Escape(entry.Latest ?? ""), + Markup.Escape(entry.Description ?? "")); } - var index = await client.IndexAsync(group, name, cancel).ConfigureAwait(false) - ?? throw new ProjectException($"Tazel Portal Modules has no module {group}:{name}"); + reporter.Console.Write(table); + return 0; + } + + /// <summary>The group of a module named without one, which must be the only module of that name.</summary> + private static async Task<string> GroupOfAsync(PortalModulesClient client, string name, CancellationToken cancel) + { + var catalog = await client.CatalogAsync(cancel).ConfigureAwait(false); + var groups = catalog.Modules.Where(entry => entry.Module == name).Select(entry => entry.Group).Distinct().Order().ToList(); + return groups.Count switch + { + 0 => throw new ProjectException($"Tazel Portal Modules has no module {name}"), + 1 => groups[0], + _ => throw new CommandLineException($"{name} is a module of {string.Join(", ", groups)}; write the group: group:{name}"), + }; + } + + /// <summary>A module's latest version and a table of its versions, newest first.</summary> + private void ShowModule(ModuleIndex index) + { var highest = PortalModulesClient.Highest(index); reporter.Console.MarkupLine($"[bold]{Markup.Escape($"{index.Group}:{index.Module}")}[/]" + (highest is null ? "" : $" latest {Markup.Escape(highest.Version)}")); @@ -332,6 +363,5 @@ internal sealed partial class Commands } reporter.Console.Write(versions); - return 0; } } diff --git a/src/Progmasoft.Tazel/Driver/Toolchains.cs b/src/Progmasoft.Tazel/Driver/Toolchains.cs index b13641f..cd6d625 100644 --- a/src/Progmasoft.Tazel/Driver/Toolchains.cs +++ b/src/Progmasoft.Tazel/Driver/Toolchains.cs @@ -43,24 +43,9 @@ internal static class Host var extensions = IsWindows ? (Environment.GetEnvironmentVariable("PATHEXT") ?? ".EXE;.CMD;.BAT").Split(';', StringSplitOptions.RemoveEmptyEntries) : [""]; - foreach (var directory in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)) - { - if (directory.Length == 0) - { - continue; - } - - foreach (var extension in extensions.Prepend("")) - { - var candidate = Path.Combine(directory, name + extension); - if (File.Exists(candidate) && (IsWindows || IsExecutable(candidate))) - { - return candidate; - } - } - } - - return null; + return (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries) + .SelectMany(directory => extensions.Prepend("").Select(extension => Path.Combine(directory, name + extension))) + .FirstOrDefault(candidate => File.Exists(candidate) && (IsWindows || IsExecutable(candidate))); } private static bool IsExecutable(string file) => @@ -208,33 +193,34 @@ internal sealed class ToolchainChooser(Workspace workspace, Platform platform) } } - private CCToolchain HostCC(Family family) + private static CCToolchain? HostClang() { - RequireHost(family); - if (Host.Which("clang") is { } clang) + var clang = Host.Which("clang"); + var archiver = Host.Which("llvm-ar") ?? Host.Which("ar"); + if (clang is null || archiver is null) { - var clangxx = Host.Which("clang++") ?? clang; - var archiver = Host.Which("llvm-ar") ?? Host.Which("ar"); - if (archiver is not null) - { - return new CCToolchain("clang on PATH", new Tool(clang, []), new Tool(clangxx, []), new Tool(clangxx, []), - new Tool(archiver, []), []); - } + return null; } - if (family == Family.CC && Host.Which("gcc") is { } gcc && Host.Which("g++") is { } gxx && - (Host.Which("gcc-ar") ?? Host.Which("ar")) is { } ar) - { - return new CCToolchain("gcc on PATH", new Tool(gcc, []), new Tool(gxx, []), new Tool(gxx, []), new Tool(ar, []), []); - } + var clangxx = Host.Which("clang++") ?? clang; + return new CCToolchain("clang on PATH", new Tool(clang, []), new Tool(clangxx, []), new Tool(clangxx, []), new Tool(archiver, []), []); + } - if (family == Family.CC && Host.Which("zig") is { } zig) - { - return new CCToolchain("zig cc on PATH", new Tool(zig, ["cc"]), new Tool(zig, ["c++"]), new Tool(zig, ["c++"]), - new Tool(zig, ["ar"]), []); - } + private static CCToolchain? HostGcc() => + Host.Which("gcc") is { } gcc && Host.Which("g++") is { } gxx && (Host.Which("gcc-ar") ?? Host.Which("ar")) is { } ar + ? new CCToolchain("gcc on PATH", new Tool(gcc, []), new Tool(gxx, []), new Tool(gxx, []), new Tool(ar, []), []) + : null; - throw new ProjectException( + private static CCToolchain? HostZig() => + Host.Which("zig") is { } zig + ? new CCToolchain("zig cc on PATH", new Tool(zig, ["cc"]), new Tool(zig, ["c++"]), new Tool(zig, ["c++"]), new Tool(zig, ["ar"]), []) + : null; + + private CCToolchain HostCC(Family family) + { + RequireHost(family); + var found = HostClang() ?? (family == Family.CC ? HostGcc() ?? HostZig() : null); + return found ?? throw new ProjectException( $"no {FamilyName(family)} compiler on PATH (clang{(family == Family.CC ? ", gcc or zig" : "")}); " + "install one or register a toolchain in MODULE.csx"); } diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs b/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs index 9950f9e..c4f1271 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs @@ -6,6 +6,12 @@ using Progmasoft.Tazel.Dsl.Custom.Lexer; namespace Progmasoft.Tazel.Dsl.Custom; +/// <summary>Where a problem is: its line and column, from 1, and how many characters the mark covers.</summary> +/// <param name="Line">The line.</param> +/// <param name="Column">The column.</param> +/// <param name="Width">The width of the mark.</param> +public readonly record struct Place(int Line, int Column, int Width); + /// <summary> /// A problem in a file the user wrote, with all it takes to show it well: where it is, the line it is on, what to put /// under the mark, how to fix it, and a joke to soften the blow. @@ -26,18 +32,18 @@ public sealed record Diagnostic( /// <summary>The message with its place, as one plain line: <c>file:line:column: message</c>.</summary> public string Plain => $"{File}:{Line}:{Column}: {Message}"; - /// <summary>A problem at <paramref name="line"/>:<paramref name="column"/> of <paramref name="text"/>.</summary> + /// <summary>A problem at <paramref name="place"/> of <paramref name="text"/>.</summary> public static Diagnostic At( - string code, string text, string file, int line, int column, int width, string message, string label, string? help = null, - string? joke = null) + string code, string text, string file, Place place, string message, string label, string? help, string? joke) { ArgumentNullException.ThrowIfNull(text); - return new Diagnostic(code, file, line, column, Math.Max(1, width), LineOf(text, line), message, label, help, joke); + return new Diagnostic(code, file, place.Line, place.Column, Math.Max(1, place.Width), LineOf(text, place.Line), message, label, + help, joke); } /// <summary>A problem at <paramref name="token"/>, marking all of it, quotes too.</summary> public static Diagnostic AtToken( - string code, string text, string file, Token token, string message, string label, string? help = null, string? joke = null) + string code, string text, string file, Token token, string message, string label, string? help, string? joke) { ArgumentNullException.ThrowIfNull(token); var width = token.Kind switch @@ -46,12 +52,12 @@ public sealed record Diagnostic( TokenKind.Placeholder => token.Text.Length + 2, _ => token.Text.Length, }; - return At(code, text, file, token.Line, token.Column, width, message, label, help, joke); + return At(code, text, file, new Place(token.Line, token.Column, width), message, label, help, joke); } /// <summary>A problem just after <paramref name="token"/>, where something is missing.</summary> public static Diagnostic After( - string code, string text, string file, Token token, string message, string label, string? help = null, string? joke = null) + string code, string text, string file, Token token, string message, string label, string? help, string? joke) { ArgumentNullException.ThrowIfNull(token); var marked = AtToken(code, text, file, token, message, label, help, joke); diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs index 6b1e9bd..7967986 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs @@ -111,7 +111,7 @@ public sealed class CustomLexer(string text, string file) private CustomCommandsException Fail( string code, string message, int line, int column, int width, string label, string help, string joke) => - new(Diagnostic.At(code, text, file, line, column, width, message, label, help, joke)); + new(Diagnostic.At(code, text, file, new Place(line, column, width), message, label, help, joke)); private char Advance() { @@ -190,10 +190,7 @@ public sealed class CustomLexer(string text, string file) var value = text[begin.._position]; Advance(); - var valid = value == "*" || - (value.Length > 0 && value[0] != '0' && value.Length <= 3 && IsDigits(value) && - int.Parse(value, CultureInfo.InvariantCulture) <= CustomCommandFiles.MaxArguments); - if (!valid) + if (!IsPlaceholder(value)) { throw Fail( Output.ErrorCodes.PlaceholderOutOfRange, @@ -211,6 +208,12 @@ public sealed class CustomLexer(string text, string file) return new Token(TokenKind.Placeholder, value, line, column); } + /// <summary>Whether <paramref name="value"/> is <c>*</c> or a number from 1 to the most arguments, with no zero in front.</summary> + private static bool IsPlaceholder(string value) => + value == "*" || + (value.Length is > 0 and <= 3 && value[0] != '0' && IsDigits(value) && + int.Parse(value, CultureInfo.InvariantCulture) <= CustomCommandFiles.MaxArguments); + private static bool IsDigits(string value) { foreach (var letter in value) diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs index 2970f27..06bc521 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs @@ -127,7 +127,7 @@ public static class CustomParser if (token is null) { - throw new CustomCommandsException(Diagnostic.At(code, text, file, 1, 1, 1, $"expected {wanted}", + throw new CustomCommandsException(Diagnostic.At(code, text, file, new Place(1, 1, 1), $"expected {wanted}", "the file is empty here", help, Jokes.Missing(kind))); } diff --git a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs index c8c8e5b..1425de3 100644 --- a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs +++ b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs @@ -52,130 +52,139 @@ public static class TazelEnvsFile public static IReadOnlyList<EnvEntry> Parse(string text, string file) { ArgumentNullException.ThrowIfNull(text); - var tokens = new CustomLexer(text, file).Tokens(); - var entries = new List<EnvEntry>(); - var names = new Dictionary<string, Token>(StringComparer.Ordinal); - var i = 0; - while (i < tokens.Count) + return new Reader(new CustomLexer(text, file).Tokens(), text, file).Entries(); + } + + private sealed class Reader(IReadOnlyList<Token> tokens, string text, string file) + { + private int _position; + + public List<EnvEntry> Entries() { - var name = Take(TokenKind.Name, "the name of a value"); - if (names.TryGetValue(name.Text, out var first)) + var entries = new List<EnvEntry>(); + var names = new Dictionary<string, Token>(StringComparer.Ordinal); + while (_position < tokens.Count) { - throw Fail(Output.ErrorCodes.EnvsTwice, name, $"'{name.Text}' is set twice", "the second one", - $"keep one of them; the first is on line {first.Line}", - "Two values, one name. Tazel is not going to flip a coin."); + var name = Take(TokenKind.Name, "the name of a value"); + if (names.TryGetValue(name.Text, out var first)) + { + throw Fail(Output.ErrorCodes.EnvsTwice, name, $"'{name.Text}' is set twice", "the second one", + $"keep one of them; the first is on line {first.Line}", + "Two values, one name. Tazel is not going to flip a coin."); + } + + names[name.Text] = name; + Take(TokenKind.Colon, $"':' after {name.Text}"); + var value = Value(name); + Take(TokenKind.Semicolon, $"';' after the value of {name.Text}"); + entries.Add(new EnvEntry(name.Text, value, name.Line)); } - names[name.Text] = name; - Take(TokenKind.Colon, $"':' after {name.Text}"); - EnvValue value; - if (Peek() is { Kind: TokenKind.String } literal) + return entries; + } + + private Token? Peek => _position < tokens.Count ? tokens[_position] : null; + + /// <summary>A string, s("line") or ("program" "argument").</summary> + private EnvValue Value(Token name) + { + if (Peek is { Kind: TokenKind.String } literal) { - i++; - value = new EnvValue.Text(literal.Text); + _position++; + return new EnvValue.Text(literal.Text); } - else if (Peek() is { Kind: TokenKind.Name, Text: "s" }) + + if (Peek is { Kind: TokenKind.Name, Text: "s" }) { - i++; - var open = Take(TokenKind.Open, "'(' after s"); - var strings = Strings(); - Take(TokenKind.Close, "')' after the line of s(...)"); - value = strings.Count == 1 - ? new EnvValue.Shell(strings[0]) - : throw Fail(Output.ErrorCodes.EnvsShellOneLine, open, "s(...) takes one string, the whole line", "this s(...)", - $"write one line: {name.Text}: s(`echo $HOME`);", "One shell, one line. It is not a group chat."); + _position++; + return Shell(name); } - else if (Peek() is { Kind: TokenKind.Open }) + + if (Peek is { Kind: TokenKind.Open }) { - var open = Take(TokenKind.Open, "'('"); - var strings = Strings(); - Take(TokenKind.Close, "')' after the strings of a program"); - value = strings.Count > 0 - ? new EnvValue.Program(strings) - : throw Fail(Output.ErrorCodes.EnvsEmptyProgram, open, "a program names at least itself", "these parentheses are empty", - $"name the program first: {name.Text}: (\"rustc\" \"--version\");", - "Empty parentheses: a program that forgot its own name."); + return Program(name); } - else if (Peek() is { } stranger) + + if (Peek is { } stranger) { throw Fail(Output.ErrorCodes.EnvsNotAValue, stranger, $"expected the value of {name.Text}", "this is not a value", $"a value is a string, a program or a shell line: {name.Text}: '0.1.0'; or {name.Text}: (\"git\" \"describe\"); or {name.Text}: s(`date`);", stranger.Kind == TokenKind.Name ? $"'{stranger.Text}' without quotes is a name, and names are not values. Quotes, please!" : "Tazel expected a value and got something else entirely."); } - else - { - throw new CustomCommandsException(Diagnostic.After(Output.ErrorCodes.EnvsNoValue, text, file, tokens[i - 1], $"expected the value of {name.Text}", - "the value goes here", $"for example {name.Text}: '0.1.0';", "A name, a colon, and then... silence.")); - } - Take(TokenKind.Semicolon, $"';' after the value of {name.Text}"); - entries.Add(new EnvEntry(name.Text, value, name.Line)); + throw new CustomCommandsException(Diagnostic.After(Output.ErrorCodes.EnvsNoValue, text, file, tokens[_position - 1], + $"expected the value of {name.Text}", "the value goes here", $"for example {name.Text}: '0.1.0';", + "A name, a colon, and then... silence.")); } - return entries; - - Token? Peek() => i < tokens.Count ? tokens[i] : null; + private EnvValue Shell(Token name) + { + var open = Take(TokenKind.Open, "'(' after s"); + var strings = Strings(); + Take(TokenKind.Close, "')' after the line of s(...)"); + return strings.Count == 1 + ? new EnvValue.Shell(strings[0]) + : throw Fail(Output.ErrorCodes.EnvsShellOneLine, open, "s(...) takes one string, the whole line", "this s(...)", + $"write one line: {name.Text}: s(`echo $HOME`);", "One shell, one line. It is not a group chat."); + } - Token Take(TokenKind kind, string wanted) + private EnvValue Program(Token name) { - if (Peek() is { } token && token.Kind == kind) - { - i++; - return token; - } + var open = Take(TokenKind.Open, "'('"); + var strings = Strings(); + Take(TokenKind.Close, "')' after the strings of a program"); + return strings.Count > 0 + ? new EnvValue.Program(strings) + : throw Fail(Output.ErrorCodes.EnvsEmptyProgram, open, "a program names at least itself", "these parentheses are empty", + $"name the program first: {name.Text}: (\"rustc\" \"--version\");", + "Empty parentheses: a program that forgot its own name."); + } - var code = kind switch - { - TokenKind.Semicolon => Output.ErrorCodes.EnvsNoSemicolon, - TokenKind.Colon => Output.ErrorCodes.EnvsNoColon, - TokenKind.Close => Output.ErrorCodes.EnvsNoClose, - TokenKind.Open => Output.ErrorCodes.EnvsNoOpen, - _ => Output.ErrorCodes.EnvsUnexpected, - }; - var help = kind switch - { - TokenKind.Semicolon => "end every value with ';': example-version: '0.1.0';", - TokenKind.Colon => "a name and its value are joined by ':': example-version: '0.1.0';", - TokenKind.Close => "close it with ')'", - TokenKind.Open => "open it with '(': s(`date`)", - _ => "an entry is: name: value;", - }; - if (i > 0 && (Peek() is null || kind is TokenKind.Semicolon or TokenKind.Colon)) + private List<string> Strings() + { + var strings = new List<string>(); + while (Peek is { Kind: TokenKind.String } token) { - throw new CustomCommandsException(Diagnostic.After(code, text, file, tokens[i - 1], $"expected {wanted}", - kind switch - { - TokenKind.Semicolon => "a ';' goes here", - TokenKind.Colon => "a ':' goes here", - TokenKind.Close => "a ')' goes here", - _ => "something goes here", - }, - help, Jokes.Missing(kind))); + _position++; + strings.Add(token.Text); } - throw Fail(code, Peek()!, $"expected {wanted}", "not this", help, Jokes.Missing(kind)); + return Peek is { Kind: TokenKind.Placeholder } placeholder + ? throw Fail(Output.ErrorCodes.EnvsPlaceholder, placeholder, "a value of tazel_envs.txt takes no <N> or <*>", + "this placeholder", "write the argument itself, in quotes", "Nobody passes arguments to a file. It just sits there.") + : strings; } - List<string> Strings() + private Token Take(TokenKind kind, string wanted) { - var strings = new List<string>(); - while (Peek() is { Kind: TokenKind.String } token) + if (Peek is { } token && token.Kind == kind) { - i++; - strings.Add(token.Text); + _position++; + return token; } - if (Peek() is { Kind: TokenKind.Placeholder } placeholder) + var (code, label, help) = Missing(kind); + if (_position > 0 && (Peek is null || kind is TokenKind.Semicolon or TokenKind.Colon)) { - throw Fail(Output.ErrorCodes.EnvsPlaceholder, placeholder, "a value of tazel_envs.txt takes no <N> or <*>", "this placeholder", - "write the argument itself, in quotes", "Nobody passes arguments to a file. It just sits there."); + throw new CustomCommandsException(Diagnostic.After(code, text, file, tokens[_position - 1], $"expected {wanted}", + label, help, Jokes.Missing(kind))); } - return strings; + throw Fail(code, Peek!, $"expected {wanted}", "not this", help, Jokes.Missing(kind)); } - CustomCommandsException Fail(string code, Token token, string message, string label, string help, string joke) => + /// <summary>The code, the label of the gap, and the help for something missing.</summary> + private static (string Code, string Label, string Help) Missing(TokenKind kind) => kind switch + { + TokenKind.Semicolon => (Output.ErrorCodes.EnvsNoSemicolon, "a ';' goes here", "end every value with ';': example-version: '0.1.0';"), + TokenKind.Colon => (Output.ErrorCodes.EnvsNoColon, "a ':' goes here", "a name and its value are joined by ':': example-version: '0.1.0';"), + TokenKind.Close => (Output.ErrorCodes.EnvsNoClose, "a ')' goes here", "close it with ')'"), + TokenKind.Open => (Output.ErrorCodes.EnvsNoOpen, "something goes here", "open it with '(': s(`date`)"), + _ => (Output.ErrorCodes.EnvsUnexpected, "something goes here", "an entry is: name: value;"), + }; + + private CustomCommandsException 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/Label/Labels.cs b/src/Progmasoft.Tazel/Label/Labels.cs index 4637aac..43c6b06 100644 --- a/src/Progmasoft.Tazel/Label/Labels.cs +++ b/src/Progmasoft.Tazel/Label/Labels.cs @@ -80,6 +80,26 @@ public static partial class Labels ? label : throw new LabelException($"'{text}' names packages, not one target; write //dir:name"); + /// <summary>The dependency an @name label names, or null, and the rest of the label from its //.</summary> + private static (string? Repository, string Remainder) Repository(string text) + { + if (!text.StartsWith('@')) + { + return (null, text); + } + + var slashes = text.IndexOf("//", StringComparison.Ordinal); + return slashes < 0 + ? throw new LabelException($"'{text}' has no //; write @name//:target") + : (Checked(text[1..slashes], "dependency name", text), text[slashes..]); + } + + private static LabelException NoTarget(string text, string shown) + { + var last = shown[(shown.LastIndexOf('/') + 1)..]; + return new LabelException($"'{text}' names no target; write //{shown}:{last} or //{shown}/..."); + } + /// <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) { @@ -90,20 +110,7 @@ public static partial class Labels return new TargetLabel(current, Checked(text[1..], "target name", text)); } - string? repository = null; - var rest = text; - if (text.StartsWith('@')) - { - var slashes = text.IndexOf("//", StringComparison.Ordinal); - if (slashes < 0) - { - throw new LabelException($"'{text}' has no //; write @name//:target"); - } - - repository = Checked(text[1..slashes], "dependency name", text); - rest = text[slashes..]; - } - + var (repository, rest) = Repository(text); if (!rest.StartsWith("//", StringComparison.Ordinal)) { throw new LabelException($"'{text}' is not a label; write //dir:name, //:name or :name"); @@ -123,9 +130,7 @@ public static partial class Labels var colon = body.LastIndexOf(':'); if (colon < 0) { - var shown = body.TrimEnd('/'); - var last = shown[(shown.LastIndexOf('/') + 1)..]; - throw new LabelException($"'{text}' names no target; write //{shown}:{last} or //{shown}/..."); + throw NoTarget(text, body.TrimEnd('/')); } var directory = body[..colon]; diff --git a/src/Progmasoft.Tazel/Output/Reporter.cs b/src/Progmasoft.Tazel/Output/Reporter.cs index d2dd754..0b13325 100644 --- a/src/Progmasoft.Tazel/Output/Reporter.cs +++ b/src/Progmasoft.Tazel/Output/Reporter.cs @@ -154,43 +154,43 @@ internal sealed class Reporter /// A problem in a file the user wrote, drawn as a little picture: the line, a mark under the problem with what it /// says, how to fix it, and a light line. /// </summary> - public void Diagnostic(Dsl.Custom.Diagnostic diagnostic) + public void Diagnostic(Dsl.Custom.Diagnostic problem) { - ArgumentNullException.ThrowIfNull(diagnostic); + ArgumentNullException.ThrowIfNull(problem); lock (_lock) { var fancy = Console.Profile.Capabilities.Unicode; - var number = diagnostic.Line.ToString(System.Globalization.CultureInfo.InvariantCulture); + var number = problem.Line.ToString(System.Globalization.CultureInfo.InvariantCulture); var pad = new string(' ', number.Length); var bar = fancy ? "│" : "|"; - var before = new string(' ', Math.Max(0, diagnostic.Column - 1)); - var width = Math.Max(1, diagnostic.Width); + var before = new string(' ', Math.Max(0, problem.Column - 1)); + var width = Math.Max(1, problem.Width); string Gutter(string left) => $"[blue]{left} {bar}[/]"; - Console.MarkupLine($"[red bold]{(fancy ? "✖ " : "")}{Heading(diagnostic.Code)}[/] [bold]{Markup.Escape(diagnostic.Message)}[/]"); - Console.MarkupLine($"[blue]{pad} {(fancy ? "╭─[[" : ",-[[")}[/] [cyan]{Markup.Escape($"{Shown(diagnostic.File)}:{diagnostic.Line}:{diagnostic.Column}")}[/] [blue]]][/]"); + Console.MarkupLine($"[red bold]{(fancy ? "✖ " : "")}{Heading(problem.Code)}[/] [bold]{Markup.Escape(problem.Message)}[/]"); + Console.MarkupLine($"[blue]{pad} {(fancy ? "╭─[[" : ",-[[")}[/] [cyan]{Markup.Escape($"{Shown(problem.File)}:{problem.Line}:{problem.Column}")}[/] [blue]]][/]"); Console.MarkupLine(Gutter(pad)); - if (diagnostic.SourceLine.Length > 0 || diagnostic.Column == 1) + if (problem.SourceLine.Length > 0 || problem.Column == 1) { - Console.MarkupLine($"{Gutter(number)} {Markup.Escape(diagnostic.SourceLine)}"); + Console.MarkupLine($"{Gutter(number)} {Markup.Escape(problem.SourceLine)}"); var mark = fancy ? (width == 1 ? "┬" : new string('─', width / 2) + "┬" + new string('─', width - (width / 2) - 1)) : new string('^', width); var tee = fancy ? before + new string(' ', width / 2) : before; Console.MarkupLine($"{Gutter(pad)} [red bold]{Markup.Escape(before + mark)}[/]"); - Console.MarkupLine($"{Gutter(pad)} [red bold]{Markup.Escape(tee + (fancy ? "╰── " : "`-- "))}{Markup.Escape(diagnostic.Label)}[/]"); + Console.MarkupLine($"{Gutter(pad)} [red bold]{Markup.Escape(tee + (fancy ? "╰── " : "`-- "))}{Markup.Escape(problem.Label)}[/]"); Console.MarkupLine(Gutter(pad)); } - if (diagnostic.Help is not null) + if (problem.Help is not null) { - Console.MarkupLine($"[blue]{pad} {(fancy ? "├─" : "|-")}[/] [green]{(fancy ? "💡 " : "")}help:[/] {Markup.Escape(diagnostic.Help)}"); + Console.MarkupLine($"[blue]{pad} {(fancy ? "├─" : "|-")}[/] [green]{(fancy ? "💡 " : "")}help:[/] {Markup.Escape(problem.Help)}"); } - Console.MarkupLine($"[blue]{pad} {(fancy ? "├─" : "|-")}[/] [cyan]{(fancy ? "📖 " : "")}more:[/] tazel explain {diagnostic.Code}"); - if (diagnostic.Joke is not null) + Console.MarkupLine($"[blue]{pad} {(fancy ? "├─" : "|-")}[/] [cyan]{(fancy ? "📖 " : "")}more:[/] tazel explain {problem.Code}"); + if (problem.Joke is not null) { - Console.MarkupLine($"[blue]{pad} {(fancy ? "╰─" : "`-")}[/] [magenta italic]{(fancy ? "🎭 " : "")}{Markup.Escape(diagnostic.Joke)}[/]"); + Console.MarkupLine($"[blue]{pad} {(fancy ? "╰─" : "`-")}[/] [magenta italic]{(fancy ? "🎭 " : "")}{Markup.Escape(problem.Joke)}[/]"); } } }