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 the text files one grammar with includes, imports and conditions
- Commit
5441213294ad0a5d027ebacc176c08187433dee7- Author
- Leitwolf11 ·
- Parents
7b1cda50620e
Changes
CHANGELOG.md | 6 + docs/commands.md | 48 +++ src/Progmasoft.Tazel/Cli/Commands.cs | 8 +- src/Progmasoft.Tazel/Cli/Help.cs | 2 +- .../Dsl/Configuration/Conditions.cs | 413 +++++++++++++++++++++ .../Dsl/Configuration/ConfigurationParser.cs | 239 ++++++++++++ .../Dsl/Configuration/ConfigurationResolver.cs | 359 ++++++++++++++++++ .../Dsl/Configuration/TazelHome.cs | 65 ++++ src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs | 2 + .../Dsl/Custom/Lexer/CustomLexer.cs | 81 +++- .../Dsl/Custom/Parser/CustomParser.cs | 11 +- src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs | 28 +- src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs | 27 +- src/Progmasoft.Tazel/Output/ErrorCodes.cs | 43 +++ src/Progmasoft.Tazel/Project/Workspace.cs | 20 +- tests/Progmasoft.Tazel.Tests/ConfigurationTests.cs | 303 +++++++++++++++ 16 files changed, 1625 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6722245..bbdc28f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ ## Unreleased +- `tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` take directives: `.include "file"` and + `.include <file>` (below `$TAZEL_HOME/Include/`), `.import`, `.pragma once`, and `.if`, `.elif`, `.else`, `.end` on + conditions over `host_system`, `target_system`, `defined("NAME")` and `env("NAME")`. `tazel_options.txt` chooses the + platform before it reads what depends on it. A line that starts with a dot and a letter is a directive; a name that + starts with a dot goes in quotes. Errors `E0006` to `E0012`. + - Breaking: a package's project file is `BUILD.csx` and nothing else; a directory with `BUILD.tzl`, `BUILD.tazel`, `BUILD` or `Tazel.build` stops the build with a message. `Depends` takes labels only, such as `"//:math"`; the value a declaration returns is no longer taken. `tazel limited-time C#`, until 1.0.0, renames those files and writes the diff --git a/docs/commands.md b/docs/commands.md index 44ea283..27ba531 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -141,6 +141,54 @@ above stays asked for. This Tazel has no MicroVM to start, so with `sandboxing-w command that would run what a project brings (`build`, `run`, `test`, `package`, `custom`) rather than run it on this machine. +## Directives of the text files + +`tazel_options.txt`, `tazel_custom.txt` and `tazel_envs.txt` share one grammar: besides their entries they take +directives, lines that start with a dot and need no `;`. + +```text +.pragma once +.import <security.options.txt> +.include "config/build.options.txt" +platform: linux-amd64; +.if target_system.os == "linux" && !defined("CI") + microvm-memory: 4096; +.elif host_system.os == "macos" + microvm-memory: 2048; +.else + microvm-memory: auto; +.end +``` + +- `.include "file"` reads a file in this place, as if its text stood here; the path is relative to the directory of the + file that names it. `.include <file>` reads one below `$TAZEL_HOME/Include/Options/` (`Custom/`, `Envs/` for the + other two files), and may not leave it, through `..` or a link. `TAZEL_HOME` is `$HOME/.Tazel`, or + `%APPDATA%\Tazel` on Windows, when it is not set; set, it must be an absolute path. +- `.import` does the same, once: a file already read is not read again, and an imported file is not included again + either. `.pragma once`, first in a file, says the same of the file itself. A file that includes itself otherwise is + an error that shows the chain. +- Paths are taken as written: no wildcards, no URLs, no environment variables; a quoted path is not absolute. The + name of a file does not matter; `.options.txt`, `.custom.txt` and `.envs.txt` are the custom. +- `.if`, `.elif`, `.else` and `.end` choose the first branch whose condition holds. A branch not taken is read, so its + mistakes are found, but its includes are not opened. A condition takes `true`, `false`, strings in any of the three + quotes, `==`, `!=`, `!`, `&&`, `||` and parentheses, and: + + | Name | Value | + | --- | --- | + | `host_system.os`, `target_system.os` | `linux`, `windows`, `macos`, `freebsd`, `openbsd`, `dragonfly` | + | `host_system.arch`, `target_system.arch` | `amd64` or `aarch64`, on every system | + | `host_system.abi`, `target_system.abi` | `gnu`, `musl`, `msvc` or `default` | + | `host_system.platform`, `target_system.platform` | the platform's name, as `--platform` takes it | + | `defined("NAME")` | whether the environment variable is set | + | `env("NAME")` | its value, `""` when it is not set | + + A condition runs nothing; the environment is read once for the whole command. +- `tazel_options.txt` is read twice. First, without the branches that depend on `target_system`, which choose the + platform: `--platform`, else the file's `platform`, else this machine's. Then everything is read for that platform. + A `platform` inside a condition on `target_system`, or in a file such a branch includes, is an error. +- Includes nest 64 deep, `.if` blocks 64 deep, and one configuration reads at most 4,096 files and 1,000,000 tokens. + The last entry of each file may leave out its `;`. An error in an included file is shown in that file. + ## tazel_custom.txt ```text diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 57bf47c..bf7c734 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -202,7 +202,13 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector throw new CustomCommandsException($"there is no {CustomCommandFiles.FileName} in {workingDirectory}"); } - var commands = CustomParser.Parse(File.ReadAllText(file)); + // Its conditions see the platform tazel_options.txt chooses, else this machine's. + var (options, _) = TazelOptionsFile.Effective(workingDirectory); + var context = Dsl.Configuration.ConfigurationContext.ForThisMachine() with + { + Target = Dsl.Configuration.SystemFacts.Of(options.Platform ?? Driver.Host.Platform), + }; + var commands = CustomParser.Parse(File.ReadAllText(file), CustomCommandFiles.FileName, file, context); if (words.Count > CustomCommandFiles.MaxArguments) { throw new CommandLineException($"tazel custom takes at most {CustomCommandFiles.MaxArguments} words"); diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs index 986b5c3..c4b0542 100644 --- a/src/Progmasoft.Tazel/Cli/Help.cs +++ b/src/Progmasoft.Tazel/Cli/Help.cs @@ -181,7 +181,7 @@ internal static class Help 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) + 00 the text files (their comments, strings, placeholders and directives) 01 the command line 02 tazel_options.txt 03 tazel_custom.txt diff --git a/src/Progmasoft.Tazel/Dsl/Configuration/Conditions.cs b/src/Progmasoft.Tazel/Dsl/Configuration/Conditions.cs new file mode 100644 index 0000000..b8d9635 --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Configuration/Conditions.cs @@ -0,0 +1,413 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using Progmasoft.Tazel.Dsl.Common; + +namespace Progmasoft.Tazel.Dsl.Configuration; + +/// <summary>What a condition or a part of one stands for.</summary> +public enum ConditionType +{ + /// <summary>true or false.</summary> + Boolean, + + /// <summary>A string.</summary> + String, +} + +/// <summary>A condition, or a part of one, of <c>.if</c> and <c>.elif</c>.</summary> +public abstract record Condition +{ + /// <summary>What it stands for.</summary> + public abstract ConditionType Type { get; } + + /// <summary>Whether it names <c>target_system</c>, so it holds only once the platform is chosen.</summary> + public abstract bool UsesTarget { get; } +} + +/// <summary><c>true</c>, <c>false</c> or a string in quotes.</summary> +/// <param name="Value">A bool or a string.</param> +public sealed record LiteralCondition(object Value) : Condition +{ + /// <inheritdoc/> + public override ConditionType Type => Value is bool ? ConditionType.Boolean : ConditionType.String; + + /// <inheritdoc/> + public override bool UsesTarget => false; +} + +/// <summary><c>host_system.os</c> and the like.</summary> +/// <param name="System"><c>host_system</c> or <c>target_system</c>.</param> +/// <param name="Field"><c>os</c>, <c>arch</c>, <c>abi</c> or <c>platform</c>.</param> +public sealed record MemberCondition(string System, string Field) : Condition +{ + /// <inheritdoc/> + public override ConditionType Type => ConditionType.String; + + /// <inheritdoc/> + public override bool UsesTarget => System == "target_system"; +} + +/// <summary><c>defined("NAME")</c> or <c>env("NAME")</c>.</summary> +/// <param name="Function"><c>defined</c> or <c>env</c>.</param> +/// <param name="Name">The name of the environment variable.</param> +public sealed record CallCondition(string Function, string Name) : Condition +{ + /// <inheritdoc/> + public override ConditionType Type => Function == "defined" ? ConditionType.Boolean : ConditionType.String; + + /// <inheritdoc/> + public override bool UsesTarget => false; +} + +/// <summary><c>!</c> of a condition.</summary> +/// <param name="Operand">The condition.</param> +public sealed record NotCondition(Condition Operand) : Condition +{ + /// <inheritdoc/> + public override ConditionType Type => ConditionType.Boolean; + + /// <inheritdoc/> + public override bool UsesTarget => Operand.UsesTarget; +} + +/// <summary><c>==</c>, <c>!=</c>, <c>&&</c> or <c>||</c> of two conditions.</summary> +/// <param name="Operator">The operator.</param> +/// <param name="Left">Its left side.</param> +/// <param name="Right">Its right side.</param> +public sealed record BinaryCondition(string Operator, Condition Left, Condition Right) : Condition +{ + /// <inheritdoc/> + public override ConditionType Type => ConditionType.Boolean; + + /// <inheritdoc/> + public override bool UsesTarget => Left.UsesTarget || Right.UsesTarget; +} + +/// <summary>A condition that cannot be read.</summary> +public sealed class ConditionException : Exception +{ + /// <summary>What is wrong.</summary> + public ConditionException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public ConditionException() + { + } + + /// <summary>What is wrong, and why.</summary> + public ConditionException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary>What a condition sees of a system: <c>host_system</c> or <c>target_system</c>.</summary> +/// <param name="Os"><c>linux</c>, <c>windows</c>, <c>macos</c>, <c>freebsd</c>, <c>openbsd</c> or <c>dragonfly</c>.</param> +/// <param name="Arch"><c>amd64</c> (x86-64) or <c>aarch64</c> (ARM64), the same on every system.</param> +/// <param name="Abi"><c>gnu</c>, <c>musl</c>, <c>msvc</c> or <c>default</c>.</param> +/// <param name="Platform">The name of the platform, as <c>--platform</c> takes it, such as <c>linux-amd64</c>.</param> +public sealed record SystemFacts(string Os, string Arch, string Abi, string Platform) +{ + /// <summary>The facts of <paramref name="platform"/>.</summary> + public static SystemFacts Of(Platform platform) => new( + platform.GetOS() switch + { + OS.Linux => "linux", + OS.Windows => "windows", + OS.MacOS => "macos", + OS.FreeBSD => "freebsd", + OS.OpenBSD => "openbsd", + _ => "dragonfly", + }, + platform.GetArch() == Common.Arch.X64 ? "amd64" : "aarch64", + platform.GetOS() switch + { + OS.Linux => "gnu", + OS.Windows => "msvc", + _ => "default", + }, + platform.Name()); + + /// <summary>The value of <paramref name="field"/>.</summary> + public string this[string field] => field switch + { + "os" => Os, + "arch" => Arch, + "abi" => Abi, + _ => Platform, + }; +} + +/// <summary>Reads the text of a condition: the lexer and parser of the condition language in one.</summary> +internal sealed class ConditionReader(string text) +{ + private static readonly HashSet<string> Fields = new(StringComparer.Ordinal) { "os", "arch", "abi", "platform" }; + + private int _position; + + public Condition Read() + { + if (text.Length == 0) + { + throw new ConditionException("the condition is missing"); + } + + var condition = Or(); + Space(); + if (_position < text.Length) + { + // The usual slips of other languages get their own words. + var rest = text[_position..]; + throw new ConditionException(rest[0] switch + { + '=' => "'=' is not an operator of conditions; compare with ==", + '&' => "'&' is not an operator of conditions; write &&", + '|' => "'|' is not an operator of conditions; write ||", + _ => $"'{rest}' cannot follow '{text[.._position].TrimEnd()}'", + }); + } + + return condition; + } + + private Condition Or() + { + var left = And(); + while (Take("||")) + { + left = new BinaryCondition("||", Booleans(left, "||"), Booleans(And(), "||")); + } + + return left; + } + + private Condition And() + { + var left = Equality(); + while (Take("&&")) + { + left = new BinaryCondition("&&", Booleans(left, "&&"), Booleans(Equality(), "&&")); + } + + return left; + } + + private Condition Equality() + { + var left = Unary(); + while (true) + { + var op = Take("==") ? "==" : Take("!=") ? "!=" : null; + if (op is null) + { + return left; + } + + var right = Unary(); + if (left.Type != right.Type) + { + throw new ConditionException($"{op} compares a {Name(left.Type)} with a {Name(right.Type)}"); + } + + left = new BinaryCondition(op, left, right); + } + } + + private Condition Unary() + { + Space(); + if (_position < text.Length && text[_position] == '!' && !At("!=")) + { + _position++; + return new NotCondition(Booleans(Unary(), "!")); + } + + return Primary(); + } + + private Condition Primary() + { + Space(); + if (_position >= text.Length) + { + throw new ConditionException("the condition ends where a value should be"); + } + + var letter = text[_position]; + if (letter == '(') + { + _position++; + var inner = Or(); + if (!Take(")")) + { + throw new ConditionException("a '(' has no ')'"); + } + + return inner; + } + + if (letter is '"' or '\'' or '`') + { + return new LiteralCondition(Quoted()); + } + + var name = Word(); + if (name.Length == 0) + { + throw new ConditionException($"'{letter}' is not an operator of conditions"); + } + + switch (name) + { + case "true": + return new LiteralCondition(true); + case "false": + return new LiteralCondition(false); + case "host_system" or "target_system": + if (!Take(".")) + { + throw new ConditionException($"{name} needs a field: {name}.os, .arch, .abi or .platform"); + } + + var field = Word(); + return Fields.Contains(field) ? new MemberCondition(name, field) + : throw new ConditionException($"{name}.{field} is not a field; the fields are os, arch, abi and platform"); + case "defined" or "env": + if (!Take("(")) + { + throw new ConditionException($"{name} is called: {name}(\"NAME\")"); + } + + Space(); + if (_position >= text.Length || text[_position] is not ('"' or '\'' or '`')) + { + throw new ConditionException($"{name} takes the name of a variable in quotes"); + } + + var variable = Quoted(); + return Take(")") ? new CallCondition(name, variable) : throw new ConditionException($"{name}(\"{variable}\" has no ')'"); + default: + var near = Cli.Suggestions.Nearest(name, ["true", "false", "host_system", "target_system", "defined", "env"]); + throw new ConditionException($"'{name}' is not a name conditions know{(near is null ? "" : $"; did you mean {near}?")}"); + } + } + + private static Condition Booleans(Condition condition, string op) => condition.Type == ConditionType.Boolean + ? condition + : throw new ConditionException($"{op} takes true or false, and a string stands beside it; compare the string with == or !="); + + private static string Name(ConditionType type) => type == ConditionType.Boolean ? "boolean" : "string"; + + private string Quoted() + { + var quote = text[_position++]; + var end = text.IndexOf(quote, _position); + if (end < 0) + { + throw new ConditionException($"a string has no closing {quote}"); + } + + var value = text[_position..end]; + _position = end + 1; + return value; + } + + private string Word() + { + var begin = _position; + while (_position < text.Length && (char.IsAsciiLetterOrDigit(text[_position]) || text[_position] == '_')) + { + _position++; + } + + return text[begin.._position]; + } + + private bool At(string what) => string.CompareOrdinal(text, _position, what, 0, what.Length) == 0; + + private bool Take(string what) + { + Space(); + if (!At(what)) + { + return false; + } + + _position += what.Length; + return true; + } + + private void Space() + { + while (_position < text.Length && char.IsWhiteSpace(text[_position])) + { + _position++; + } + } +} + +/// <summary>Evaluates conditions against what the configuration sees.</summary> +public static class ConditionEvaluator +{ + /// <summary> + /// The value of <paramref name="condition"/>: true, false, or null when it needs <c>target_system</c> and + /// <paramref name="target"/> is not chosen yet. <c>&&</c> and <c>||</c> stop at their first side when it + /// decides, so the second may need nothing that is unknown. + /// </summary> + public static bool? Evaluate( + Condition condition, SystemFacts host, SystemFacts? target, IReadOnlyDictionary<string, string> environment) + { + ArgumentNullException.ThrowIfNull(condition); + return Value(condition, host, target, environment) switch + { + bool truth => truth, + _ => null, + }; + } + + // A bool, a string, or null for unknown. + private static object? Value(Condition condition, SystemFacts host, SystemFacts? target, IReadOnlyDictionary<string, string> environment) + { + switch (condition) + { + case LiteralCondition literal: + return literal.Value; + case MemberCondition member: + return member.System == "host_system" ? host[member.Field] : target?[member.Field]; + case CallCondition call: + return call.Function == "defined" ? environment.ContainsKey(call.Name) : environment.GetValueOrDefault(call.Name, ""); + case NotCondition not: + return Value(not.Operand, host, target, environment) is bool truth ? !truth : null; + case BinaryCondition { Operator: "&&" } and: + return Value(and.Left, host, target, environment) switch + { + false => false, + true => Value(and.Right, host, target, environment), + _ => Value(and.Right, host, target, environment) is false ? false : null, + }; + case BinaryCondition { Operator: "||" } or: + return Value(or.Left, host, target, environment) switch + { + true => true, + false => Value(or.Right, host, target, environment), + _ => Value(or.Right, host, target, environment) is true ? true : null, + }; + case BinaryCondition binary: + var (left, right) = (Value(binary.Left, host, target, environment), Value(binary.Right, host, target, environment)); + if (left is null || right is null) + { + return null; + } + + return binary.Operator == "==" ? Equals(left, right) : !Equals(left, right); + default: + throw new ArgumentException($"no condition {condition.GetType().Name}", nameof(condition)); + } + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationParser.cs b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationParser.cs new file mode 100644 index 0000000..0cd2849 --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationParser.cs @@ -0,0 +1,239 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.Linq; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Custom.Lexer; +using Progmasoft.Tazel.Output; + +namespace Progmasoft.Tazel.Dsl.Configuration; + +/// <summary>A part of a text file: tokens of its entries, or a directive.</summary> +/// <param name="At">Where it starts.</param> +public abstract record Node(Token At); + +/// <summary>Tokens of entries, as the reader of the file's kind takes them.</summary> +/// <param name="Tokens">The tokens, in order.</param> +public sealed record TokensNode(IReadOnlyList<Token> Tokens) : Node(Tokens[0]); + +/// <summary><c>.include</c> or <c>.import</c> of a file.</summary> +/// <param name="At">The directive.</param> +/// <param name="Path">The path as written, without its quotes or brackets.</param> +/// <param name="Global">Whether it was written <c><path></c>, below the Include directory of TAZEL_HOME.</param> +/// <param name="Import">Whether it is <c>.import</c>, which reads a file at most once.</param> +public sealed record IncludeNode(Token At, string Path, bool Global, bool Import) : Node(At); + +/// <summary>One branch of an <c>.if</c>: its condition, null for <c>.else</c>, and what it holds.</summary> +/// <param name="At">The <c>.if</c>, <c>.elif</c> or <c>.else</c>.</param> +/// <param name="Condition">The condition, or null for <c>.else</c>.</param> +/// <param name="Body">What the branch holds.</param> +public sealed record Branch(Token At, Condition? Condition, IReadOnlyList<Node> Body); + +/// <summary><c>.if</c> ... <c>.end</c>: the first branch whose condition holds is taken.</summary> +/// <param name="At">The <c>.if</c>.</param> +/// <param name="Branches">Its branches, in order.</param> +public sealed record IfNode(Token At, IReadOnlyList<Branch> Branches) : Node(At) +{ + /// <summary>Whether any branch's condition names <c>target_system</c>.</summary> + public bool OnTarget => Branches.Any(branch => branch.Condition?.UsesTarget == true); +} + +/// <summary>A text file read: what it holds and whether it said <c>.pragma once</c>.</summary> +/// <param name="Nodes">Its parts, in order.</param> +/// <param name="Once">Whether it starts with <c>.pragma once</c>.</param> +public sealed record ConfigurationDocument(IReadOnlyList<Node> Nodes, bool Once); + +/// <summary> +/// The parser of <c>tazel_options.txt</c>, <c>tazel_custom.txt</c> and <c>tazel_envs.txt</c>: it puts the tokens of +/// <see cref="CustomLexer"/> into a tree of entries and directives. It reads every branch of every <c>.if</c>, so a +/// mistake in a branch not taken is found too, and it opens no file and runs nothing. +/// </summary> +public static class ConfigurationParser +{ + /// <summary>The deepest <c>.if</c> may nest, and the deepest includes may go.</summary> + public const int MaxDepth = 64; + + private sealed class Frame(Token at) + { + public Token At { get; } = at; + + public List<Branch> Branches { get; } = []; + + public Token BranchAt { get; set; } = at; + + public Condition? Condition { get; set; } + + public List<Node> Body { get; set; } = []; + + public bool SawElse { get; set; } + } + + /// <summary>The tree of <paramref name="tokens"/>, read from <paramref name="text"/> of <paramref name="file"/>.</summary> + public static ConfigurationDocument Parse(IReadOnlyList<Token> tokens, string file, string text) + { + ArgumentNullException.ThrowIfNull(tokens); + var root = new List<Node>(); + var frames = new Stack<Frame>(); + var pending = new List<Token>(); + var once = false; + List<Node> Current() => frames.Count == 0 ? root : frames.Peek().Body; + void Flush() + { + if (pending.Count > 0) + { + Current().Add(new TokensNode(pending.ToList())); + pending.Clear(); + } + } + + CustomCommandsException Fail(string code, Token at, string message, string help, string joke) => + new(Diagnostic.AtToken(code, text, file, at with { Text = "." + at.Text }, message, "this directive", help, joke)); + + for (var i = 0; i < tokens.Count; i++) + { + var token = tokens[i]; + if (token.Kind != TokenKind.Directive) + { + pending.Add(token); + continue; + } + + Flush(); + var argument = token.Argument ?? ""; + if (argument.EndsWith(';')) + { + throw Fail(ErrorCodes.DirectiveUnknown, token, $".{token.Text} takes no ';'", "leave the ';' out", + "Directives are terse. They do not even say goodbye with a ';'."); + } + + switch (token.Text) + { + case "include" or "import": + var (path, global) = IncludePath(argument) ?? throw Fail(ErrorCodes.IncludePathRefused, token, + $".{token.Text} needs one path, in quotes or in angle brackets, not '{argument}'", + $"write .{token.Text} \"file\" for a file beside this one, or .{token.Text} <file> for one of TAZEL_HOME's Include directory", + "Tazel looked for a path and found an opinion instead."); + Current().Add(new IncludeNode(token, path, global, token.Text == "import")); + break; + case "pragma": + if (argument != "once") + { + throw Fail(ErrorCodes.DirectiveUnknown, token, $"'.pragma {argument}' is not a pragma Tazel knows", + ".pragma once is the only pragma", "Tazel has exactly one pragma, and it is used once."); + } + + if (i != 0) + { + throw Fail(ErrorCodes.DirectiveUnknown, token, ".pragma once must come first in its file", + "move it to the top, above everything but comments", "Once is a word that only works at the start."); + } + + once = true; + break; + case "if": + if (frames.Count >= MaxDepth) + { + throw Fail(ErrorCodes.ConditionalUnbalanced, token, $".if blocks nest more than {MaxDepth} deep", + "fold the conditions together with && and ||", "Somewhere, deep in the ifs, a condition got lost."); + } + + frames.Push(new Frame(token) { Condition = Condition(token, file, text) }); + break; + case "elif" or "else": + var frame = frames.Count > 0 ? frames.Peek() : throw Fail(ErrorCodes.ConditionalUnbalanced, token, + $".{token.Text} without an .if", "open the block with .if", "An answer, and nobody asked."); + if (frame.SawElse) + { + throw Fail(ErrorCodes.ConditionalUnbalanced, token, $".{token.Text} after .else", + ".else is the last branch of its .if", "After else, there is nothing else."); + } + + if (token.Text == "else" && argument.Length > 0) + { + throw Fail(ErrorCodes.ConditionalUnbalanced, token, ".else takes no condition", + "write .elif and the condition, or .else alone", "Else is for everything that is left; it does not choose."); + } + + frame.Branches.Add(new Branch(frame.BranchAt, frame.Condition, frame.Body)); + frame.BranchAt = token; + frame.Condition = token.Text == "elif" ? Condition(token, file, text) : null; + frame.Body = []; + frame.SawElse = token.Text == "else"; + break; + case "end": + var closing = frames.Count > 0 ? frames.Pop() : throw Fail(ErrorCodes.ConditionalUnbalanced, token, + ".end without an .if", "remove it, or open the block with .if", "Tazel found an ending without a story."); + if (argument.Length > 0) + { + throw Fail(ErrorCodes.ConditionalUnbalanced, token, ".end takes nothing after it", "write .end alone", + "The end is the end. Nothing comes after it on the line."); + } + + closing.Branches.Add(new Branch(closing.BranchAt, closing.Condition, closing.Body)); + Current().Add(new IfNode(closing.At, closing.Branches)); + break; + default: + var near = Cli.Suggestions.Nearest(token.Text, ["include", "import", "pragma", "if", "elif", "else", "end"]); + throw Fail(ErrorCodes.DirectiveUnknown, token, $".{token.Text} is not a directive", + near is null ? "the directives are .include, .import, .pragma once, .if, .elif, .else and .end; a name that starts with a dot goes in quotes" + : $"did you mean .{near}?", + "Tazel only answers to the directives it was introduced to."); + } + } + + Flush(); + if (frames.Count > 0) + { + throw Fail(ErrorCodes.ConditionalUnbalanced, frames.Peek().At, ".if without its .end", "close the block with .end", + "This .if is still waiting for the end of the story."); + } + + return new ConfigurationDocument(root, once); + } + + // "file", 'file' or `file`, relative to the file that names it; <file>, below the Include directory. + private static (string Path, bool Global)? IncludePath(string argument) + { + if (argument.Length < 3) + { + return null; + } + + var (first, last) = (argument[0], argument[^1]); + var inner = argument[1..^1]; + if (inner.Length == 0 || inner.IndexOfAny(['"', '\'', '`', '<', '>']) >= 0) + { + return null; + } + + return first switch + { + '"' or '\'' or '`' when last == first => (inner, false), + '<' when last == '>' => (inner, true), + _ => null, + }; + } + + private static Condition Condition(Token token, string file, string text) + { + try + { + var condition = new ConditionReader(token.Argument ?? "").Read(); + if (condition.Type != ConditionType.Boolean) + { + throw new ConditionException("the condition is a string, not true or false; compare it with == or !="); + } + + return condition; + } + catch (ConditionException problem) + { + throw new CustomCommandsException(Diagnostic.AtToken(ErrorCodes.ConditionInvalid, text, file, + token with { Text = "." + token.Text }, problem.Message, "in this condition", + "conditions take true, false, strings, host_system.*, target_system.*, defined(\"NAME\"), env(\"NAME\"), == != ! && || and ( )", + "Tazel reads conditions. It does not guess them.")); + } + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs new file mode 100644 index 0000000..aa20c1d --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Configuration/ConfigurationResolver.cs @@ -0,0 +1,359 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Custom.Lexer; +using Progmasoft.Tazel.Output; + +namespace Progmasoft.Tazel.Dsl.Configuration; + +/// <summary>The kind of a text file, which names its Include directory: Options, Custom or Envs.</summary> +public enum ConfigurationFamily +{ + /// <summary><c>tazel_options.txt</c>.</summary> + Options, + + /// <summary><c>tazel_custom.txt</c>.</summary> + Custom, + + /// <summary><c>tazel_envs.txt</c>.</summary> + Envs, +} + +/// <summary> +/// What the conditions of a configuration see: this machine, the platform once it is chosen, and one snapshot of the +/// environment for every file and phase of a command. +/// </summary> +/// <param name="Host">This machine.</param> +/// <param name="Target">The platform being built for; null while it is chosen.</param> +/// <param name="Environment">The environment variables.</param> +public sealed record ConfigurationContext(SystemFacts Host, SystemFacts? Target, IReadOnlyDictionary<string, string> Environment) +{ + /// <summary>This machine and the environment of this process, with no platform chosen yet.</summary> + public static ConfigurationContext ForThisMachine() + { + var environment = new Dictionary<string, string>(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + foreach (DictionaryEntry entry in System.Environment.GetEnvironmentVariables()) + { + environment[(string)entry.Key] = entry.Value as string ?? ""; + } + + return new ConfigurationContext(SystemFacts.Of(Driver.Host.Platform), null, environment); + } + + /// <summary>This context with this machine as the platform built for.</summary> + public ConfigurationContext ForItself() => this with { Target = Host }; +} + +/// <summary> +/// The tree-walking interpreter of the text files: from a file's tree it gives the tokens of the entries its taken +/// branches hold, with those of the files it includes in their places, each token naming the file it comes from. +/// </summary> +public static class ConfigurationResolver +{ + /// <summary>The most files one configuration reads.</summary> + public const int MaxFiles = 4096; + + /// <summary>The most tokens one configuration holds.</summary> + public const int MaxTokens = 1_000_000; + + /// <summary> + /// The tokens of <paramref name="text"/>, the file at <paramref name="path"/> that messages call + /// <paramref name="shown"/>, with its directives resolved for <paramref name="context"/>. With no target in the context, a branch that depends on <c>target_system</c> and + /// what follows it in its <c>.if</c> are left out, so only what holds on every platform chooses the platform. A + /// <c>platform</c> entry in such a branch is an error in either case. + /// </summary> + public static IReadOnlyList<Token> Resolve( + string path, string shown, string text, ConfigurationFamily family, ConfigurationContext context) + { + ArgumentNullException.ThrowIfNull(context); + return new Walk(family, context).Root(path, shown, text); + } + + /// <summary>The file a path of a file of <paramref name="family"/> names, checked against its root.</summary> + internal static string IncludeRoot(ConfigurationFamily family) => + Path.Combine(TazelHome.Directory(), "Include", family.ToString()); + + private sealed class Walk(ConfigurationFamily family, ConfigurationContext context) + { + private readonly List<Token> _output = []; + private readonly HashSet<string> _loaded = new(StringComparer.Ordinal); + private readonly HashSet<string> _once = new(StringComparer.Ordinal); + private readonly List<(string Canonical, string Shown)> _chain = []; + private int _files; + + public IReadOnlyList<Token> Root(string path, string shown, string text) + { + var canonical = Canonical(Path.GetFullPath(path)); + Read(canonical, shown, text, origin: null, onTarget: false); + return _output; + } + + private void Read(string canonical, string shown, string text, Source? origin, bool onTarget) + { + if (++_files > MaxFiles) + { + throw Failure(ErrorCodes.IncludeTooDeep, null, $"this configuration reads more than {MaxFiles} files", Chain()); + } + + var document = ConfigurationParser.Parse(new CustomLexer(text, shown).Tokens(), shown, text); + _loaded.Add(canonical); + if (document.Once) + { + _once.Add(canonical); + } + + _chain.Add((canonical, shown)); + var first = _output.Count; + Nodes(document.Nodes, Path.GetDirectoryName(canonical)!, shown, text, origin, onTarget); + _chain.RemoveAt(_chain.Count - 1); + + // The last entry of a file may leave out its ';': it is put back, so the next file starts afresh. + if (_output.Count > first && _output[^1].Kind != TokenKind.Semicolon) + { + var last = _output[^1]; + _output.Add(new Token(TokenKind.Semicolon, ";", last.Line, last.Column + last.Text.Length, Origin: last.Origin)); + } + } + + private void Nodes(IReadOnlyList<Node> nodes, string directory, string shown, string text, Source? origin, bool onTarget) + { + foreach (var node in nodes) + { + switch (node) + { + case TokensNode tokens: + if (onTarget) + { + NoPlatform(tokens.Tokens, shown, text, origin); + } + + if (_output.Count + tokens.Tokens.Count > MaxTokens) + { + throw Failure(ErrorCodes.IncludeTooDeep, null, $"this configuration holds more than {MaxTokens} tokens", Chain()); + } + + _output.AddRange(origin is null ? tokens.Tokens : tokens.Tokens.Select(token => token with { Origin = origin })); + break; + case IncludeNode include: + Include(include, directory, shown, text, origin, onTarget); + break; + case IfNode chain: + If(chain, directory, shown, text, origin, onTarget); + break; + } + } + } + + private void If(IfNode chain, string directory, string shown, string text, Source? origin, bool onTarget) + { + var dependent = onTarget || chain.OnTarget; + if (chain.OnTarget) + { + // Every branch, taken or not, is looked at: a platform here would choose the platform from itself. + foreach (var branch in chain.Branches) + { + foreach (var tokens in Flat(branch.Body)) + { + NoPlatform(tokens.Tokens, shown, text, origin); + } + } + } + + foreach (var branch in chain.Branches) + { + var holds = branch.Condition is null ? true + : ConditionEvaluator.Evaluate(branch.Condition, context.Host, context.Target, context.Environment); + if (holds is null) + { + // While the platform is chosen, a branch on target_system decides nothing, and nor do those after it. + return; + } + + if (holds == true) + { + Nodes(branch.Body, directory, shown, text, origin, dependent); + return; + } + } + } + + private static IEnumerable<TokensNode> Flat(IReadOnlyList<Node> nodes) => nodes.SelectMany(node => node switch + { + TokensNode tokens => [tokens], + IfNode chain => chain.Branches.SelectMany(branch => Flat(branch.Body)), + _ => [], + }); + + private void NoPlatform(IReadOnlyList<Token> tokens, string shown, string text, Source? origin) + { + if (family != ConfigurationFamily.Options) + { + return; + } + + for (var i = 0; i + 1 < tokens.Count; i++) + { + var token = tokens[i]; + var startsEntry = i == 0 || tokens[i - 1].Kind == TokenKind.Semicolon; + if (startsEntry && token is { Kind: TokenKind.Name, Text: "platform" } && tokens[i + 1].Kind == TokenKind.Colon) + { + var at = origin is null ? token : token with { Origin = origin }; + throw new CustomCommandsException(Diagnostic.AtToken(ErrorCodes.PlatformDependsOnTarget, text, shown, at, + "the platform is chosen inside a condition on target_system, which depends on the platform", + "this platform", "choose the platform outside such a condition, or with a condition on host_system", + "Tazel cannot pick the platform by asking which platform it picked.")); + } + } + } + + private void Include(IncludeNode include, string directory, string shown, string text, Source? origin, bool onTarget) + { + var at = origin is null ? include.At : include.At with { Origin = origin }; + var target = Target(include, directory, at, shown, text); + var canonical = Canonical(target); + if (_once.Contains(canonical) || (include.Import && _loaded.Contains(canonical))) + { + return; + } + + if (_chain.Any(entry => entry.Canonical == canonical)) + { + throw Failure(ErrorCodes.IncludeTooDeep, (at, shown, text), $"{include.Path} includes itself", + Chain() + $" -> {include.Path}"); + } + + if (_chain.Count >= ConfigurationParser.MaxDepth) + { + throw Failure(ErrorCodes.IncludeTooDeep, (at, shown, text), $"includes nest more than {ConfigurationParser.MaxDepth} deep", Chain()); + } + + string included; + try + { + included = File.ReadAllText(canonical); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + throw Failure(ErrorCodes.IncludeMissing, (at, shown, text), $"{include.Path} cannot be read: {error.Message}", null); + } + + if (include.Import) + { + _once.Add(canonical); + } + + var name = Shown(canonical); + Read(canonical, name, included, new Source(name, included), onTarget); + } + + // The file an include names: beside the file that names it, or below the family's Include directory. + private string Target(IncludeNode include, string directory, Token at, string shown, string text) + { + var path = include.Path; + CustomCommandsException Refused(string why) => Failure(ErrorCodes.IncludePathRefused, (at, shown, text), + $"'{path}' {why}", null); + if (path.IndexOfAny(['*', '?', '[', ']']) >= 0) + { + throw Refused("has a wildcard; name one file"); + } + + if (path.Contains("://", StringComparison.Ordinal)) + { + throw Refused("is a URL; Tazel includes files of this machine only"); + } + + if (Path.IsPathRooted(path) || (path.Length >= 2 && path[1] == ':')) + { + throw Refused(include.Global ? "is absolute; a path in <> is below the Include directory" : "is absolute; a path in quotes is relative to this file"); + } + + if (!include.Global) + { + var full = Path.GetFullPath(Path.Combine(directory, path)); + if (!File.Exists(full)) + { + throw Failure(ErrorCodes.IncludeMissing, (at, shown, text), $"{path} is not a file beside {shown}", null); + } + + return full; + } + + if (path.Replace('\\', '/').Split('/').Any(part => part is ".." or ".")) + { + throw Refused("has . or .. parts; a path in <> stays below the Include directory"); + } + + string root; + try + { + root = Canonical(IncludeRoot(family)); + } + catch (ConfigurationHomeException error) + { + throw Failure(ErrorCodes.IncludePathRefused, (at, shown, text), error.Message, null); + } + + var file = Path.GetFullPath(Path.Combine(root, path)); + if (!File.Exists(file)) + { + throw Failure(ErrorCodes.IncludeMissing, (at, shown, text), $"<{path}> is not a file of {root}", null); + } + + var real = Canonical(file); + if (!real.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + { + throw Refused($"leaves {root} through a link"); + } + + return real; + } + + private string Chain() => string.Join(" -> ", _chain.Select(entry => entry.Shown)); + + private static string Shown(string canonical) + { + var relative = Path.GetRelativePath(System.Environment.CurrentDirectory, canonical); + return relative.StartsWith("..", StringComparison.Ordinal) ? canonical : relative.Replace('\\', '/'); + } + + private static CustomCommandsException Failure(string code, (Token At, string File, string Text)? where, string message, string? chain) + { + var full = chain is null ? message : $"{message} ({chain})"; + if (where is not { } place) + { + return new CustomCommandsException(full); + } + + return new CustomCommandsException(Diagnostic.AtToken(code, place.Text, place.File, place.At with { Text = "." + place.At.Text }, + full, "this directive", code == ErrorCodes.IncludeTooDeep ? "say .pragma once at the top of the file, or .import it" : null, + "Tazel followed the includes all the way down, and then some.")); + } + } + + /// <summary> + /// <paramref name="path"/> with every link of it followed, so two names of one file are one file and a link + /// cannot lead out of a directory. + /// </summary> + internal static string Canonical(string path) + { + var full = Path.GetFullPath(path); + var root = Path.GetPathRoot(full)!; + var current = root; + foreach (var part in full[root.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + var next = Path.Combine(current, part); + FileSystemInfo info = Directory.Exists(next) ? new DirectoryInfo(next) : new FileInfo(next); + current = info.LinkTarget is not null && info.ResolveLinkTarget(returnFinalTarget: true) is { } resolved + ? Path.GetFullPath(resolved.FullName) + : next; + } + + return current; + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Configuration/TazelHome.cs b/src/Progmasoft.Tazel/Dsl/Configuration/TazelHome.cs new file mode 100644 index 0000000..4db91b5 --- /dev/null +++ b/src/Progmasoft.Tazel/Dsl/Configuration/TazelHome.cs @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.IO; + +namespace Progmasoft.Tazel.Dsl.Configuration; + +/// <summary>A <c>TAZEL_HOME</c> Tazel cannot use.</summary> +public sealed class ConfigurationHomeException : Exception +{ + /// <summary>What is wrong with it.</summary> + public ConfigurationHomeException(string message) + : base(message) + { + } + + /// <summary>Nothing to say.</summary> + public ConfigurationHomeException() + { + } + + /// <summary>What is wrong, and why.</summary> + public ConfigurationHomeException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// <summary> +/// The directory of Tazel's own files for this user: <c>TAZEL_HOME</c> when it is set, else <c>$HOME/.Tazel</c> on +/// Linux, macOS and the BSDs and <c>%APPDATA%\Tazel</c> on Windows, whatever XDG says. A <c>TAZEL_HOME</c> that is set +/// but empty or relative is an error, never a reason to use another directory. Nothing here creates it. +/// </summary> +public static class TazelHome +{ + /// <summary>The name of the variable that sets it.</summary> + public const string Variable = "TAZEL_HOME"; + + /// <summary>The directory, resolved from the environment as it is now.</summary> + public static string Directory() + { + if (System.Environment.GetEnvironmentVariable(Variable) is { } explicitHome) + { + if (explicitHome.Length == 0 || !Path.IsPathFullyQualified(explicitHome)) + { + throw new ConfigurationHomeException( + $"{Variable} is '{explicitHome}', which is not an absolute path; set it to one, or unset it for the default"); + } + + return Path.GetFullPath(explicitHome); + } + + if (OperatingSystem.IsWindows()) + { + var appData = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData); + return appData.Length > 0 ? Path.Combine(appData, "Tazel") + : throw new ConfigurationHomeException("%APPDATA% is not set; set TAZEL_HOME"); + } + + var home = System.Environment.GetEnvironmentVariable("HOME"); + return home is { Length: > 0 } && Path.IsPathFullyQualified(home) ? Path.Combine(home, ".Tazel") + : throw new ConfigurationHomeException("HOME is not an absolute path; set TAZEL_HOME"); + } +} diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs b/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs index c4f1271..d467765 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Diagnostic.cs @@ -46,6 +46,7 @@ public sealed record Diagnostic( string code, string text, string file, Token token, string message, string label, string? help, string? joke) { ArgumentNullException.ThrowIfNull(token); + (text, file) = token.Origin is { } origin ? (origin.Text, origin.File) : (text, file); var width = token.Kind switch { TokenKind.String => token.Text.Length + 2, @@ -60,6 +61,7 @@ public sealed record Diagnostic( string code, string text, string file, Token token, string message, string label, string? help, string? joke) { ArgumentNullException.ThrowIfNull(token); + (text, file) = token.Origin is { } origin ? (origin.Text, origin.File) : (text, file); 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); diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs index 7967986..afed64b 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Lexer/CustomLexer.cs @@ -30,18 +30,38 @@ public enum TokenKind /// <summary><c>)</c>.</summary> Close, + + /// <summary><c>[</c>.</summary> + BracketOpen, + + /// <summary><c>]</c>.</summary> + BracketClose, + + /// <summary> + /// A line that starts with <c>.</c> and a letter: <c>.include</c>, <c>.import</c>, <c>.pragma</c>, <c>.if</c>, + /// <c>.elif</c>, <c>.else</c>, <c>.end</c>. Its text is the word after the dot, its argument the rest of the line. + /// </summary> + Directive, } +/// <summary>The file a token was read from and its text, for a token of a file another one includes.</summary> +/// <param name="File">The file, as messages show it.</param> +/// <param name="Text">All of its text.</param> +public sealed record Source(string File, string Text); + /// <summary>One word of the file, with where it starts.</summary> /// <param name="Kind">What it is.</param> /// <param name="Text">Its text; for a string, what stands between the quotes.</param> /// <param name="Line">Its line, from 1.</param> /// <param name="Column">Its column, from 1.</param> -public sealed record Token(TokenKind Kind, string Text, int Line, int Column); +/// <param name="Argument">For a directive, the rest of its line, trimmed; null otherwise.</param> +/// <param name="Origin">The file the token comes from when it is not the one being read, else null.</param> +public sealed record Token(TokenKind Kind, string Text, int Line, int Column, string? Argument = null, Source? Origin = null); /// <summary> -/// Splits the text of <c>tazel_custom.txt</c> or <c>tazel_options.txt</c>: comments go, and whitespace of any kind -/// only separates. <c>#</c> starts a comment to the end of the line, <c><# ... #></c> a comment of any length. +/// Splits the text of <c>tazel_options.txt</c>, <c>tazel_custom.txt</c> or <c>tazel_envs.txt</c>: comments go, and +/// whitespace of any kind only separates. <c>#</c> starts a comment to the end of the line, <c><# ... #></c> a +/// comment of any length. A line whose first character, after spaces, is <c>.</c> and a letter is a directive. /// </summary> /// <param name="text">The text.</param> /// <param name="file">The file, for messages.</param> @@ -51,6 +71,9 @@ public sealed class CustomLexer(string text, string file) private int _line = 1; private int _column = 1; + // Whether only whitespace stands between the start of the line and here: a directive starts a line. + private bool _lineStart = true; + /// <summary>Every token of the text, in order; a character that starts no token is an error.</summary> public IReadOnlyList<Token> Tokens() { @@ -62,6 +85,10 @@ public sealed class CustomLexer(string text, string file) { Advance(); } + else if (letter == '.' && _lineStart && _position + 1 < text.Length && char.IsAsciiLetter(text[_position + 1])) + { + tokens.Add(Directive()); + } else if (At("<#")) { SkipBlockComment(); @@ -93,8 +120,10 @@ public sealed class CustomLexer(string text, string file) ';' => TokenKind.Semicolon, '(' => TokenKind.Open, ')' => TokenKind.Close, + '[' => TokenKind.BracketOpen, + ']' => TokenKind.BracketClose, _ => 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", + "this file knows names, strings in ' \" or `, ( ) [ ] : ; <N> and directives such as .include; 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)); @@ -120,15 +149,59 @@ public sealed class CustomLexer(string text, string file) { _line++; _column = 1; + _lineStart = true; } else { _column++; + _lineStart &= char.IsWhiteSpace(letter); } return letter; } + // .word and the rest of the line, up to a # comment; a directive takes no other token after it. + private Token Directive() + { + var (line, column) = (_line, _column); + Advance(); + var begin = _position; + while (_position < text.Length && char.IsAsciiLetter(text[_position])) + { + Advance(); + } + + var word = text[begin.._position]; + var rest = _position; + while (_position < text.Length && text[_position] != '\n') + { + Advance(); + } + + var argument = text[rest.._position]; + // A # outside a string ends the line's text, as everywhere in these files. + var inside = '\0'; + for (var i = 0; i < argument.Length; i++) + { + var c = argument[i]; + if (inside != '\0') + { + inside = c == inside ? '\0' : inside; + } + else if (c is '"' or '\'' or '`') + { + inside = c; + } + else if (c == '#') + { + argument = argument[..i]; + break; + } + } + + return new Token(TokenKind.Directive, word, line, column, argument.Trim()); + } + private void SkipBlockComment() { var (line, column) = (_line, _column); diff --git a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs index a71c92d..1377695 100644 --- a/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs +++ b/src/Progmasoft.Tazel/Dsl/Custom/Parser/CustomParser.cs @@ -15,9 +15,14 @@ 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) => Parse(text, CustomCommandFiles.FileName); - /// <summary>The commands of <paramref name="text"/>; <paramref name="file"/> names it in messages.</summary> - public static IReadOnlyList<CustomCommand> Parse(string text, string file) => - new Reader(new CustomLexer(text, file).Tokens(), file, text).Commands(); + /// <summary> + /// The commands of <paramref name="text"/>; <paramref name="file"/> names it in messages. Its directives are + /// resolved for <paramref name="context"/> (this machine, built for itself, by default), and a quoted include is + /// found beside <paramref name="path"/> (<paramref name="file"/> from the working directory by default). + /// </summary> + public static IReadOnlyList<CustomCommand> Parse(string text, string file, string? path = null, Configuration.ConfigurationContext? context = null) => + new Reader(Configuration.ConfigurationResolver.Resolve(path ?? file, file, text, Configuration.ConfigurationFamily.Custom, + context ?? Configuration.ConfigurationContext.ForThisMachine().ForItself()), file, text).Commands(); private sealed class Reader(IReadOnlyList<Token> tokens, string file, string text) { diff --git a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs index 5f9f7ad..7b7fb2e 100644 --- a/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs +++ b/src/Progmasoft.Tazel/Dsl/Envs/TazelEnvs.cs @@ -48,11 +48,17 @@ public static class TazelEnvsFile /// <summary>The entries of <paramref name="text"/>, named tazel_envs.txt in messages.</summary> public static IReadOnlyList<EnvEntry> Parse(string text) => Parse(text, FileName); - /// <summary>The entries of <paramref name="text"/>; <paramref name="file"/> names it in messages.</summary> - public static IReadOnlyList<EnvEntry> Parse(string text, string file) + /// <summary> + /// The entries of <paramref name="text"/>; <paramref name="file"/> names it in messages. Its directives are + /// resolved for <paramref name="context"/> (this machine, built for itself, by default), and a quoted include is + /// found beside <paramref name="path"/>. + /// </summary> + public static IReadOnlyList<EnvEntry> Parse(string text, string file, string? path = null, Configuration.ConfigurationContext? context = null) { ArgumentNullException.ThrowIfNull(text); - return new Reader(new CustomLexer(text, file).Tokens(), text, file).Entries(); + var tokens = Configuration.ConfigurationResolver.Resolve(path ?? file, file, text, Configuration.ConfigurationFamily.Envs, + context ?? Configuration.ConfigurationContext.ForThisMachine().ForItself()); + return new Reader(tokens, text, file).Entries(); } private sealed class Reader(IReadOnlyList<Token> tokens, string text, string file) @@ -213,11 +219,21 @@ internal sealed class ModuleEnvironment : IEnvironmentValues _entries = entries.ToDictionary(entry => entry.Name, StringComparer.Ordinal); } - /// <summary>The values of the module at <paramref name="root"/>, or null when it has no <c>tazel_envs.txt</c>.</summary> - public static ModuleEnvironment? Load(string root, string shown) + /// <summary> + /// The values of the module at <paramref name="root"/>, or null when it has no <c>tazel_envs.txt</c>; its + /// conditions see <paramref name="target"/> as the platform built for (this machine's when null). + /// </summary> + public static ModuleEnvironment? Load(string root, string shown, Common.Platform? target = null) { var file = Path.Combine(root, TazelEnvsFile.FileName); - return File.Exists(file) ? new ModuleEnvironment(root, shown, TazelEnvsFile.Parse(File.ReadAllText(file), shown)) : null; + if (!File.Exists(file)) + { + return null; + } + + var context = Configuration.ConfigurationContext.ForThisMachine(); + context = context with { Target = Configuration.SystemFacts.Of(target ?? Driver.Host.Platform) }; + return new ModuleEnvironment(root, shown, TazelEnvsFile.Parse(File.ReadAllText(file), shown, file, context)); } public string? Get(string name) diff --git a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs index 5db7616..05be515 100644 --- a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs +++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs @@ -90,13 +90,26 @@ public static class TazelOptionsFile /// </summary> public static TazelOptions Parse(string text) => Parse(text, TazelOptions.FileName); - /// <summary>The options of <paramref name="text"/>; <paramref name="file"/> names it in messages.</summary> - public static TazelOptions Parse(string text, string file) + /// <summary> + /// The options of <paramref name="text"/>; <paramref name="file"/> names it in messages and a quoted include is + /// found beside <paramref name="path"/>. It is read twice: first without what depends on <c>target_system</c>, which + /// chooses the platform (<paramref name="requested"/>, else the file's, else this machine's), then for that + /// platform. A platform chosen inside a condition on <c>target_system</c> is an error. + /// </summary> + public static TazelOptions Parse(string text, string file, string? path = null, Platform? requested = null) + { + var machine = Configuration.ConfigurationContext.ForThisMachine(); + var chosen = Read(text, file, path, machine); + var platform = requested ?? chosen.Platform ?? Driver.Host.Platform; + return Read(text, file, path, machine with { Target = Configuration.SystemFacts.Of(platform) }); + } + + private static TazelOptions Read(string text, string file, string? path, Configuration.ConfigurationContext context) { IReadOnlyList<Token> tokens; try { - tokens = new CustomLexer(text, file).Tokens(); + tokens = Configuration.ConfigurationResolver.Resolve(path ?? file, file, text, Configuration.ConfigurationFamily.Options, context); } catch (CustomCommandsException error) { @@ -150,9 +163,9 @@ public static class TazelOptionsFile /// for in any file above stays asked for, so a project cannot turn off what a directory around it requires. /// Default options, and no file, without any. /// </summary> - public static (TazelOptions Options, string? SandboxFile) Effective(string directory) + public static (TazelOptions Options, string? SandboxFile) Effective(string directory, Platform? requested = null) { - var files = Find(directory).Select(file => (File: file, Options: Read(file))).ToList(); + var files = Find(directory).Select(file => (File: file, Options: Read(file, requested))).ToList(); if (files.Count == 0) { return (new TazelOptions(), null); @@ -162,7 +175,7 @@ public static class TazelOptionsFile return (files[0].Options with { SandboxingWithMicroVM = asking is not null }, asking); } - private static TazelOptions Read(string file) + private static TazelOptions Read(string file, Platform? requested) { string text; try @@ -178,7 +191,7 @@ public static class TazelOptionsFile throw new TazelOptionsException($"{file} could not be read: {problem.Message}", problem); } - return Parse(text, file); + return Parse(text, file, file, requested); } private sealed class Reader(IReadOnlyList<Token> tokens, string file, string text) diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index cb5268d..82bddc8 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -29,6 +29,13 @@ internal static partial class ErrorCodes public const string StringNotClosed = "E0003"; public const string PlaceholderNotClosed = "E0004"; public const string PlaceholderOutOfRange = "E0005"; + public const string DirectiveUnknown = "E0006"; + public const string ConditionalUnbalanced = "E0007"; + public const string ConditionInvalid = "E0008"; + public const string IncludePathRefused = "E0009"; + public const string IncludeMissing = "E0010"; + public const string IncludeTooDeep = "E0011"; + public const string PlatformDependsOnTarget = "E0012"; public const string CommandLine = "E0100"; @@ -107,6 +114,42 @@ internal static partial class ErrorCodes "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(DirectiveUnknown, "a directive Tazel does not know, or one written wrongly", + "A line that starts with a dot and a letter is a directive: .include, .import, .pragma once, .if, .elif, .else " + + "or .end. Directives take no ';'. .pragma once stands first in its file, before anything but comments, and once " + + "is the only pragma. A name that starts with a dot at the start of a line is read as a directive, so it goes in " + + "quotes.", + ".pragma once;", ".pragma once", Lexer), + new(ConditionalUnbalanced, "an .if without its .end, or a branch out of place", + "An .if opens a block that .end closes; between them come any .elif and at most one .else, last. An .elif, .else " + + "or .end with no .if open, a second .else, an .elif after .else, an .if left open at the end of the file, and " + + "blocks nested deeper than 64 are errors. .else and .end take nothing after them.", + ".if host_system.os == \"linux\"\nmicrovm-cpus: 4;", ".if host_system.os == \"linux\"\nmicrovm-cpus: 4;\n.end", Lexer), + new(ConditionInvalid, "a condition Tazel cannot read", + "A condition of .if and .elif is made of true and false, strings in quotes, host_system.os, .arch, .abi and " + + ".platform, the same four of target_system, defined(\"NAME\") and env(\"NAME\") for the environment, ==, !=, !, && and " + + "|| with the usual precedence, and parentheses. == and != compare two strings or two booleans; !, && and || take " + + "booleans, and the whole condition is one. Any other name or operator is an error; a condition runs nothing.", + ".if host_system.os = \"linux\"", ".if host_system.os == \"linux\"", Lexer), + new(IncludePathRefused, "an include or import path Tazel does not take", + "A path in quotes is a file relative to the directory of the file that names it; one in angle brackets, " + + "<file>, is below the Include directory of TAZEL_HOME for the kind of file (Options, Custom or Envs) and may not " + + "leave it, not through .. or a link either. Paths are taken as written: no wildcards, no URLs, no environment " + + "variables, and a quoted path is not absolute.", + ".include \"https://example.com/build.options.txt\"", ".include \"config/build.options.txt\"", Lexer), + new(IncludeMissing, "a file to include that is not there or cannot be read", + "The file a .include or .import names must exist and be readable. Nothing is included from a branch of .if that " + + "is not taken, so only a file the configuration reaches has to exist.", null, null, Lexer), + new(IncludeTooDeep, "includes that go round, nest too deep or grow too large", + "A file that includes itself, directly or through others, is an error unless it says .pragma once or is " + + "imported: then it is read once. Includes may nest 64 deep, and one configuration reads at most 4,096 files and " + + "1,000,000 tokens. The message shows the chain of includes.", null, null, Lexer), + new(PlatformDependsOnTarget, "a platform chosen by a condition on target_system", + "Tazel chooses the platform first, from the command line and the platform entries that do not depend on " + + "target_system, and then reads everything else for that platform. A platform set inside an .if or .elif on " + + "target_system, or in a file such a branch includes, would choose the platform from itself, so it is an error.", + ".if target_system.os == \"linux\"\nplatform: windows-x64;\n.end", ".if host_system.os == \"linux\"\nplatform: windows-x64;\n.end", + Options), new(CommandLine, "a command line Tazel cannot take", "The command, an option or a value is not one Tazel knows, or a command got arguments it does not take. Tazel " + "suggests the nearest spelling when there is one. tazel help lists the commands, and tazel help <command> --long " + diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs index 075a3e9..583db50 100644 --- a/src/Progmasoft.Tazel/Project/Workspace.cs +++ b/src/Progmasoft.Tazel/Project/Workspace.cs @@ -104,8 +104,8 @@ internal sealed class Workspace string directory, BuildContext build, Version tazelVersion, Action<string>? status = null) { var root = ModuleFiles.FindRoot(directory); - var main = await LoadModuleAsync(root, null, tazelVersion, root).ConfigureAwait(false); - var workspace = new Workspace(main); + var main = await LoadModuleAsync(root, null, tazelVersion, root, build.Platform).ConfigureAwait(false); + var workspace = new Workspace(main) { _target = build.Platform }; await workspace.LoadDependenciesAsync(main, tazelVersion).ConfigureAwait(false); await workspace.LoadPortalModulesAsync(tazelVersion, offline: false).ConfigureAwait(false); await workspace.LoadPackagesAsync(main, build, status ?? (_ => { })).ConfigureAwait(false); @@ -125,12 +125,16 @@ internal sealed class Workspace return LoadModuleAsync(root, null, tazelVersion, root); } - private static async Task<LoadedModule> LoadModuleAsync(string root, string? repository, Version tazelVersion, string mainRoot) + // The platform the modules are loaded for: what the conditions of their tazel_envs.txt see. + private Platform? _target; + + private static async Task<LoadedModule> LoadModuleAsync( + string root, string? repository, Version tazelVersion, string mainRoot, Platform? target = null) { var file = Path.Combine(root, ModuleFiles.ModuleFile); var shown = repository is null ? ModuleFiles.ModuleFile : $"@{repository}//{ModuleFiles.ModuleFile}"; var globals = new ModuleGlobals(); - var environment = EnvironmentOf(root, repository); + var environment = EnvironmentOf(root, repository, target); using (Dsl.Environment.EnvironmentValues.Enter(environment)) { await ScriptHost.RunAsync(await File.ReadAllTextAsync(file).ConfigureAwait(false), shown, globals, mainRoot) @@ -145,12 +149,12 @@ internal sealed class Workspace } /// <summary>The values of the module's tazel_envs.txt, or null when it has none.</summary> - private static Dsl.Envs.ModuleEnvironment? EnvironmentOf(string root, string? repository) + private static Dsl.Envs.ModuleEnvironment? EnvironmentOf(string root, string? repository, Platform? target) { var shown = repository is null ? Dsl.Envs.TazelEnvsFile.FileName : $"@{repository}//{Dsl.Envs.TazelEnvsFile.FileName}"; try { - return Dsl.Envs.ModuleEnvironment.Load(root, shown); + return Dsl.Envs.ModuleEnvironment.Load(root, shown, target); } catch (Dsl.Custom.CustomCommandsException error) { @@ -214,7 +218,7 @@ internal sealed class Workspace } var unpacked = LocalModules.Unpack(Main.Root, module.Root, local, place); - var loaded = await LoadModuleAsync(unpacked, local.Name, tazelVersion, Main.Root).ConfigureAwait(false); + var loaded = await LoadModuleAsync(unpacked, local.Name, tazelVersion, Main.Root, _target).ConfigureAwait(false); External[local.Name] = loaded; await LoadDependenciesAsync(loaded, tazelVersion).ConfigureAwait(false); } @@ -246,7 +250,7 @@ internal sealed class Workspace var root = await PortalDependencies.FetchAsync(Main.Root, module, offline ? null : client, System.Threading.CancellationToken.None).ConfigureAwait(false); - External[module.Repository] = await LoadModuleAsync(root, module.Repository, tazelVersion, Main.Root).ConfigureAwait(false); + External[module.Repository] = await LoadModuleAsync(root, module.Repository, tazelVersion, Main.Root, _target).ConfigureAwait(false); PortalModules.Add(module); } } diff --git a/tests/Progmasoft.Tazel.Tests/ConfigurationTests.cs b/tests/Progmasoft.Tazel.Tests/ConfigurationTests.cs new file mode 100644 index 0000000..b685102 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/ConfigurationTests.cs @@ -0,0 +1,303 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Progmasoft.Tazel.Dsl.Common; +using Progmasoft.Tazel.Dsl.Configuration; +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; + +public sealed class ConfigurationTests +{ + private static TazelOptions Options(TemporaryModule module, string text, Platform? requested = null) + { + var file = Path.Combine(module.Root, "tazel_options.txt"); + File.WriteAllText(file, text); + return TazelOptionsFile.Parse(text, "tazel_options.txt", file, requested); + } + + private static Diagnostic Problem(Action read) + { + var error = Assert.ThrowsAny<Exception>(read); + return error switch + { + TazelOptionsException { Diagnostic: { } d } => d, + CustomCommandsException { Diagnostic: { } d } => d, + _ => throw new Xunit.Sdk.XunitException($"no diagnostic: {error}"), + }; + } + + private static ConfigurationContext Context(Platform host, Platform? target, Dictionary<string, string>? environment = null) => + new(SystemFacts.Of(host), target is { } t ? SystemFacts.Of(t) : null, environment ?? []); + + [Fact] + public void IncludesFilesBesideEachFileThatNamesThem() + { + using var module = new TemporaryModule() + .Write("config/cpus.options.txt", ".include \"deeper/memory.options.txt\"\nmicrovm-cpus: 3") + .Write("config/deeper/memory.options.txt", "microvm-memory: 2048"); + var options = Options(module, ".include \"config/cpus.options.txt\"\nmicrovm-network: true;"); + Assert.Equal(3, options.MicroVMCpus.Amount); + Assert.Equal(2048, options.MicroVMMemory.Amount); + Assert.True(options.MicroVMNetwork); + } + + [Fact] + public void ImportAndPragmaOnceReadAFileOnce() + { + using var module = new TemporaryModule() + .Write("a.options.txt", "microvm-cpus: 2") + .Write("b.options.txt", ".pragma once\nmicrovm-memory: 512"); + // Read twice, either would set an option twice. + var options = Options(module, ".import \"a.options.txt\"\n.import \"a.options.txt\"\n.include \"a.options.txt\"\n" + + ".include \"b.options.txt\"\n.include \"b.options.txt\"\n"); + Assert.Equal(2, options.MicroVMCpus.Amount); + Assert.Equal(512, options.MicroVMMemory.Amount); + using var twice = new TemporaryModule().Write("a.options.txt", "microvm-cpus: 2"); + Assert.Equal(ErrorCodes.OptionsTwice, Problem(() => Options(twice, ".include \"a.options.txt\"\n.include \"a.options.txt\"\n")).Code); + } + + [Fact] + public void AFileThatIncludesItselfIsAnErrorUnlessItIsOnce() + { + using var module = new TemporaryModule() + .Write("a.options.txt", ".include \"b.options.txt\"\nmicrovm-cpus: 2") + .Write("b.options.txt", ".include \"a.options.txt\"\n") + .Write("c.options.txt", ".pragma once\n.include \"c.options.txt\"\nmicrovm-cpus: 4"); + var cycle = Problem(() => Options(module, ".include \"a.options.txt\"\n")); + Assert.Equal(ErrorCodes.IncludeTooDeep, cycle.Code); + Assert.Contains("a.options.txt includes itself", cycle.Message, StringComparison.Ordinal); + Assert.Contains("tazel_options.txt -> ", cycle.Message, StringComparison.Ordinal); + Assert.Equal(4, Options(module, ".include \"c.options.txt\"\n").MicroVMCpus.Amount); + } + + [Fact] + public void IncludesNestAtMost64Deep() + { + using var module = new TemporaryModule(); + for (var i = 0; i < 70; i++) + { + module.Write($"n{i}.options.txt", $".include \"n{i + 1}.options.txt\"\n"); + } + + module.Write("n70.options.txt", "microvm-cpus: 1"); + var deep = Problem(() => Options(module, ".include \"n0.options.txt\"\n")); + Assert.Equal(ErrorCodes.IncludeTooDeep, deep.Code); + Assert.Contains("nest more than 64 deep", deep.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData(".include \"*.options.txt\"", "has a wildcard")] + [InlineData(".include \"https://example.com/x.options.txt\"", "is a URL")] + [InlineData(".include \"/etc/x.options.txt\"", "is absolute")] + [InlineData(".include \"missing.options.txt\"", "is not a file beside")] + [InlineData(".include missing.options.txt", "needs one path, in quotes or in angle brackets")] + [InlineData(".include <../x.options.txt>", "has . or .. parts")] + public void RefusesPathsItDoesNotTake(string directive, string message) + { + using var module = new TemporaryModule(); + var problem = Problem(() => Options(module, directive + "\n")); + Assert.Contains(message, problem.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData(".pragma once;", "takes no ';'")] + [InlineData("microvm-cpus: 1;\n.pragma once", "must come first")] + [InlineData(".pragma twice", "is not a pragma")] + [InlineData(".inclde \"x\"", ".inclde is not a directive")] + [InlineData(".elif true", ".elif without an .if")] + [InlineData(".end", ".end without an .if")] + [InlineData(".if true\n.else\n.else\n.end", ".else after .else")] + [InlineData(".if true\n.else\n.elif false\n.end", ".elif after .else")] + [InlineData(".if true\n.else false\n.end", ".else takes no condition")] + [InlineData(".if true\nmicrovm-cpus: 1;", ".if without its .end")] + [InlineData(".if host_system.os = \"linux\"\n.end", "'=' is not an operator of conditions; compare with ==")] + [InlineData(".if host_system.kernel == \"x\"\n.end", "is not a field")] + [InlineData(".if host_system.os\n.end", "is a string, not true or false")] + [InlineData(".if host_system.os == true\n.end", "compares a string with a boolean")] + [InlineData(".if hots_system.os == \"x\"\n.end", "did you mean host_system?")] + [InlineData(".if !host_system.os\n.end", "! takes true or false")] + public void SaysWhatIsWrongWithADirective(string text, string message) + { + using var module = new TemporaryModule(); + var problem = Problem(() => Options(module, text)); + Assert.Contains(message, problem.Message, StringComparison.Ordinal); + } + + [Fact] + public void AMisspeltDirectiveGetsTheNearest() + { + using var module = new TemporaryModule(); + Assert.Equal("did you mean .include?", Problem(() => Options(module, ".inclde \"x\"\n")).Help); + } + + [Fact] + public void ConditionsNest64DeepAtMost() + { + using var module = new TemporaryModule(); + var text = string.Concat(Enumerable.Repeat(".if true\n", 65)) + string.Concat(Enumerable.Repeat(".end\n", 65)); + Assert.Contains("nest more than 64 deep", Problem(() => Options(module, text)).Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData("true || false && false", true)] + [InlineData("(true || false) && false", false)] + [InlineData("!false && true", true)] + [InlineData("host_system.os == \"linux\" && host_system.arch == \"amd64\"", true)] + [InlineData("host_system.abi == \"gnu\" && host_system.platform == \"linux-amd64\"", true)] + [InlineData("target_system.os == \"windows\" && target_system.abi == \"msvc\"", true)] + [InlineData("defined(\"SET\") && env(\"SET\") == \"yes\" && !defined(\"UNSET\") && env(\"UNSET\") == \"\"", true)] + [InlineData("'single' == `back`", false)] + [InlineData("\"a\" != 'a'", false)] + public void EvaluatesConditions(string text, bool expected) + { + var condition = new ConditionReader(text).Read(); + var context = Context(Platform.LinuxAmd64, Platform.WindowsX64, new Dictionary<string, string> { ["SET"] = "yes" }); + Assert.Equal(expected, ConditionEvaluator.Evaluate(condition, context.Host, context.Target, context.Environment)); + } + + [Fact] + public void ABranchNotTakenOpensNoFileButIsRead() + { + using var module = new TemporaryModule(); + var options = Options(module, ".if false\n.include \"missing.options.txt\"\n.elif true\nmicrovm-cpus: 2;\n.else\nmicrovm-cpus: 3;\n.end\n"); + Assert.Equal(2, options.MicroVMCpus.Amount); + // Its syntax is checked all the same. + Assert.Equal(ErrorCodes.ConditionInvalid, Problem(() => Options(module, ".if false\n.elif nonsense\n.end\n")).Code); + } + + [Fact] + public void TheTargetIsChosenFirstThenTheRestIsReadForIt() + { + using var module = new TemporaryModule(); + const string Text = "platform: windows-x64;\n.if target_system.os == \"windows\"\n microvm-memory: 4096;\n.else\n" + + " microvm-memory: 2048;\n.end\n.if host_system.os == \"linux\" || host_system.os != \"linux\"\n microvm-cpus: 2;\n.end\n"; + var options = Options(module, Text); + Assert.Equal(Platform.WindowsX64, options.Platform); + Assert.Equal(4096, options.MicroVMMemory.Amount); + Assert.Equal(2, options.MicroVMCpus.Amount); + // The command line's platform is what target_system is. + Assert.Equal(2048, Options(module, Text, Platform.LinuxAarch64).MicroVMMemory.Amount); + } + + [Fact] + public void APlatformChosenOnTheTargetIsAnError() + { + using var module = new TemporaryModule().Write("p.options.txt", "platform: linux-amd64;"); + var problem = Problem(() => Options(module, ".if target_system.os == \"linux\"\n platform: windows-x64;\n.else\n platform: linux-amd64;\n.end\n")); + Assert.Equal(ErrorCodes.PlatformDependsOnTarget, problem.Code); + Assert.Equal(2, problem.Line); + // Through an include of such a branch too. + Assert.Equal(ErrorCodes.PlatformDependsOnTarget, + Problem(() => Options(module, ".if target_system.os == \"linux\" || true\n.include \"p.options.txt\"\n.end\n")).Code); + } + + [Fact] + public void AProblemInAnIncludedFileIsShownInThatFile() + { + using var module = new TemporaryModule().Write("bad.options.txt", "\nmicrovm-cpus: lots;"); + var problem = Problem(() => Options(module, "microvm-network: true;\n.include \"bad.options.txt\"\n")); + Assert.EndsWith("bad.options.txt", problem.File, StringComparison.Ordinal); + Assert.Equal(2, problem.Line); + Assert.Equal("microvm-cpus: lots;", problem.SourceLine); + } + + [Fact] + public void CustomCommandsAndEnvsIncludeAndChooseToo() + { + using var module = new TemporaryModule() + .Write("more.custom.txt", "hello: (\"echo\" \"hi\")") + .Write("more.envs.txt", "name: 'demo'"); + var custom = CustomParser.Parse(".include \"more.custom.txt\"\n.if host_system.os == \"nowhere\"\nnever: (\"false\");\n.end\nbye: (\"echo\" \"bye\");", + "tazel_custom.txt", Path.Combine(module.Root, "tazel_custom.txt")); + Assert.Equal(["hello", "bye"], custom.Select(command => command.Name)); + var envs = TazelEnvsFile.Parse(".include \"more.envs.txt\"\nversion: '1.0';", "tazel_envs.txt", Path.Combine(module.Root, "tazel_envs.txt")); + Assert.Equal(["name", "version"], envs.Select(entry => entry.Name)); + } + + [Fact] + public void ADirectiveStartsALineOnly() + { + // In a string, or after other text, a dot is no directive. + using var module = new TemporaryModule(); + var custom = CustomParser.Parse("say: (\"echo\" \".include x\");", "tazel_custom.txt", Path.Combine(module.Root, "tazel_custom.txt")); + Assert.Single(custom); + Assert.Equal(ErrorCodes.DirectiveUnknown, + Problem(() => CustomParser.Parse(".hidden: (\"x\");", "tazel_custom.txt", Path.Combine(module.Root, "tazel_custom.txt"))).Code); + } +} + +/// <summary>The tests that set TAZEL_HOME, which every test of the process would see: one at a time.</summary> +[CollectionDefinition(nameof(TazelHomeCollection), DisableParallelization = true)] +public sealed class TazelHomeCollection +{ +} + +[Collection(nameof(TazelHomeCollection))] +public sealed class TazelHomeTests +{ + private static TazelOptions Options(TemporaryModule module, string text) + { + var file = Path.Combine(module.Root, "tazel_options.txt"); + File.WriteAllText(file, text); + return TazelOptionsFile.Parse(text, "tazel_options.txt", file); + } + + private sealed class Home : IDisposable + { + private readonly string? _was = Environment.GetEnvironmentVariable(TazelHome.Variable); + + public Home(string? value) => Environment.SetEnvironmentVariable(TazelHome.Variable, value); + + public void Dispose() => Environment.SetEnvironmentVariable(TazelHome.Variable, _was); + } + + [Fact] + public void IncludesFromTheIncludeDirectoryOfTazelHome() + { + using var module = new TemporaryModule().Write("home/Include/Options/security.options.txt", "sandboxing-with-microvm: true"); + using var home = new Home(Path.Combine(module.Root, "home")); + Assert.True(Options(module, ".import <security.options.txt>\n").SandboxingWithMicroVM); + var missing = Assert.Throws<TazelOptionsException>(() => Options(module, ".include <nope.options.txt>\n")); + Assert.Contains("is not a file of", missing.Message, StringComparison.Ordinal); + } + + [Fact] + public void ALinkOutOfTheIncludeDirectoryIsRefused() + { + Assert.SkipWhen(OperatingSystem.IsWindows(), "symbolic links need a privilege on Windows"); + using var module = new TemporaryModule().Write("outside.options.txt", "microvm-cpus: 9").Write("home/Include/Options/keep", ""); + File.CreateSymbolicLink(Path.Combine(module.Root, "home", "Include", "Options", "link.options.txt"), + Path.Combine(module.Root, "outside.options.txt")); + using var home = new Home(Path.Combine(module.Root, "home")); + var error = Assert.Throws<TazelOptionsException>(() => Options(module, ".include <link.options.txt>\n")); + Assert.Contains("through a link", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void ATazelHomeThatIsNotAbsoluteIsAnError() + { + using var home = new Home("relative/home"); + Assert.Throws<ConfigurationHomeException>(() => TazelHome.Directory()); + using var module = new TemporaryModule(); + var error = Assert.Throws<TazelOptionsException>(() => Options(module, ".include <x.options.txt>\n")); + Assert.Contains("not an absolute path", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void TheDefaultHomeIsDotTazelOrAppDataTazel() + { + using var home = new Home(null); + var directory = TazelHome.Directory(); + Assert.Equal(OperatingSystem.IsWindows() ? "Tazel" : ".Tazel", Path.GetFileName(directory)); + } +}