// SPDX-FileCopyrightText: 2026 Progmasoft // 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; /// A part of a text file: tokens of its entries, or a directive. /// Where it starts. public abstract record Node(Token At); /// Tokens of entries, as the reader of the file's kind takes them. /// The tokens, in order. public sealed record TokensNode(IReadOnlyList Tokens) : Node(Tokens[0]); /// .include or .import of a file. /// The directive. /// The path as written, without its quotes or brackets. /// Whether it was written <path>, below the Include directory of TAZEL_HOME. /// Whether it is .import, which reads a file at most once. public sealed record IncludeNode(Token At, string Path, bool Global, bool Import) : Node(At); /// One branch of an .if: its condition, null for .else, and what it holds. /// The .if, .elif or .else. /// The condition, or null for .else. /// What the branch holds. public sealed record Branch(Token At, Condition? Condition, IReadOnlyList Body); /// .if ... .end: the first branch whose condition holds is taken. /// The .if. /// Its branches, in order. public sealed record IfNode(Token At, IReadOnlyList Branches) : Node(At) { /// Whether any branch's condition names target_system. public bool OnTarget => Branches.Any(branch => branch.Condition?.UsesTarget == true); } /// A text file read: what it holds and whether it said .pragma once. /// Its parts, in order. /// Whether it starts with .pragma once. public sealed record ConfigurationDocument(IReadOnlyList Nodes, bool Once); /// /// The parser of tazel_options.txt, tazel_custom.txt and tazel_envs.txt: it puts the tokens of /// into a tree of entries and directives. It reads every branch of every .if, so a /// mistake in a branch not taken is found too, and it opens no file and runs nothing. /// public static class ConfigurationParser { /// The deepest .if may nest, and the deepest includes may go. public static int MaxDepth { get; } = 64; private static readonly string[] Directives = ["include", "import", "pragma", "if", "elif", "else", "end"]; /// The tree of , read from of . public static ConfigurationDocument Parse(IReadOnlyList tokens, string file, string text) { ArgumentNullException.ThrowIfNull(tokens); return new Reader(file, text).Read(tokens); } // An .if being read: its branches so far, and the one being read. private sealed class Frame(Token at, Condition? test) { public Token At { get; } = at; public List Branches { get; } = []; public Token BranchAt { get; set; } = at; public Condition? Test { get; set; } = test; public List Body { get; set; } = []; public bool SawElse { get; set; } public void Close() => Branches.Add(new Branch(BranchAt, Test, Body)); } private sealed class Reader(string file, string text) { private readonly List _root = []; private readonly Stack _frames = new(); private readonly List _pending = []; private bool _once; private List Current => _frames.Count == 0 ? _root : _frames.Peek().Body; public ConfigurationDocument Read(IReadOnlyList tokens) { for (var i = 0; i < tokens.Count; i++) { var token = tokens[i]; if (token.Kind != TokenKind.Directive) { _pending.Add(token); continue; } Flush(); Directive(token, token.Argument ?? "", first: i == 0); } 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); } private void Flush() { if (_pending.Count > 0) { Current.Add(new TokensNode(_pending.ToList())); _pending.Clear(); } } private 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)); private void Directive(Token token, string argument, bool first) { 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": Include(token, argument); break; case "pragma": Pragma(token, argument, first); break; case "if": If(token); break; case "elif" or "else": Else(token, argument); break; case "end": End(token, argument); break; default: var near = Cli.Suggestions.Nearest(token.Text, Directives); 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."); } } private void Include(Token token, string argument) { 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} 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")); } private void Pragma(Token token, string argument, bool first) { 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 (!first) { 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; } private void If(Token token) { 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, ConditionOf(token, file, text))); } private void Else(Token token, string argument) { 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."); } var isElse = token.Text == "else"; if (isElse && 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.Close(); frame.BranchAt = token; frame.Test = isElse ? null : ConditionOf(token, file, text); frame.Body = []; frame.SawElse = isElse; } private void End(Token token, string argument) { 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.Close(); Current.Add(new IfNode(closing.At, closing.Branches)); } } // "file", 'file' or `file`, relative to the file that names it; , 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 ConditionOf(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.")); } } }