tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Show errors with their line, a mark, help and a joke
- Commit
fb5357e53084b613e803294492f8f4fa2e533e48- Author
- Leitwolf11 ·
- Parents
eec8fe2ec540
Changes
docs/commands.md | 20 ++++ src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs | 10 ++ src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs | 79 +++++++++++++ src/Progmasoft.Tazel/Dsl/Custom/Jokes.cs | 60 ++++++++++ .../Dsl/Custom/Lexer/CustomLexer.cs | 25 ++-- .../Dsl/Custom/Parser/CustomParser.cs | 78 ++++++++++--- src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs | 62 ++++++++-- src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs | 77 ++++++++++--- src/Progmasoft.Tazel/Output/Reporter.cs | 72 +++++++++++- src/Progmasoft.Tazel/Program.cs | 37 +++++- tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs | 128 +++++++++++++++++++++ 11 files changed, 591 insertions(+), 57 deletions(-) diff --git a/docs/commands.md b/docs/commands.md index f0a50ab..d3426d5 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -174,3 +174,23 @@ var exampleVersion = GetEnvironment.From("example-version"); // "0.1.0"; null fo - A value is not an environment variable: it reaches no shell, no program Tazel runs and not Tazel itself; only `GetEnvironment.From` reads it. +## 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: + +```text +✖ error: expected ';' after the value of example-version + ╭─[ tazel_envs.txt:1:25 ] + │ +1 │ example-version: '0.1.0' + │ ┬ + │ ╰── a ';' goes here + │ + ├─ 💡 help: end every value with ';': example-version: '0.1.0'; + ╰─ 🎭 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. + diff --git a/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs b/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs index 77df81c..9832911 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/CustomCommands.cs @@ -16,6 +16,16 @@ public sealed class CustomCommandsException : Exception { } + /// <summary>A problem of the file, with all it takes to show it well.</summary> + public CustomCommandsException(Diagnostic diagnostic) + : base((diagnostic ?? throw new ArgumentNullException(nameof(diagnostic))).Plain) + { + Diagnostic = diagnostic; + } + + /// <summary>The place, the line, the help and the joke, when the problem has a place.</summary> + public Diagnostic? Diagnostic { get; } + /// <summary>Nothing to say.</summary> public CustomCommandsException() { diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs b/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs new file mode 100644 index 0000000..18c74cf --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using Progmasoft.Tazel.Dsl.Custom.Lexer; + +namespace Progmasoft.Tazel.Dsl.Custom; + +/// <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. +/// </summary> +/// <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> +/// <param name="Width">How many characters the mark covers, at least 1.</param> +/// <param name="SourceLine">The text of the line, without its line ending; empty when unknown.</param> +/// <param name="Message">What is wrong, in one sentence.</param> +/// <param name="Label">What the mark under the line says.</param> +/// <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) +{ + /// <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? joke = null) + { + ArgumentNullException.ThrowIfNull(text); + return new Diagnostic(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) + { + ArgumentNullException.ThrowIfNull(token); + var width = token.Kind switch + { + TokenKind.String => token.Text.Length + 2, + TokenKind.Placeholder => token.Text.Length + 2, + _ => token.Text.Length, + }; + return At(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) + { + ArgumentNullException.ThrowIfNull(token); + var marked = AtToken(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 }; + } + + private static string LineOf(string text, int line) + { + var start = 0; + for (var current = 1; current < line; current++) + { + var next = text.IndexOf('\n', start); + if (next < 0) + { + return ""; + } + + start = next + 1; + } + + var end = text.IndexOf('\n', start); + return (end < 0 ? text[start..] : text[start..end]).TrimEnd('\r').Replace('\t', ' '); + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Jokes.cs b/src/Progmasoft.Tazel/Dsl/Custom/Jokes.cs new file mode 100644 index 0000000..8999e46 --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Custom/Jokes.cs @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System.Collections.Generic; +using Progmasoft.Tazel.Dsl.Custom.Lexer; + +namespace Progmasoft.Tazel.Dsl.Custom; + +/// <summary> +/// The light lines of Tazel's errors. The same problem always gets the same line, so a test or a log reads the same +/// every time; which line a message gets depends only on its text. +/// </summary> +internal static class Jokes +{ + private static readonly string[] Project = + [ + "Tazel read your project files very carefully and found exactly one thing to complain about.", + "Builds are like soufflés: one wrong ingredient and nothing rises.", + "Tazel stopped here rather than guess. Guessing is how bugs are born.", + "Nothing was built, so at least nothing was broken.", + "Every great build starts with a small fix. This is yours.", + ]; + + private static readonly string[] CommandLine = + [ + "Tazel takes command lines literally; it is that kind of friend.", + "Close! Computers just do not do 'close'.", + "Typing is hard. Tazel would know; it has no fingers.", + "Tazel wanted to say yes. The parser said no.", + ]; + + /// <summary>The line for something missing where <paramref name="kind"/> belongs.</summary> + public static string Missing(TokenKind kind) => kind switch + { + TokenKind.Semicolon => "Semicolons are small, but they hold this whole file together.", + TokenKind.Colon => "A name without its ':' is a name with nothing to say.", + TokenKind.Open => "Every good step opens with a '('.", + TokenKind.Close => "What opens must close. Parentheses are very strict about that.", + TokenKind.String => "Tazel expected words in quotes and got the silent treatment.", + _ => "Tazel expected a name here and found a stranger.", + }; + + /// <summary>The line for an error of a project file, a label or a build.</summary> + public static string ForProject(string message) => Pick(Project, message); + + /// <summary>The line for a command line Tazel cannot take.</summary> + public static string ForCommandLine(string message) => Pick(CommandLine, message); + + // string.GetHashCode differs between runs; this does not. + private static string Pick(IReadOnlyList<string> lines, string message) + { + var hash = 0u; + foreach (var letter in message) + { + hash = (hash * 31) + letter; + } + + return lines[(int)(hash % (uint)lines.Count)]; + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs index 72f8a00..04fc3a3 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs @@ -93,7 +93,9 @@ public sealed class CustomLexer(string text, string file) ';' => TokenKind.Semicolon, '(' => TokenKind.Open, ')' => TokenKind.Close, - _ => throw Fail($"'{letter}' has no meaning here", _line, _column), + _ => throw Fail($"'{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."), }; tokens.Add(new Token(kind, letter.ToString(), _line, _column)); Advance(); @@ -107,8 +109,9 @@ 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) => - new($"{file}:{line}:{column}: {message}"); + 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)); private char Advance() { @@ -143,7 +146,8 @@ public sealed class CustomLexer(string text, string file) Advance(); } - throw Fail("this comment has no closing #>", line, column); + throw Fail("this comment has no closing #>", line, column, 2, "the comment opens here", "close it with #>", + "This comment is still talking. Somebody has to say #>."); } // A string has no escapes: it ends at the next quote of its own kind, whatever comes between. @@ -159,7 +163,8 @@ public sealed class CustomLexer(string text, string file) if (_position == text.Length) { - throw Fail($"this string has no closing {quote}", line, column); + throw Fail($"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."); } var value = text[begin.._position]; @@ -179,7 +184,8 @@ public sealed class CustomLexer(string text, string file) if (_position == text.Length || text[_position] != '>') { - throw Fail("expected <N> or <*>", line, column); + throw Fail("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."); } var value = text[begin.._position]; @@ -193,7 +199,12 @@ public sealed class CustomLexer(string text, string file) $"<{value}> is not an argument: <N> runs from 1 to {CustomCommandFiles.MaxArguments}, " + "and <*> is all of them", line, - column); + column, + value.Length + 2, + "this one", + $"use <1> to <{CustomCommandFiles.MaxArguments}>, or <*>", + value == "0" ? "Tazel counts from 1, like a person, not from 0, like a computer." + : "That is a lot of arguments. Tazel would rather not argue that much."); } return new Token(TokenKind.Placeholder, value, line, column); diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs index 3a3addc..394e306 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs @@ -14,9 +14,9 @@ public static class CustomParser { /// <summary>The commands of the text of a <c>tazel_custom.txt</c>, in the order they are written.</summary> public static IReadOnlyList<CustomCommand> Parse(string text, string file = CustomCommandFiles.FileName) => - new Reader(new CustomLexer(text, file).Tokens(), file).Commands(); + new Reader(new CustomLexer(text, file).Tokens(), file, text).Commands(); - private sealed class Reader(IReadOnlyList<Token> tokens, string file) + private sealed class Reader(IReadOnlyList<Token> tokens, string file, string text) { private int _position; @@ -35,12 +35,17 @@ public static class CustomParser if (words.Contains(CustomCommandFiles.NameEnd)) { - throw Fail(name, $"'{CustomCommandFiles.NameEnd}' ends a name on the command line, so a name cannot hold it"); + var end = words.IndexOf(CustomCommandFiles.NameEnd); + throw Fail(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."); } if (words.Count > CustomCommandFiles.MaxArguments) { - throw Fail(name, $"a name holds at most {CustomCommandFiles.MaxArguments} words"); + throw Fail(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."); } Take(TokenKind.Colon, "':' after the name of a command"); @@ -55,7 +60,8 @@ public static class CustomParser var joined = string.Join(' ', words); if (commands.ContainsKey(joined)) { - throw Fail(name, $"the command '{joined}' is defined twice"); + throw Fail(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."); } var command = new CustomCommand(joined, steps); @@ -64,7 +70,10 @@ public static class CustomParser throw Fail( name, $"'{joined}' needs {command.Required} arguments, and its name leaves room for " + - $"{CustomCommandFiles.MaxArguments - words.Count}"); + $"{CustomCommandFiles.MaxArguments - words.Count}", + "this name", + "use fewer <N> in its steps, or fewer words in its name", + "The arguments do not all fit in the car."); } commands[joined] = command; @@ -76,21 +85,53 @@ public static class CustomParser private Token? Peek() => _position < tokens.Count ? tokens[_position] : null; - private CustomCommandsException Fail(Token? token, string message) => - new($"{file}:{(token is null ? "" : $"{token.Line}:{token.Column}: ")}{message}"); + private CustomCommandsException Fail(Token token, string message, string label, string? help, string? joke) => + new(Diagnostic.AtToken(text, file, token, message, label, help, joke)); private Token Take(TokenKind kind, string wanted) { var token = Peek(); - if (token?.Kind != kind) + if (token?.Kind == kind) { - throw Fail(token ?? tokens.LastOrDefault(), $"expected {wanted}"); + _position++; + return token; + } + + var previous = _position > 0 ? tokens[_position - 1] : null; + var help = kind switch + { + TokenKind.Semicolon => "end every command with ';': build: (\"tazel\" \"build\" \"//...\");", + TokenKind.Colon => "a name and its steps are joined by ':': build: (\"tazel\" \"build\");", + TokenKind.Open => "a step is (\"program\" \"argument\") or s(\"a shell line\")", + TokenKind.Close => "close the step with ')'", + _ => "a command is: name: (\"program\" \"argument\");", + }; + // 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}", + $"{Describe(kind)} goes here", help, Jokes.Missing(kind))); } - _position++; - return token; + if (token is null) + { + throw new CustomCommandsException(Diagnostic.At(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)); } + private static string Describe(TokenKind kind) => kind switch + { + TokenKind.Semicolon => "a ';'", + TokenKind.Colon => "a ':'", + TokenKind.Open => "a '('", + TokenKind.Close => "a ')'", + TokenKind.String => "a string", + _ => "a name", + }; + private List<Token> Values() { var values = new List<Token>(); @@ -123,12 +164,15 @@ 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"); + throw Fail(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: s(\"npm dev\")"); + throw Fail(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."); } return new CustomStep.Shell(values[0].Text); @@ -136,12 +180,14 @@ public static class CustomParser if (values.Count == 0) { - throw Fail(open, "a command names at least a program"); + throw Fail(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"); + throw Fail(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."); } return new CustomStep.Program(values.Select(ArgumentOf).ToList()); diff --git a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs index df74e94..83cfaa8 100644 --- a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs +++ b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs @@ -48,18 +48,22 @@ public static class TazelEnvsFile /// <summary>The entries of <paramref name="text"/>; <paramref name="file"/> names it in messages.</summary> public static IReadOnlyList<EnvEntry> Parse(string text, string file = FileName) { + ArgumentNullException.ThrowIfNull(text); var tokens = new CustomLexer(text, file).Tokens(); var entries = new List<EnvEntry>(); - var names = new HashSet<string>(StringComparer.Ordinal); + var names = new Dictionary<string, Token>(StringComparer.Ordinal); var i = 0; while (i < tokens.Count) { var name = Take(TokenKind.Name, "the name of a value"); - if (!names.Add(name.Text)) + if (names.TryGetValue(name.Text, out var first)) { - throw Fail(name, $"'{name.Text}' is set twice"); + throw Fail(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}"); EnvValue value; if (Peek() is { Kind: TokenKind.String } literal) @@ -75,7 +79,8 @@ 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: s(`$HOME`)"); + : throw Fail(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 }) { @@ -84,11 +89,21 @@ 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: (\"rustc\" \"--help\")"); + : throw Fail(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", + $"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 Fail(Peek() ?? name, $"expected the value of {name.Text}: a string, (\"program\" \"argument\") or s(\"line\")"); + throw new CustomCommandsException(Diagnostic.After(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}"); @@ -101,13 +116,34 @@ public static class TazelEnvsFile Token Take(TokenKind kind, string wanted) { - if (Peek() is not { } token || token.Kind != kind) + if (Peek() is { } token && token.Kind == kind) + { + i++; + return token; + } + + 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)) { - throw Fail(Peek() ?? tokens[^1], $"expected {wanted}"); + throw new CustomCommandsException(Diagnostic.After(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))); } - i++; - return token; + throw Fail(Peek()!, $"expected {wanted}", "not this", help, Jokes.Missing(kind)); } List<string> Strings() @@ -121,13 +157,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 <*>"); + throw Fail(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) => new($"{file}:{token.Line}:{token.Column}: {message}"); + CustomCommandsException Fail(Token token, string message, string label, string help, string joke) => + new(Diagnostic.AtToken(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 4b19b9f..8ca7fc0 100644 --- a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs +++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs @@ -53,6 +53,16 @@ public sealed class TazelOptionsException : Exception { } + /// <summary>A problem of the file, with all it takes to show it well.</summary> + public TazelOptionsException(Diagnostic diagnostic) + : base((diagnostic ?? throw new ArgumentNullException(nameof(diagnostic))).Plain) + { + Diagnostic = diagnostic; + } + + /// <summary>The place, the line, the help and the joke, when the problem has a place.</summary> + public Diagnostic? Diagnostic { get; } + /// <summary>Nothing to say.</summary> public TazelOptionsException() { @@ -88,10 +98,10 @@ public static class TazelOptionsFile } catch (CustomCommandsException error) { - throw new TazelOptionsException(error.Message, error); + throw error.Diagnostic is { } diagnostic ? new TazelOptionsException(diagnostic) : new TazelOptionsException(error.Message, error); } - return new Reader(tokens, file).Options(); + return new Reader(tokens, file, text).Options(); } /// <summary>Every <c>tazel_options.txt</c> at or above <paramref name="directory"/>, the nearest first.</summary> @@ -169,7 +179,7 @@ public static class TazelOptionsFile return Parse(text, file); } - private sealed class Reader(IReadOnlyList<Token> tokens, string file) + private sealed class Reader(IReadOnlyList<Token> tokens, string file, string text) { private int _position; @@ -182,18 +192,24 @@ public static class TazelOptionsFile var key = Take(TokenKind.Name, "the name of an option"); if (!Keys.Contains(key.Text, StringComparer.Ordinal)) { - throw Fail(key, $"'{key.Text}' is not an option; the options are {string.Join(", ", Keys)}"); + var near = Cli.Suggestions.Nearest(key.Text, Keys); + throw Fail(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"); + throw Fail(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 Fail(_position < tokens.Count ? tokens[_position] : key, $"expected a value for {key.Text}"); + throw new TazelOptionsException(Diagnostic.After(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.")); } var value = tokens[_position++]; @@ -216,46 +232,75 @@ public static class TazelOptionsFile return options; } - private TazelOptionsException Fail(Token token, string message) => - new($"{file}:{token.Line}:{token.Column}: {message}"); + private TazelOptionsException Fail(Token token, string message, string label, string help, string joke) => + new(Diagnostic.AtToken(text, file, token, message, label, help, joke)); + + private static string Example(string key) => key switch + { + "platform" => "linux-amd64", + "microvm-memory" => "2048", + "microvm-cpus" => "2", + _ => "true", + }; private Token Take(TokenKind kind, string wanted) { - if (_position >= tokens.Count || tokens[_position].Kind != kind) + if (_position < tokens.Count && tokens[_position].Kind == kind) + { + return tokens[_position++]; + } + + var help = kind switch + { + TokenKind.Semicolon => "end the value with ';': platform: linux-amd64;", + TokenKind.Colon => "an option and its value are joined by ':': platform: linux-amd64;", + _ => "an option is: name: value;", + }; + if (_position > 0 && (_position >= tokens.Count || kind is TokenKind.Semicolon or TokenKind.Colon)) { - throw Fail(_position < tokens.Count ? tokens[_position] : tokens[^1], $"expected {wanted}"); + throw new TazelOptionsException(Diagnostic.After(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))); } - return tokens[_position++]; + throw Fail(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"); + : throw Fail(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. private Allocation Amount(Token value, int min, int max, string unit) { if (value.Kind == TokenKind.String) { - return value.Text == "auto" ? Allocation.Auto : throw Fail(value, "the only string here is \"auto\""); + return value.Text == "auto" ? Allocation.Auto : throw Fail(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\""); + throw Fail(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}") + ? throw Fail(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); } 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; the platforms are {string.Join(", ", Platforms.Names)}"); + : throw Fail(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)}", + "Tazel looked on every map; there is no such place."); } } diff --git a/src/Progmasoft.Tazel/Output/Reporter.cs b/src/Progmasoft.Tazel/Output/Reporter.cs index 9f8127e..f746e33 100644 --- a/src/Progmasoft.Tazel/Output/Reporter.cs +++ b/src/Progmasoft.Tazel/Output/Reporter.cs @@ -126,15 +126,81 @@ internal sealed class Reporter } } - /// <summary>What went wrong, ending the command.</summary> - public void Error(string message) + /// <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) { lock (_lock) { - Console.MarkupLine($"[red bold]error[/]: {Markup.Escape(message)}"); + var fancy = Console.Profile.Capabilities.Unicode; + Console.MarkupLine($"[red bold]{(fancy ? "✖ " : "")}error[/]: [bold]{Markup.Escape(message)}[/]"); + if (help is not null) + { + Console.MarkupLine($" [blue]{(fancy ? "├─" : "|-")}[/] [green]{(fancy ? "💡 " : "")}help:[/] {Markup.Escape(help)}"); + } + + if (joke is not null) + { + Console.MarkupLine($" [blue]{(fancy ? "╰─" : "`-")}[/] [magenta italic]{(fancy ? "🎭 " : "")}{Markup.Escape(joke)}[/]"); + } + } + } + + /// <summary> + /// 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) + { + ArgumentNullException.ThrowIfNull(diagnostic); + lock (_lock) + { + var fancy = Console.Profile.Capabilities.Unicode; + var number = diagnostic.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); + string Gutter(string left) => $"[blue]{left} {bar}[/]"; + + Console.MarkupLine($"[red bold]{(fancy ? "✖ " : "")}error[/]: [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) + { + Console.MarkupLine($"{Gutter(number)} {Markup.Escape(diagnostic.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)); + } + + if (diagnostic.Help is not null) + { + Console.MarkupLine($"[blue]{pad} {(fancy ? "├─" : "|-")}[/] [green]{(fancy ? "💡 " : "")}help:[/] {Markup.Escape(diagnostic.Help)}"); + } + + if (diagnostic.Joke is not null) + { + Console.MarkupLine($"[blue]{pad} {(fancy ? "╰─" : "`-")}[/] [magenta italic]{(fancy ? "🎭 " : "")}{Markup.Escape(diagnostic.Joke)}[/]"); + } } } + // A file below the current directory is shown from there, which is shorter and what the user typed. + private static string Shown(string file) + { + if (!System.IO.Path.IsPathRooted(file)) + { + return file; + } + + var relative = System.IO.Path.GetRelativePath(Environment.CurrentDirectory, file); + return relative.StartsWith("..", StringComparison.Ordinal) ? file : relative; + } + /// <summary>Something the user should know that does not stop the command.</summary> public void Warning(string message) => Write($"[yellow]warning[/]: {Markup.Escape(message)}"); diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index f100ac1..150ee28 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: MIT using System; +using System.Linq; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -41,7 +42,8 @@ internal static class Program } catch (CommandLineException error) { - new Reporter(Reporter.CreateConsole(When.Auto, output), quiet: false, When.Never).Error(error.Message); + new Reporter(Reporter.CreateConsole(When.Auto, output), quiet: false, When.Never).Error(error.Message, + HelpFor(arguments), Jokes.ForCommandLine(error.Message)); return UsageError; } @@ -52,13 +54,18 @@ internal static class Program } catch (CommandLineException error) { - reporter.Error(error.Message); + reporter.Error(error.Message, HelpFor(arguments), Jokes.ForCommandLine(error.Message)); return UsageError; } + catch (Exception error) when (Placed(error) is { } diagnostic) + { + reporter.Diagnostic(diagnostic); + return 1; + } catch (Exception error) when (error is ProjectException or LabelException or TazelOptionsException or CustomCommandsException) { - reporter.Error(error.Message); + reporter.Error(error.Message, null, Jokes.ForProject(error.Message)); return 1; } catch (OperationCanceledException) @@ -67,4 +74,28 @@ internal static class Program return 130; } } + + /// <summary>The diagnostic of a problem with a place in a file, found through the causes too.</summary> + private static Diagnostic? Placed(Exception? error) + { + for (; error is not null; error = error.InnerException) + { + switch (error) + { + case CustomCommandsException { Diagnostic: { } custom }: + return custom; + case TazelOptionsException { Diagnostic: { } options }: + return options; + } + } + + return null; + } + + /// <summary>Where to read about the command that was typed.</summary> + private static string HelpFor(string[] arguments) + { + var command = arguments.FirstOrDefault(argument => CommandLine.Commands.Contains(argument, StringComparer.Ordinal)); + return command is null ? "tazel help lists the commands" : $"tazel help {command} --long says what {command} takes"; + } } diff --git a/tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs b/tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs new file mode 100644 index 0000000..5084dcd --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/DiagnosticTests.cs @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +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 Xunit; + +namespace Progmasoft.Tazel.Tests; + +public sealed class DiagnosticTests +{ + [Theory] + [InlineData("envs", "x: '1'")] + [InlineData("envs", "x '1';")] + [InlineData("envs", "x: '1';\nx: '2';")] + [InlineData("envs", "x: version;")] + [InlineData("envs", "x:")] + [InlineData("envs", "x: ();")] + [InlineData("envs", "x: s('a' 'b');")] + [InlineData("envs", "x: ('echo' <1>);")] + [InlineData("envs", "x: \"open")] + [InlineData("envs", "<# open")] + [InlineData("envs", "x: @;")] + [InlineData("custom", "build (\"tazel\");")] + [InlineData("custom", "build: (\"tazel\")")] + [InlineData("custom", "build: ();")] + [InlineData("custom", "build: s(\"a\" \"b\");")] + [InlineData("custom", "build: (<1>);")] + [InlineData("custom", "build: (\"a\" <0>);")] + [InlineData("custom", "a: (\"x\");\na: (\"y\");")] + [InlineData("options", "platform: linux-amd46;")] + [InlineData("options", "plaform: linux-amd64;")] + [InlineData("options", "microvm-cpus: 99999;")] + [InlineData("options", "microvm-network: maybe;")] + [InlineData("options", "microvm-memory: \"lots\";")] + [InlineData("options", "platform linux-amd64;")] + [InlineData("options", "platform:")] + public void EveryProblemIsShownWithItsPlaceHelpAndAJoke(string reader, string text) + { + var diagnostic = DiagnosticOf(reader, text); + Assert.NotNull(diagnostic); + Assert.False(string.IsNullOrWhiteSpace(diagnostic.Label)); + Assert.False(string.IsNullOrWhiteSpace(diagnostic.Help)); + Assert.False(string.IsNullOrWhiteSpace(diagnostic.Joke)); + Assert.InRange(diagnostic.Column, 1, diagnostic.SourceLine.Length + 1); + Assert.Equal(text.Split('\n')[diagnostic.Line - 1], diagnostic.SourceLine); + } + + [Fact] + public void AMissingSemicolonIsMarkedRightAfterTheValue() + { + var diagnostic = DiagnosticOf("envs", "example-version: '0.1.0'\n")!; + Assert.Equal((1, 25), (diagnostic.Line, diagnostic.Column)); + Assert.Equal("a ';' goes here", diagnostic.Label); + Assert.Contains("example-version: '0.1.0';", diagnostic.Help, StringComparison.Ordinal); + } + + [Fact] + public void AMisspelledPlatformGetsASuggestion() => + Assert.Equal("did you mean linux-amd64?", DiagnosticOf("options", "platform: linux-amd46;")!.Help); + + [Fact] + public void TheSameProblemAlwaysGetsTheSameJoke() => + Assert.Equal(Jokes.ForProject("//:x is not a target"), Jokes.ForProject("//:x is not a target")); + + [Fact] + public async Task TheErrorIsDrawnWithTheLineAMarkHelpAndAJoke() + { + using var module = new TemporaryModule().Write("MODULE.csx", TemporaryModule.ModuleFile) + .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("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); + Assert.Contains("help: end every value with ';'", output, StringComparison.Ordinal); + Assert.Contains("Semicolons are small, but they hold this whole file together.", output, StringComparison.Ordinal); + } + + [Fact] + public async Task ACommandLineErrorSaysWhereTheHelpIs() + { + using var module = new TemporaryModule(); + var (status, written) = await module.TazelAsync(".", "build", "--colour", "never"); + // The command line is read before --color is, so the colors stay; they are not what this test is about. + var output = System.Text.RegularExpressions.Regex.Replace(written, "\u001b\\[[0-9;]*m", ""); + 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()), + output, StringComparison.Ordinal); + } + + private static Diagnostic? DiagnosticOf(string reader, string text) + { + try + { + switch (reader) + { + case "envs": + TazelEnvsFile.Parse(text); + break; + case "custom": + CustomParser.Parse(text); + break; + default: + TazelOptionsFile.Parse(text); + break; + } + } + catch (CustomCommandsException error) + { + return error.Diagnostic; + } + catch (TazelOptionsException error) + { + return error.Diagnostic; + } + + Assert.Fail($"'{text}' was read without a problem"); + return null; + } +}