tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Give every error a code and add tazel explain
- Commit
f433ebe1b3082b7c25db4cdb0e523df406e1da2e- Author
- Leitwolf11 ·
- Parents
fb5357e53084
Changes
CHANGELOG.md | 2 + docs/commands.md | 26 ++- src/Progmasoft.Tazel/Cli/CommandLine.cs | 30 ++- src/Progmasoft.Tazel/Cli/Commands.cs | 9 +- src/Progmasoft.Tazel/Cli/Help.cs | 18 ++ src/Progmasoft.Tazel/Cli/MoreCommands.cs | 44 ++++ src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs | 15 +- .../Dsl/Custom/Lexer/CustomLexer.cs | 13 +- .../Dsl/Custom/Parser/CustomParser.cs | 33 ++- src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs | 28 ++- src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs | 30 ++- src/Progmasoft.Tazel/Output/ErrorCodes.cs | 260 +++++++++++++++++++++ src/Progmasoft.Tazel/Output/Reporter.cs | 12 +- src/Progmasoft.Tazel/Program.cs | 16 +- tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs | 65 +++++- 15 files changed, 535 insertions(+), 66 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4330104..0dea928 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ The first version of Tazel, written in C# for .NET 10. - An action cache by content, depfiles for headers, parallel actions, runfiles, sharded and flaky tests. - Reproducible `.tazel.tar.xz` archives of modules, and dependencies on them checked by SHA-256. - `tazel_options.txt` (with `platform:`), `tazel_custom.txt`, and `tazel_envs.txt` with `GetEnvironment.From`. +- Errors with codes (`error[E0406]:`), the line and a mark under the problem, help, and `tazel explain <code>` + with `--long`. - `tazel coverage` (LLVM source-based, an LCOV report), `tazel query`, `cquery` and `aquery`, `tazel fetch`, `tazel vendor`, and `tazel portal-modules search` and `info`; `tazel help --long`. - Modules of Tazel Portal Modules as dependencies: each at the highest version asked for, checked by SHA-256, diff --git a/docs/commands.md b/docs/commands.md index d3426d5..5955901 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -176,11 +176,12 @@ var exampleVersion = GetEnvironment.From("example-version"); // "0.1.0"; null fo ## Errors -An error in `tazel_envs.txt`, `tazel_custom.txt` or `tazel_options.txt` shows where it is, the line, a mark under -the problem, how to fix it and a light line: +Every error has a code, `E` and four digits, written as `error[E0406]:`. An error in `tazel_envs.txt`, +`tazel_custom.txt` or `tazel_options.txt` shows where it is, the line, a mark under the problem, how to fix it, where +to read more, and a light line: ```text -✖ error: expected ';' after the value of example-version +✖ error[E0406]: expected ';' after the value of example-version ╭─[ tazel_envs.txt:1:25 ] │ 1 │ example-version: '0.1.0' @@ -188,9 +189,24 @@ the problem, how to fix it and a light line: │ ╰── a ';' goes here │ ├─ 💡 help: end every value with ';': example-version: '0.1.0'; + ├─ 📖 more: tazel explain E0406 ╰─ 🎭 Semicolons are small, but they hold this whole file together. ``` -A terminal without Unicode gets the same picture in ASCII. Other errors say what went wrong, where to read more -when there is a place, and a light line too; the same problem always gets the same line. +A terminal without Unicode gets the same picture in ASCII. Other errors say what went wrong, how to fix it where +there is a way, where to read more, and a light line too; the same problem always gets the same line. +`tazel explain E0406` prints what a code means with a fixed example; `tazel explain E0406 --long` says why and shows +the wrong text and the right one side by side. The first two digits say where an error comes from: + +| Codes | From | +| --- | --- | +| `E00xx` | the text files: their comments, strings and placeholders | +| `E01xx` | the command line | +| `E02xx` | `tazel_options.txt` | +| `E03xx` | `tazel_custom.txt` | +| `E04xx` | `tazel_envs.txt` | +| `E05xx` | `MODULE.csx`, `BUILD.csx` and builds | +| `E06xx` | labels | + +A code, once given, keeps its meaning. diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 340fc58..89376a5 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -93,6 +93,8 @@ internal sealed record QueryCommand(OutputOptions Output, QueryKind Kind, string internal sealed record FetchCommand(OutputOptions Output) : Command(Output); +internal sealed record ExplainCommand(OutputOptions Output, string Code, bool Long) : Command(Output); + internal sealed record VendorCommand(OutputOptions Output) : Command(Output); /// <summary>Searching Tazel Portal Modules, or the versions of one module.</summary> @@ -118,7 +120,7 @@ internal static class CommandLine /// <summary>The commands, as <c>tazel help</c> lists them.</summary> public static IReadOnlyList<string> Commands { get; } = ["build", "run", "test", "coverage", "query", "cquery", "aquery", "fetch", "vendor", "clean", "package", "custom", - "portal-modules", "version", "help", "dotnet"]; + "portal-modules", "explain", "version", "help", "dotnet"]; private enum Kind { @@ -149,7 +151,7 @@ internal static class CommandLine new("linker-options", Kind.List, null, Building), new("zig-compiler-options", Kind.List, null, Building), new("expunge", Kind.Flag, null, "clean"), - new("long", Kind.Flag, null, "help"), + new("long", Kind.Flag, null, "help", "explain"), new("exact", Kind.Flag, null, "portal-modules"), new("output", Kind.Value, ["label", "label_kind"], "query", "cquery", "aquery"), ]; @@ -255,6 +257,8 @@ internal static class CommandLine "cquery" => QueryKind.CQuery, _ => QueryKind.AQuery, }, string.Join(' ', positional), Flags(seen), Last(seen, "output") ?? "label"); + case "explain": + return Explain(output, positional, seen.Any(entry => entry.Option.Long == "long")); case "fetch": NoPositional(command, positional); return new FetchCommand(output); @@ -486,6 +490,28 @@ internal static class CommandLine return new PortalModulesCommand(output, positional[0] == "search" ? PortalAction.Search : PortalAction.Info, query, exact); } + private static ExplainCommand Explain(OutputOptions output, List<string> positional, bool @long) + { + if (positional.Count != 1) + { + throw new CommandLineException("tazel explain takes one error code, such as tazel explain E0406"); + } + + var code = positional[0].ToUpperInvariant(); + if (!ErrorCodes.IsCode(code)) + { + throw new CommandLineException($"'{positional[0]}' is not an error code: E and four digits, such as E0406"); + } + + if (ErrorCodes.Find(code) is null) + { + var near = Suggestions.Nearest(code, ErrorCodes.Codes.Select(entry => entry.Code).ToList()); + throw new CommandLineException($"Tazel has no error {code}{(near is null ? "" : $"; did you mean {near}?")}"); + } + + return new ExplainCommand(output, code, @long); + } + private static void NoPositional(string command, List<string> positional) { if (positional.Count > 0) diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 697daed..109d8ee 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -43,6 +43,9 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector 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: @@ -50,7 +53,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector case PortalModulesCommand portal: return await PortalModulesAsync(portal, cancel).ConfigureAwait(false); case DaemonCommand daemon: - reporter.Error($"tazel dotnet {daemon.Action}: this Tazel runs every command in a process of its own and has no 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, + "Tazel is a morning person: awake at once, every time, no daemon needed."); return 1; case CleanCommand clean: return Clean(clean); @@ -294,7 +298,8 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector default: if (!built) { - reporter.Error($"{executor.Failed} action{(executor.Failed == 1 ? "" : "s")} failed"); + reporter.Error(ErrorCodes.ActionsFailed, $"{executor.Failed} action{(executor.Failed == 1 ? "" : "s")} failed", "the FAILED lines above say what each one printed; --keep-going shows every failure at once", + Dsl.Custom.Jokes.ForProject($"{executor.Failed}")); return 1; } diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 17327bf..d823b7c 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -162,6 +162,24 @@ internal static class Help the name, and what follows is arguments, which <1>, <2>... and <*> take. Everything after custom belongs to the command, its options too. """), + ["explain"] = new("tazel explain <code> [--long]: what an error code means and how to fix it.", """ + tazel explain <code> [--long] + + Every error of Tazel has a code, E and four digits, as in error[E0406]. tazel explain prints what the code + means and a fixed example; --long says why, and shows the wrong text and the right one side by side. + The first two digits say where an error comes from: + 00 the text files (their comments, strings and placeholders) + 01 the command line + 02 tazel_options.txt + 03 tazel_custom.txt + 04 tazel_envs.txt + 05 MODULE.csx, BUILD.csx and builds + 06 labels + + Examples: + tazel explain E0406 + tazel explain E0406 --long + """), ["version"] = new("tazel version: prints the version of Tazel.", """ tazel version diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs index 3255860..f03c095 100644 --- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -127,6 +127,50 @@ internal sealed partial class Commands return new PackageId(null, path); } + /// <summary>What an error code means; with --long, why, and the wrong and right text side by side.</summary> + 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 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[/]"); + return; + } + + 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) + { + wrong.Border = BoxBorder.Ascii; + right.Border = BoxBorder.Ascii; + } + + console.Write(new Columns(wrong, right) { Expand = false }); + } + + var related = ErrorCodes.Codes.Where(other => other.Where == entry.Where && other.Code != entry.Code).Select(other => other.Code).ToList(); + if (related.Count > 0) + { + console.WriteLine(); + console.MarkupLine($"[grey]The other errors of {Markup.Escape(entry.Where)}: {string.Join(", ", related)}[/]"); + } + } + private async Task<int> FetchAsync() { RefuseWithoutSandbox(); diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs b/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs index 18c74cf..9950f9e 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs @@ -10,6 +10,7 @@ namespace Progmasoft.Tazel.Dsl.Custom; /// 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. /// </summary> +/// <param name="Code">The error code, E and four digits, that <c>tazel explain</c> explains.</param> /// <param name="File">The file, as it is shown.</param> /// <param name="Line">The line, from 1.</param> /// <param name="Column">The column, from 1.</param> @@ -20,23 +21,23 @@ namespace Progmasoft.Tazel.Dsl.Custom; /// <param name="Help">How to fix it, ideally with the fixed text.</param> /// <param name="Joke">A light line about it.</param> public sealed record Diagnostic( - string File, int Line, int Column, int Width, string SourceLine, string Message, string Label, string? Help, string? Joke) + string Code, string File, int Line, int Column, int Width, string SourceLine, string Message, string Label, string? Help, string? Joke) { /// <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> public static Diagnostic At( - string text, string file, int line, int column, int width, string message, string label, string? help = null, + string code, string text, string file, int line, int column, int width, string message, string label, string? help = null, string? joke = null) { ArgumentNullException.ThrowIfNull(text); - return new Diagnostic(file, line, column, Math.Max(1, width), LineOf(text, line), message, label, help, joke); + return new Diagnostic(code, file, line, column, Math.Max(1, width), LineOf(text, line), message, label, help, joke); } /// <summary>A problem at <paramref name="token"/>, marking all of it, quotes too.</summary> public static Diagnostic AtToken( - 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 = null, string? joke = null) { ArgumentNullException.ThrowIfNull(token); var width = token.Kind switch @@ -45,15 +46,15 @@ public sealed record Diagnostic( TokenKind.Placeholder => token.Text.Length + 2, _ => token.Text.Length, }; - return At(text, file, token.Line, token.Column, width, message, label, help, joke); + return At(code, text, file, 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 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 = null, string? joke = null) { ArgumentNullException.ThrowIfNull(token); - var marked = AtToken(text, file, token, message, label, help, joke); + var marked = AtToken(code, text, file, token, message, label, help, joke); // A string may span lines; then the mark goes to the end of the line it starts on. var column = Math.Min(token.Column + marked.Width, marked.SourceLine.Length + 1); return marked with { Column = column, Width = 1 }; diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs index 04fc3a3..6b1e9bd 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs @@ -93,7 +93,7 @@ public sealed class CustomLexer(string text, string file) ';' => TokenKind.Semicolon, '(' => TokenKind.Open, ')' => TokenKind.Close, - _ => throw Fail($"'{letter}' has no meaning here", _line, _column, 1, "this one", + _ => throw Fail(Output.ErrorCodes.CharacterHasNoMeaning, $"'{letter}' has no meaning here", _line, _column, 1, "this one", "this file knows names, strings in ' \" or `, ( ) : ; and <N>; put other text in quotes", $"Tazel squinted at '{letter}' for a long time. It squinted back."), }; @@ -110,8 +110,8 @@ public sealed class CustomLexer(string text, string file) private bool At(string what) => string.CompareOrdinal(text, _position, what, 0, what.Length) == 0; private CustomCommandsException Fail( - string message, int line, int column, int width, string label, string help, string joke) => - new(Diagnostic.At(text, file, line, column, width, message, label, help, joke)); + 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)); private char Advance() { @@ -146,7 +146,7 @@ public sealed class CustomLexer(string text, string file) Advance(); } - throw Fail("this comment has no closing #>", line, column, 2, "the comment opens here", "close it with #>", + throw Fail(Output.ErrorCodes.CommentNotClosed, "this comment has no closing #>", line, column, 2, "the comment opens here", "close it with #>", "This comment is still talking. Somebody has to say #>."); } @@ -163,7 +163,7 @@ public sealed class CustomLexer(string text, string file) if (_position == text.Length) { - throw Fail($"this string has no closing {quote}", line, column, 1, "the string starts here", + throw Fail(Output.ErrorCodes.StringNotClosed, $"this string has no closing {quote}", line, column, 1, "the string starts here", $"end it with another {quote}", "This string ran off with the rest of the file."); } @@ -184,7 +184,7 @@ public sealed class CustomLexer(string text, string file) if (_position == text.Length || text[_position] != '>') { - throw Fail("expected <N> or <*>", line, column, Math.Max(1, _position - begin + 1), "a placeholder starts here", + throw Fail(Output.ErrorCodes.PlaceholderNotClosed, "expected <N> or <*>", line, column, Math.Max(1, _position - begin + 1), "a placeholder starts here", "write <1> for the first argument, or <*> for all of them", "'<' walked in alone; its '>' never showed up."); } @@ -196,6 +196,7 @@ public sealed class CustomLexer(string text, string file) if (!valid) { throw Fail( + Output.ErrorCodes.PlaceholderOutOfRange, $"<{value}> is not an argument: <N> runs from 1 to {CustomCommandFiles.MaxArguments}, " + "and <*> is all of them", line, diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs index 394e306..abe49a2 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs @@ -36,7 +36,7 @@ public static class CustomParser if (words.Contains(CustomCommandFiles.NameEnd)) { var end = words.IndexOf(CustomCommandFiles.NameEnd); - throw Fail(tokens[_position - words.Count + end], + throw Fail(Output.ErrorCodes.CustomNameEnd, tokens[_position - words.Count + end], $"'{CustomCommandFiles.NameEnd}' ends a name on the command line, so a name cannot hold it", "this word", "pick another word for this part of the name", $"'{CustomCommandFiles.NameEnd}' is the bouncer at the end of a name; it cannot be a guest too."); @@ -44,7 +44,7 @@ public static class CustomParser if (words.Count > CustomCommandFiles.MaxArguments) { - throw Fail(name, $"a name holds at most {CustomCommandFiles.MaxArguments} words", "this name", + throw Fail(Output.ErrorCodes.CustomNameTooLong, name, $"a name holds at most {CustomCommandFiles.MaxArguments} words", "this name", $"shorten it to {CustomCommandFiles.MaxArguments} words or fewer", "That is not a name, that is a sentence."); } @@ -60,7 +60,7 @@ public static class CustomParser var joined = string.Join(' ', words); if (commands.ContainsKey(joined)) { - throw Fail(name, $"the command '{joined}' is defined twice", "the second one", + throw Fail(Output.ErrorCodes.CustomTwice, name, $"the command '{joined}' is defined twice", "the second one", "rename one of them, or put all their steps in one", "Two commands, one name: Tazel refuses to pick a favorite."); } @@ -68,6 +68,7 @@ public static class CustomParser if (words.Count + command.Required > CustomCommandFiles.MaxArguments) { throw Fail( + Output.ErrorCodes.CustomTooManyArguments, name, $"'{joined}' needs {command.Required} arguments, and its name leaves room for " + $"{CustomCommandFiles.MaxArguments - words.Count}", @@ -85,8 +86,8 @@ public static class CustomParser private Token? Peek() => _position < tokens.Count ? tokens[_position] : null; - private CustomCommandsException Fail(Token token, string message, string label, string? help, string? joke) => - new(Diagnostic.AtToken(text, file, token, message, label, help, joke)); + 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)); private Token Take(TokenKind kind, string wanted) { @@ -98,6 +99,14 @@ public static class CustomParser } var previous = _position > 0 ? tokens[_position - 1] : null; + var code = kind switch + { + TokenKind.Semicolon => Output.ErrorCodes.CustomNoSemicolon, + TokenKind.Colon => Output.ErrorCodes.CustomNoColon, + TokenKind.Open => Output.ErrorCodes.CustomNoOpen, + TokenKind.Close => Output.ErrorCodes.CustomNoClose, + _ => Output.ErrorCodes.CustomUnexpected, + }; var help = kind switch { TokenKind.Semicolon => "end every command with ';': build: (\"tazel\" \"build\" \"//...\");", @@ -109,17 +118,17 @@ public static class CustomParser // Missing at the end of the file, or a ';' or ':' that belongs right after the last thing: mark the gap. if (previous is not null && (token is null || kind is TokenKind.Semicolon or TokenKind.Colon)) { - throw new CustomCommandsException(Diagnostic.After(text, file, previous, $"expected {wanted}", + throw new CustomCommandsException(Diagnostic.After(code, text, file, previous, $"expected {wanted}", $"{Describe(kind)} goes here", help, Jokes.Missing(kind))); } if (token is null) { - throw new CustomCommandsException(Diagnostic.At(text, file, 1, 1, 1, $"expected {wanted}", + throw new CustomCommandsException(Diagnostic.At(code, text, file, 1, 1, 1, $"expected {wanted}", "the file is empty here", help, Jokes.Missing(kind))); } - throw Fail(token, $"expected {wanted}", $"{Describe(kind)} goes here, not this", help, Jokes.Missing(kind)); + throw Fail(code, token, $"expected {wanted}", $"{Describe(kind)} goes here, not this", help, Jokes.Missing(kind)); } private static string Describe(TokenKind kind) => kind switch @@ -164,14 +173,14 @@ public static class CustomParser var placeholder = values.FirstOrDefault(value => value.Kind == TokenKind.Placeholder); if (placeholder is not null) { - throw Fail(placeholder, "s(...) takes no arguments; (...) passes them", "this one", + throw Fail(Output.ErrorCodes.CustomShellArguments, placeholder, "s(...) takes no arguments; (...) passes them", "this one", "pass arguments with (\"program\" <1>), or write the whole line in s(...)", "The shell has its own ideas; Tazel does not hand it arguments too."); } if (values.Count != 1) { - throw Fail(open, "s(...) takes one string, the whole command line", "this s(...)", + throw Fail(Output.ErrorCodes.CustomShellOneLine, open, "s(...) takes one string, the whole command line", "this s(...)", "write one line: s(\"npm run dev\")", "One shell, one line. It is not a group chat."); } @@ -180,13 +189,13 @@ public static class CustomParser if (values.Count == 0) { - throw Fail(open, "a command names at least a program", "these parentheses are empty", + throw Fail(Output.ErrorCodes.CustomEmpty, open, "a command names at least a program", "these parentheses are empty", "name the program first: (\"npm\" \"run\" \"dev\")", "Empty parentheses: a command with nothing to say."); } if (values[0].Kind != TokenKind.String) { - throw Fail(values[0], "a command starts with the name of its program", "this is not a program", + throw Fail(Output.ErrorCodes.CustomNoProgram, values[0], "a command starts with the name of its program", "this is not a program", "put the program first: (\"echo\" <1>)", "Tazel does not run surprises; it wants to know the program."); } diff --git a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs index 83cfaa8..ca42d26 100644 --- a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs +++ b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs @@ -58,7 +58,7 @@ public static class TazelEnvsFile var name = Take(TokenKind.Name, "the name of a value"); if (names.TryGetValue(name.Text, out var first)) { - throw Fail(name, $"'{name.Text}' is set twice", "the second one", + 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."); } @@ -79,7 +79,7 @@ public static class TazelEnvsFile Take(TokenKind.Close, "')' after the line of s(...)"); value = strings.Count == 1 ? new EnvValue.Shell(strings[0]) - : throw Fail(open, "s(...) takes one string, the whole line", "this s(...)", + : 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."); } else if (Peek() is { Kind: TokenKind.Open }) @@ -89,20 +89,20 @@ public static class TazelEnvsFile Take(TokenKind.Close, "')' after the strings of a program"); value = strings.Count > 0 ? new EnvValue.Program(strings) - : throw Fail(open, "a program names at least itself", "these parentheses are empty", + : 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."); } else if (Peek() is { } stranger) { - throw Fail(stranger, $"expected the value of {name.Text}", "this is not a value", + 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(text, file, tokens[i - 1], $"expected the value of {name.Text}", + 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.")); } @@ -122,6 +122,14 @@ public static class TazelEnvsFile return token; } + 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';", @@ -132,7 +140,7 @@ public static class TazelEnvsFile }; if (i > 0 && (Peek() is null || kind is TokenKind.Semicolon or TokenKind.Colon)) { - throw new CustomCommandsException(Diagnostic.After(text, file, tokens[i - 1], $"expected {wanted}", + throw new CustomCommandsException(Diagnostic.After(code, text, file, tokens[i - 1], $"expected {wanted}", kind switch { TokenKind.Semicolon => "a ';' goes here", @@ -143,7 +151,7 @@ public static class TazelEnvsFile help, Jokes.Missing(kind))); } - throw Fail(Peek()!, $"expected {wanted}", "not this", help, Jokes.Missing(kind)); + throw Fail(code, Peek()!, $"expected {wanted}", "not this", help, Jokes.Missing(kind)); } List<string> Strings() @@ -157,15 +165,15 @@ public static class TazelEnvsFile if (Peek() is { Kind: TokenKind.Placeholder } placeholder) { - throw Fail(placeholder, "a value of tazel_envs.txt takes no <N> or <*>", "this 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."); } return strings; } - CustomCommandsException Fail(Token token, string message, string label, string help, string joke) => - new(Diagnostic.AtToken(text, file, token, message, label, help, joke)); + 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/Dsl/Options/TazelOptions.cs b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs index 8ca7fc0..a5630ba 100644 --- a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs +++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs @@ -193,21 +193,21 @@ public static class TazelOptionsFile if (!Keys.Contains(key.Text, StringComparer.Ordinal)) { var near = Cli.Suggestions.Nearest(key.Text, Keys); - throw Fail(key, $"'{key.Text}' is not an option", "this one", + throw Fail(Output.ErrorCodes.OptionsUnknown, key, $"'{key.Text}' is not an option", "this one", near is null ? $"the options are {string.Join(", ", Keys)}" : $"did you mean {near}?", $"Tazel read its own manual twice; '{key.Text}' is not in it."); } if (!seen.Add(key.Text)) { - throw Fail(key, $"'{key.Text}' is set twice", "the second one", "keep one of them", + throw Fail(Output.ErrorCodes.OptionsTwice, key, $"'{key.Text}' is set twice", "the second one", "keep one of them", "Saying it twice does not make it twice as true."); } Take(TokenKind.Colon, $"':' after {key.Text}"); if (_position >= tokens.Count || tokens[_position].Kind is not (TokenKind.Name or TokenKind.String)) { - throw new TazelOptionsException(Diagnostic.After(text, file, tokens[_position - 1], + throw new TazelOptionsException(Diagnostic.After(Output.ErrorCodes.OptionsNoValue, text, file, tokens[_position - 1], $"expected a value for {key.Text}", "the value goes here", $"for example {key.Text}: {Example(key.Text)};", "A name, a colon, and then... silence.")); } @@ -232,8 +232,8 @@ public static class TazelOptionsFile return options; } - private TazelOptionsException Fail(Token token, string message, string label, string help, string joke) => - new(Diagnostic.AtToken(text, file, token, message, label, help, joke)); + private TazelOptionsException Fail(string code, Token token, string message, string label, string help, string joke) => + new(Diagnostic.AtToken(code, text, file, token, message, label, help, joke)); private static string Example(string key) => key switch { @@ -250,6 +250,12 @@ public static class TazelOptionsFile return tokens[_position++]; } + var code = kind switch + { + TokenKind.Semicolon => Output.ErrorCodes.OptionsNoSemicolon, + TokenKind.Colon => Output.ErrorCodes.OptionsNoColon, + _ => Output.ErrorCodes.OptionsUnexpected, + }; var help = kind switch { TokenKind.Semicolon => "end the value with ';': platform: linux-amd64;", @@ -258,17 +264,17 @@ public static class TazelOptionsFile }; if (_position > 0 && (_position >= tokens.Count || kind is TokenKind.Semicolon or TokenKind.Colon)) { - throw new TazelOptionsException(Diagnostic.After(text, file, tokens[_position - 1], $"expected {wanted}", + throw new TazelOptionsException(Diagnostic.After(code, text, file, tokens[_position - 1], $"expected {wanted}", kind == TokenKind.Semicolon ? "a ';' goes here" : kind == TokenKind.Colon ? "a ':' goes here" : "something goes here", help, Jokes.Missing(kind))); } - throw Fail(tokens[_position], $"expected {wanted}", "not this", help, Jokes.Missing(kind)); + throw Fail(code, tokens[_position], $"expected {wanted}", "not this", help, Jokes.Missing(kind)); } private bool Boolean(Token value) => value is { Kind: TokenKind.Name, Text: "true" } ? true : value is { Kind: TokenKind.Name, Text: "false" } ? false - : throw Fail(value, "expected true or false", "this one", "write true or false, bare: sandboxing-with-microvm: true;", + : throw Fail(Output.ErrorCodes.OptionsNotBoolean, value, "expected true or false", "this one", "write true or false, bare: sandboxing-with-microvm: true;", "It is a yes-or-no question. Tazel accepts no 'maybe'."); // "auto" is a string, in any of the three quotes; a number stands bare. @@ -276,20 +282,20 @@ public static class TazelOptionsFile { if (value.Kind == TokenKind.String) { - return value.Text == "auto" ? Allocation.Auto : throw Fail(value, "the only string here is \"auto\"", "this string", + return value.Text == "auto" ? Allocation.Auto : throw Fail(Output.ErrorCodes.OptionsStringNotAuto, value, "the only string here is \"auto\"", "this string", $"write a number of {unit}, bare, or \"auto\"", "Tazel speaks only one word in quotes here, and it is \"auto\"."); } if (value.Text.Length == 0 || value.Text[0] == '0' || value.Text.Length > 9 || !value.Text.All(char.IsAsciiDigit)) { - throw Fail(value, $"expected a number of {unit} or \"auto\"", "this one", $"for example {min * 2} or \"auto\"", + throw Fail(Output.ErrorCodes.OptionsNotANumber, value, $"expected a number of {unit} or \"auto\"", "this one", $"for example {min * 2} or \"auto\"", "Digits only, and no zero up front: this is a number, not a phone number."); } var amount = int.Parse(value.Text, CultureInfo.InvariantCulture); return amount < min || amount > max - ? throw Fail(value, $"{amount} is outside {min} to {max} {unit}", "this number", + ? throw Fail(Output.ErrorCodes.OptionsOutOfRange, value, $"{amount} is outside {min} to {max} {unit}", "this number", $"pick a number from {min} to {max}", amount > max ? "Ambitious! A little too ambitious." : "Tazel needs a bit more than that to work with.") : new Allocation(amount); } @@ -297,7 +303,7 @@ public static class TazelOptionsFile private Platform PlatformOf(Token value) => value.Kind == TokenKind.Name && Platforms.TryParse(value.Text, out var platform) ? platform - : throw Fail(value, $"'{value.Text}' is not a platform", "this one", + : throw Fail(Output.ErrorCodes.OptionsNotAPlatform, value, $"'{value.Text}' is not a platform", "this one", Cli.Suggestions.Nearest(value.Text, Platforms.Names) is { } near ? $"did you mean {near}?" : $"the platforms are {string.Join(", ", Platforms.Names)}", diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs new file mode 100644 index 0000000..dd412bd --- /dev/null +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -0,0 +1,260 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +namespace Progmasoft.Tazel.Output; + +/// <summary>What one error code means, for <c>tazel explain</c>.</summary> +/// <param name="Code">The code, <c>E</c> and four digits.</param> +/// <param name="Title">What went wrong, in a few words.</param> +/// <param name="Explanation">Why it is a problem and how to fix it.</param> +/// <param name="Wrong">Text that has the problem, or null.</param> +/// <param name="Right">The same text fixed, or null.</param> +/// <param name="Where">The file or part of Tazel the code belongs to.</param> +internal sealed record ErrorCode(string Code, string Title, string Explanation, string? Wrong, string? Right, string Where); + +/// <summary> +/// Every error code of Tazel. The first two digits say where the error comes from: 00 the lexer of the text files, +/// 01 the command line, 02 <c>tazel_options.txt</c>, 03 <c>tazel_custom.txt</c>, 04 <c>tazel_envs.txt</c>, 05 project +/// files and builds, 06 labels. A code, once given, keeps its meaning. +/// </summary> +internal static partial class ErrorCodes +{ + public const string CharacterHasNoMeaning = "E0001"; + public const string CommentNotClosed = "E0002"; + public const string StringNotClosed = "E0003"; + public const string PlaceholderNotClosed = "E0004"; + public const string PlaceholderOutOfRange = "E0005"; + + public const string CommandLine = "E0100"; + + public const string OptionsUnknown = "E0201"; + public const string OptionsTwice = "E0202"; + public const string OptionsNoValue = "E0203"; + public const string OptionsNoSemicolon = "E0204"; + public const string OptionsNoColon = "E0205"; + public const string OptionsUnexpected = "E0206"; + public const string OptionsNotBoolean = "E0207"; + public const string OptionsStringNotAuto = "E0208"; + public const string OptionsNotANumber = "E0209"; + public const string OptionsOutOfRange = "E0210"; + public const string OptionsNotAPlatform = "E0211"; + public const string OptionsUnreadable = "E0212"; + + public const string CustomNameEnd = "E0301"; + public const string CustomNameTooLong = "E0302"; + public const string CustomTwice = "E0303"; + public const string CustomTooManyArguments = "E0304"; + public const string CustomNoSemicolon = "E0305"; + public const string CustomNoColon = "E0306"; + public const string CustomNoOpen = "E0307"; + public const string CustomNoClose = "E0308"; + public const string CustomUnexpected = "E0309"; + public const string CustomShellArguments = "E0310"; + public const string CustomShellOneLine = "E0311"; + public const string CustomEmpty = "E0312"; + public const string CustomNoProgram = "E0313"; + + public const string EnvsTwice = "E0401"; + public const string EnvsShellOneLine = "E0402"; + public const string EnvsEmptyProgram = "E0403"; + public const string EnvsNotAValue = "E0404"; + public const string EnvsNoValue = "E0405"; + public const string EnvsNoSemicolon = "E0406"; + public const string EnvsNoColon = "E0407"; + public const string EnvsNoClose = "E0408"; + public const string EnvsNoOpen = "E0409"; + public const string EnvsUnexpected = "E0410"; + public const string EnvsPlaceholder = "E0411"; + + public const string Project = "E0500"; + public const string ActionsFailed = "E0501"; + public const string NoDaemon = "E0502"; + public const string Stopped = "E0503"; + public const string Label = "E0600"; + + private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt"; + private const string Options = "tazel_options.txt"; + private const string Custom = "tazel_custom.txt"; + private const string Envs = "tazel_envs.txt"; + + private static readonly ErrorCode[] All = + [ + new(CharacterHasNoMeaning, "a character that starts nothing", + "The text files know names (letters, digits, - _ .), strings in ' \" or `, the punctuation ( ) : ; and the " + + "placeholders <1> to <9> and <*>, besides comments. Any other character outside a string is an error. Put text " + + "with other characters in quotes.", + "message: hello @ world;", "message: 'hello @ world';", Lexer), + new(CommentNotClosed, "a <# comment #> without its #>", + "A comment that starts with <# goes on until #>, over as many lines as it likes. When the file ends first, the " + + "comment swallowed everything after it. Close it with #>, or use # for a comment to the end of the line.", + "<# the options of this machine\nplatform: linux-amd64;", "<# the options of this machine #>\nplatform: linux-amd64;", Lexer), + new(StringNotClosed, "a string without its closing quote", + "A string ends at the next quote of its own kind: ' ends at ', \" at \" and ` at `. There are no escapes, so a " + + "string that needs one kind of quote inside is written with another kind around it.", + "example-version: '0.1.0;", "example-version: '0.1.0';", Lexer), + new(PlaceholderNotClosed, "a < that is not a placeholder", + "Outside strings, < starts a placeholder of tazel_custom.txt: <1> for the first argument, up to <9>, or <*> for all " + + "of them. A < with no > after it, or with spaces inside, is none of them.", + "say: (\"echo\" <1);", "say: (\"echo\" <1>);", Lexer), + new(PlaceholderOutOfRange, "a placeholder with no argument behind it", + "A placeholder counts from 1, like a person: <1> to <9>, with no zero in front. <*> stands for every argument.", + "say: (\"echo\" <0>);", "say: (\"echo\" <1>);", Lexer), + + new(CommandLine, "a command line Tazel cannot take", + "The command, an option or a value is not one Tazel knows, or a command got arguments it does not take. Tazel " + + "suggests the nearest spelling when there is one. tazel help lists the commands, and tazel help <command> --long " + + "says what each takes.", + "tazel biuld //...", "tazel build //...", "the command line"), + + new(OptionsUnknown, "an option tazel_options.txt does not have", + "tazel_options.txt sets platform, sandboxing-with-microvm, microvm-network, microvm-memory and microvm-cpus. Any " + + "other name is a misspelling or an option of another tool.", + "plaform: linux-amd64;", "platform: linux-amd64;", Options), + new(OptionsTwice, "an option set twice", + "Each option is set once in a file, so that nobody has to guess which one wins. Keep one of them.", + "platform: linux-amd64;\nplatform: linux-aarch64;", "platform: linux-aarch64;", Options), + new(OptionsNoValue, "an option without its value", + "An option is a name, ':', a value and ';'. The value is missing.", + "microvm-cpus: ;", "microvm-cpus: 2;", Options), + new(OptionsNoSemicolon, "an option without its ';'", + "Every option ends with ';'; only the last one of the file may leave it out.", + "platform: linux-amd64\nmicrovm-cpus: 2;", "platform: linux-amd64;\nmicrovm-cpus: 2;", Options), + new(OptionsNoColon, "an option without its ':'", + "The name of an option and its value are joined by ':'.", + "platform linux-amd64;", "platform: linux-amd64;", Options), + new(OptionsUnexpected, "something tazel_options.txt does not expect here", + "The file is a list of name: value; and nothing else.", + "platform: (linux-amd64);", "platform: linux-amd64;", Options), + new(OptionsNotBoolean, "a yes-or-no option without true or false", + "sandboxing-with-microvm and microvm-network take true or false, bare, without quotes.", + "microvm-network: yes;", "microvm-network: true;", Options), + new(OptionsStringNotAuto, "a string where only \"auto\" is a string", + "microvm-memory and microvm-cpus take a number, bare, or the string \"auto\", which lets Tazel decide.", + "microvm-memory: \"2048\";", "microvm-memory: 2048;", Options), + new(OptionsNotANumber, "something that is not a number", + "A number is digits only, without a zero in front and without a unit: microvm-memory counts MiB, microvm-cpus " + + "counts processors.", + "microvm-memory: 2GiB;", "microvm-memory: 2048;", Options), + new(OptionsOutOfRange, "a number outside what the option takes", + "microvm-memory takes 256 MiB to what this machine has, microvm-cpus one processor to what this machine has.", + "microvm-cpus: 4096;", "microvm-cpus: 4;", Options), + new(OptionsNotAPlatform, "a platform Tazel does not know", + "platform names one of the platforms of --platform: linux-amd64, linux-aarch64, macos-x86_64, macos-aarch64, " + + "windows-amd64, windows-aarch64 and the others tazel help build --long lists.", + "platform: linux-amd46;", "platform: linux-amd64;", Options), + new(OptionsUnreadable, "a tazel_options.txt that cannot be read", + "Tazel found a tazel_options.txt but could not read it, or could not tell whether it is there. Tazel stops " + + "rather than skip it, as the file may turn the sandbox on. Check its permissions.", null, null, Options), + + new(CustomNameEnd, "'--' inside the name of a command", + "On the command line, '--' ends the name of a custom command and starts its arguments, so a name cannot hold it.", + "run -- all: (\"make\");", "run all: (\"make\");", Custom), + new(CustomNameTooLong, "a name of more than nine words", + "A name holds at most nine words, the most arguments tazel custom can tell apart.", null, null, Custom), + new(CustomTwice, "a command defined twice", + "Each name is defined once; rename one, or put the steps of both in one command.", + "build: (\"make\");\nbuild: (\"ninja\");", "build: (\"make\") (\"ninja\");", Custom), + new(CustomTooManyArguments, "a command whose arguments do not fit", + "The words of a name and the arguments it needs share nine places on the command line.", null, null, Custom), + new(CustomNoSemicolon, "a command without its ';'", + "Every command ends with ';', the last one too.", + "build: (\"tazel\" \"build\" \"//...\")", "build: (\"tazel\" \"build\" \"//...\");", Custom), + new(CustomNoColon, "a command without its ':'", + "The name of a command and its steps are joined by ':'.", + "build (\"tazel\" \"build\");", "build: (\"tazel\" \"build\");", Custom), + new(CustomNoOpen, "a step without its '('", + "A step is (\"program\" \"argument\"...) or s(\"a shell line\").", + "build: \"tazel\" \"build\";", "build: (\"tazel\" \"build\");", Custom), + new(CustomNoClose, "a step without its ')'", + "A step closes with ')' after its strings and placeholders.", + "build: (\"tazel\" \"build\";", "build: (\"tazel\" \"build\");", Custom), + new(CustomUnexpected, "something tazel_custom.txt does not expect here", + "The file is a list of name: steps; where a step is (\"program\" ...) or s(\"line\").", + "build: tazel build;", "build: (\"tazel\" \"build\");", Custom), + new(CustomShellArguments, "a placeholder inside s(...)", + "s(...) hands one line to the shell as written; it takes no arguments. Use (\"program\" <1>) to pass them.", + "say: s(\"echo\" <1>);", "say: (\"echo\" <1>);", Custom), + new(CustomShellOneLine, "s(...) with more or less than one string", + "s(...) takes the whole shell line as one string.", + "dev: s(\"npm\" \"run\" \"dev\");", "dev: s(\"npm run dev\");", Custom), + new(CustomEmpty, "a step with nothing in it", + "A step names at least the program it runs.", + "dev: ();", "dev: (\"npm\" \"run\" \"dev\");", Custom), + new(CustomNoProgram, "a step that starts with a placeholder", + "A step starts with the name of its program, a string; the arguments may follow.", + "run: (<1>);", "run: (\"tazel\" \"run\" <1>);", Custom), + + new(EnvsTwice, "a value set twice", + "Each name of tazel_envs.txt is set once; GetEnvironment.From could not know which one you meant.", + "example-version: '0.1.0';\nexample-version: '0.2.0';", "example-version: '0.2.0';", Envs), + new(EnvsShellOneLine, "s(...) with more or less than one string", + "s(...) takes the whole shell line as one string; /bin/sh or cmd.exe reads it.", + "home: s(`echo` `$HOME`);", "home: s(`echo $HOME`);", Envs), + new(EnvsEmptyProgram, "a program with no name", + "(\"program\" \"argument\"...) starts a program directly and needs at least its name.", + "example-output: ();", "example-output: (\"rustc\" \"--version\");", Envs), + new(EnvsNotAValue, "something that is not a value", + "A value is a string, a program (\"program\" \"argument\") or a shell line s(\"line\"). A bare word is a name, " + + "not a value; put it in quotes.", + "example-version: 0.1.0;", "example-version: '0.1.0';", Envs), + new(EnvsNoValue, "a name without its value", + "Every entry is name: value; and the value is missing.", + "example-version:", "example-version: '0.1.0';", Envs), + new(EnvsNoSemicolon, "a value without its ';'", + "Every value of tazel_envs.txt ends with ';', the last one too.", + "example-version: '0.1.0'", "example-version: '0.1.0';", Envs), + new(EnvsNoColon, "a name without its ':'", + "A name and its value are joined by ':'.", + "example-version '0.1.0';", "example-version: '0.1.0';", Envs), + new(EnvsNoClose, "a program or shell line without its ')'", + "(\"program\" ...) and s(\"line\") close with ')'.", + "example-output: (\"rustc\" \"--version\";", "example-output: (\"rustc\" \"--version\");", Envs), + new(EnvsNoOpen, "s without its '('", + "A shell line is s(\"line\"): s and '(' with nothing between.", + "home: s `echo $HOME`;", "home: s(`echo $HOME`);", Envs), + new(EnvsUnexpected, "something tazel_envs.txt does not expect here", + "The file is a list of name: value; and nothing else.", null, null, Envs), + new(EnvsPlaceholder, "a placeholder in tazel_envs.txt", + "<1> and <*> stand for the arguments of a custom command; nothing passes arguments to tazel_envs.txt. Write the " + + "argument itself.", + "example-output: (\"rustc\" <1>);", "example-output: (\"rustc\" \"--version\");", Envs), + + new(Project, "a problem in the project files or the build", + "A MODULE.csx or BUILD.csx did not compile or run, declared something Tazel refuses, or the build met " + + "something it cannot go on with, such as a dependency that is not there. The message says which file and what; " + + "a C# error of a project file names its line and column.", null, null, "MODULE.csx, BUILD.csx and builds"), + new(ActionsFailed, "actions of the build failed", + "A compiler, a linker, a test or a step ended with an error. Its command and its output are printed above, " + + "marked FAILED; the problem is in what it says. With --keep-going, Tazel goes on with what does not depend on " + + "the failed actions, so one build shows every failure.", null, null, "MODULE.csx, BUILD.csx and builds"), + new(NoDaemon, "no daemon to start or stop", + "This Tazel runs every command in a process of its own, so tazel dotnet start-daemon, restart-daemon and " + + "stop-daemon have nothing to do.", null, null, "MODULE.csx, BUILD.csx and builds"), + new(Stopped, "the command was stopped", + "Ctrl+C or a signal stopped Tazel. The actions that were running were stopped too; what finished is kept, and " + + "the next build goes on from there.", null, null, "MODULE.csx, BUILD.csx and builds"), + new(Label, "a label Tazel cannot read", + "A label names a target: //dir:name, //:name, :name in the current package, @dependency//dir:name; //dir/... " + + "and //... are patterns of packages. Names hold letters, digits and _ + . -.", + "tazel build //app/greeter", "tazel build //app:greeter", "labels"), + ]; + + private static readonly Dictionary<string, ErrorCode> ByCode = All.ToDictionary(code => code.Code, StringComparer.Ordinal); + + /// <summary>Every code, in order.</summary> + public static IReadOnlyList<ErrorCode> Codes => All; + + /// <summary>Whether <paramref name="text"/> is written as a code: E and four digits.</summary> + public static bool IsCode(string text) => CodePattern().IsMatch(text); + + /// <summary>What <paramref name="code"/> means, or null when Tazel has no such code.</summary> + public static ErrorCode? Find(string code) => ByCode.GetValueOrDefault(code); + + [GeneratedRegex("^E[0-9]{4}$")] + private static partial Regex CodePattern(); +} diff --git a/src/Progmasoft.Tazel/Output/Reporter.cs b/src/Progmasoft.Tazel/Output/Reporter.cs index f746e33..ffc5148 100644 --- a/src/Progmasoft.Tazel/Output/Reporter.cs +++ b/src/Progmasoft.Tazel/Output/Reporter.cs @@ -127,17 +127,19 @@ internal sealed class Reporter } /// <summary>What went wrong, ending the command, with how to fix it and a light line when there are ones.</summary> - public void Error(string message, string? help = null, string? joke = null) + public void Error(string code, string message, string? help = null, string? joke = null) { lock (_lock) { var fancy = Console.Profile.Capabilities.Unicode; - Console.MarkupLine($"[red bold]{(fancy ? "✖ " : "")}error[/]: [bold]{Markup.Escape(message)}[/]"); + Console.MarkupLine($"[red bold]{(fancy ? "✖ " : "")}{Heading(code)}[/] [bold]{Markup.Escape(message)}[/]"); if (help is not null) { Console.MarkupLine($" [blue]{(fancy ? "├─" : "|-")}[/] [green]{(fancy ? "💡 " : "")}help:[/] {Markup.Escape(help)}"); } + Console.MarkupLine($" [blue]{(fancy ? "├─" : "|-")}[/] [cyan]{(fancy ? "📖 " : "")}more:[/] tazel explain {code}"); + if (joke is not null) { Console.MarkupLine($" [blue]{(fancy ? "╰─" : "`-")}[/] [magenta italic]{(fancy ? "🎭 " : "")}{Markup.Escape(joke)}[/]"); @@ -162,7 +164,7 @@ internal sealed class Reporter var width = Math.Max(1, diagnostic.Width); string Gutter(string left) => $"[blue]{left} {bar}[/]"; - Console.MarkupLine($"[red bold]{(fancy ? "✖ " : "")}error[/]: [bold]{Markup.Escape(diagnostic.Message)}[/]"); + 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(Gutter(pad)); if (diagnostic.SourceLine.Length > 0 || diagnostic.Column == 1) @@ -182,6 +184,7 @@ internal sealed class Reporter Console.MarkupLine($"[blue]{pad} {(fancy ? "├─" : "|-")}[/] [green]{(fancy ? "💡 " : "")}help:[/] {Markup.Escape(diagnostic.Help)}"); } + Console.MarkupLine($"[blue]{pad} {(fancy ? "├─" : "|-")}[/] [cyan]{(fancy ? "📖 " : "")}more:[/] tazel explain {diagnostic.Code}"); if (diagnostic.Joke is not null) { Console.MarkupLine($"[blue]{pad} {(fancy ? "╰─" : "`-")}[/] [magenta italic]{(fancy ? "🎭 " : "")}{Markup.Escape(diagnostic.Joke)}[/]"); @@ -189,6 +192,9 @@ internal sealed class Reporter } } + // error[E0406]: the code in brackets, as rustc writes it; markup needs its brackets doubled. + private static string Heading(string code) => $"error[[{Markup.Escape(code)}]]:"; + // A file below the current directory is shown from there, which is shorter and what the user typed. private static string Shown(string file) { diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 150ee28..2d44bfe 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -42,8 +42,8 @@ internal static class Program } catch (CommandLineException error) { - new Reporter(Reporter.CreateConsole(When.Auto, output), quiet: false, When.Never).Error(error.Message, - HelpFor(arguments), Jokes.ForCommandLine(error.Message)); + new Reporter(Reporter.CreateConsole(When.Auto, output), quiet: false, When.Never).Error(ErrorCodes.CommandLine, + error.Message, HelpFor(arguments), Jokes.ForCommandLine(error.Message)); return UsageError; } @@ -54,7 +54,7 @@ internal static class Program } catch (CommandLineException error) { - reporter.Error(error.Message, HelpFor(arguments), Jokes.ForCommandLine(error.Message)); + reporter.Error(ErrorCodes.CommandLine, error.Message, HelpFor(arguments), Jokes.ForCommandLine(error.Message)); return UsageError; } catch (Exception error) when (Placed(error) is { } diagnostic) @@ -65,12 +65,18 @@ internal static class Program catch (Exception error) when (error is ProjectException or LabelException or TazelOptionsException or CustomCommandsException) { - reporter.Error(error.Message, null, Jokes.ForProject(error.Message)); + var code = error switch + { + LabelException => ErrorCodes.Label, + TazelOptionsException => ErrorCodes.OptionsUnreadable, + _ => ErrorCodes.Project, + }; + reporter.Error(code, error.Message, null, Jokes.ForProject(error.Message)); return 1; } catch (OperationCanceledException) { - reporter.Error("stopped"); + reporter.Error(ErrorCodes.Stopped, "stopped", null, "Tazel put its tools down mid-sentence."); return 130; } } diff --git a/tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs b/tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs index 5084dcd..0dc3ccf 100644 --- a/tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs +++ b/tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs @@ -2,11 +2,13 @@ // SPDX-License-Identifier: MIT using System; +using System.Linq; using System.Threading.Tasks; using Progmasoft.Tazel.Dsl.Custom; using Progmasoft.Tazel.Dsl.Custom.Parser; using Progmasoft.Tazel.Dsl.Envs; using Progmasoft.Tazel.Dsl.Options; +using Progmasoft.Tazel.Output; using Xunit; namespace Progmasoft.Tazel.Tests; @@ -47,6 +49,7 @@ public sealed class DiagnosticTests Assert.False(string.IsNullOrWhiteSpace(diagnostic.Help)); Assert.False(string.IsNullOrWhiteSpace(diagnostic.Joke)); Assert.InRange(diagnostic.Column, 1, diagnostic.SourceLine.Length + 1); + Assert.NotNull(ErrorCodes.Find(diagnostic.Code)); Assert.Equal(text.Split('\n')[diagnostic.Line - 1], diagnostic.SourceLine); } @@ -74,7 +77,8 @@ public sealed class DiagnosticTests .Write("tazel_envs.txt", "example-version: '0.1.0'\n"); var (status, output) = await module.TazelAsync(".", "build", "//...", "--quiet"); Assert.Equal(1, status); - Assert.Contains("error: expected ';' after the value of example-version", output, StringComparison.Ordinal); + Assert.Contains("error[E0406]: expected ';' after the value of example-version", output, StringComparison.Ordinal); + Assert.Contains("more: tazel explain E0406", output, StringComparison.Ordinal); Assert.Contains("tazel_envs.txt:1:25", output, StringComparison.Ordinal); Assert.Contains("1 | example-version: '0.1.0'", output.Replace('│', '|'), StringComparison.Ordinal); Assert.Contains("a ';' goes here", output, StringComparison.Ordinal); @@ -92,10 +96,67 @@ public sealed class DiagnosticTests Assert.Equal(2, status); Assert.Contains("help: tazel help build --long says what build takes", output, StringComparison.Ordinal); var message = output.Split('\n')[0]; - Assert.Contains(Jokes.ForCommandLine(message[(message.IndexOf("error: ", StringComparison.Ordinal) + 7)..].Trim()), + Assert.Contains("error[E0100]: ", message, StringComparison.Ordinal); + Assert.Contains(Jokes.ForCommandLine(message[(message.IndexOf("]: ", StringComparison.Ordinal) + 3)..].Trim()), output, StringComparison.Ordinal); } + [Theory] + [InlineData("envs", "x: '1'", "E0406")] + [InlineData("envs", "x '1';", "E0407")] + [InlineData("envs", "x: version;", "E0404")] + [InlineData("envs", "x: \"open", "E0003")] + [InlineData("custom", "build: (\"tazel\")", "E0305")] + [InlineData("custom", "build: s(\"a\" \"b\");", "E0311")] + [InlineData("options", "platform: linux-amd46;", "E0211")] + [InlineData("options", "microvm-cpus: 99999;", "E0210")] + public void EachProblemHasItsOwnCode(string reader, string text, string code) => + Assert.Equal(code, DiagnosticOf(reader, text)!.Code); + + [Fact] + public void EveryCodeIsWrittenOnceAndExplained() + { + var constants = typeof(ErrorCodes).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) + .Where(field => field.IsLiteral).Select(field => (string)field.GetRawConstantValue()!).ToList(); + Assert.Equal(constants.Count, constants.Distinct(StringComparer.Ordinal).Count()); + Assert.Equal(constants.Order(StringComparer.Ordinal), ErrorCodes.Codes.Select(code => code.Code).Order(StringComparer.Ordinal)); + foreach (var code in ErrorCodes.Codes) + { + Assert.True(ErrorCodes.IsCode(code.Code), code.Code); + Assert.False(string.IsNullOrWhiteSpace(code.Title), code.Code); + Assert.EndsWith(".", code.Explanation, StringComparison.Ordinal); + Assert.Equal(code.Wrong is null, code.Right is null); + } + } + + [Fact] + public async Task ExplainSaysWhatACodeMeansShortAndLong() + { + using var module = new TemporaryModule(); + var (status, output) = await module.TazelAsync(".", "explain", "E0406"); + Assert.Equal(0, status); + Assert.Contains("E0406: a value without its ';'", output, StringComparison.Ordinal); + Assert.Contains("example-version: '0.1.0';", output, StringComparison.Ordinal); + Assert.Contains("tazel explain E0406 --long", output, StringComparison.Ordinal); + + (status, output) = await module.TazelAsync(".", "explain", "e0406", "--long"); + Assert.Equal(0, status); + Assert.Contains("wrong", output, StringComparison.Ordinal); + Assert.Contains("right", output, StringComparison.Ordinal); + Assert.Contains("The other errors of tazel_envs.txt", output, StringComparison.Ordinal); + } + + [Theory] + [InlineData(new[] { "explain" }, "takes one error code")] + [InlineData(new[] { "explain", "406" }, "'406' is not an error code")] + [InlineData(new[] { "explain", "E9999" }, "Tazel has no error E9999")] + [InlineData(new[] { "explain", "E0407", "E0406" }, "takes one error code")] + public void ExplainRefusesWhatIsNotACode(string[] arguments, string message) + { + var error = Assert.Throws<Progmasoft.Tazel.Cli.CommandLineException>(() => Progmasoft.Tazel.Cli.CommandLine.Parse(arguments)); + Assert.Contains(message, error.Message, StringComparison.Ordinal); + } + private static Diagnostic? DiagnosticOf(string reader, string text) { try