// SPDX-FileCopyrightText: 2026 Progmasoft // SPDX-License-Identifier: MIT using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Progmasoft.Tazel.Driver; /// /// One action of a build: a command line with its environment, the files it reads and the files it writes, all relative /// to the directory it runs in. Inputs the command finds by itself, such as headers, come from its depfile. /// /// What an action does, which decides what --recompile forces. internal enum ActionKind { /// A step of a plugin or a custom build action. Step, /// Compiling one source file to an object file. Compile, /// Compiling and linking in one command, as zig does. CompileAndLink, /// Linking objects and libraries into a program or a shared library. Link, /// Archiving objects into a static library. Archive, } /// What a build may take from its caches: everything, nothing for compilations, or nothing at all. internal enum CachePolicy { /// The caches as configured. Normal, /// --recompile: compilations run, and other actions follow from what they wrote. Recompile, /// --no-cache: every action runs, and no cache is read or written. NoCache, } internal sealed class BuildAction { /// What the action does; a step unless a planner says otherwise. public ActionKind Kind { get; init; } = ActionKind.Step; /// /// The command with the compiler's own cache moved to the directory it is given, for a run that must really compile; /// null when the compiler keeps no cache of its own that Tazel knows of. The key stays that of . /// public Func>? WithCompilerCache { get; init; } public required string Description { get; init; } public required IReadOnlyList Command { get; init; } public required string Directory { get; init; } public required IReadOnlyList Inputs { get; init; } public required IReadOnlyList Outputs { get; init; } public IReadOnlyDictionary Environment { get; init; } = new Dictionary(); /// The Make-style dependency file the command writes, if it writes one. public string? Depfile { get; init; } /// What to say when the command succeeded but did not write one of its outputs. public IReadOnlyDictionary MissingOutputHints { get; init; } = new Dictionary(); /// Work done in Tazel after the command succeeded, such as the links of a shared library. public Action? After { get; init; } /// Work that runs in Tazel instead of , such as a step of a plugin. public Func>? Work { get; init; } /// The actions whose outputs this one reads. public List Prerequisites { get; } = []; /// The digest of what the action is apart from its files: command, directory and environment. public string Key { get { var text = new StringBuilder(); foreach (var part in Command) { text.Append(part).Append('\0'); } text.Append('\u0001').Append(Directory).Append('\u0001'); foreach (var (name, value) in Environment.OrderBy(entry => entry.Key, StringComparer.Ordinal)) { text.Append(name).Append('=').Append(value).Append('\0'); } return Digests.Sha256(Encoding.UTF8.GetBytes(text.ToString())); } } public string Full(string path) => Path.GetFullPath(Path.Combine(Directory, path)); } /// /// The SHA-256 of files, each read once in a build: what a file holds is taken the first time an action asks, and kept /// until a build writes it (). A file most compilations include, a header of the standard library, /// is read and looked at once, not once per compilation that names it. /// internal sealed class Digests { // A digest, or null for a file that was not there or could not be read. private readonly ConcurrentDictionary _known = new(StringComparer.Ordinal); /// The SHA-256 of as lower-case hexadecimal. public static string Sha256(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); /// The digest of , or null when it is not a readable regular file. public string? Of(string file) => _known.GetOrAdd(file, Read); /// Forgets , before or after a build writes it. public void Forget(string file) => _known.TryRemove(file, out _); private static string? Read(string file) { if (!File.Exists(file)) { return null; } try { using var stream = File.OpenRead(file); return Convert.ToHexStringLower(SHA256.HashData(stream)); } catch (Exception error) when (error is IOException or UnauthorizedAccessException) { return null; } } } /// /// Action-level incremental builds. Each action keeps a record beside its first output: its key, and the digest of /// every input it read and every output it wrote. An action is current while its key is the same, every input has the /// digest it had, and every output is still what it wrote. Inputs are compared by content, so touching a file reruns /// nothing, and an output rebuilt to the same bytes reruns none of the actions that read it. /// internal sealed class ActionCache(Digests digests, bool enabled = true) { /// Whether would write what it wrote last time; never, when the cache is off. public bool IsCurrent(BuildAction action) { if (!enabled) { return false; } var record = Read(RecordOf(action)); if (record is null || record.Value.Key != action.Key) { return false; } var files = record.Value.Files; return files.All(entry => digests.Of(entry.Key) == entry.Value) && action.Outputs.All(output => files.ContainsKey(action.Full(output))) && action.Inputs.All(input => files.ContainsKey(action.Full(input))); } /// Records after it succeeded. public void Record(BuildAction action) { var files = new SortedDictionary(StringComparer.Ordinal); foreach (var output in action.Outputs) { digests.Forget(action.Full(output)); } var discovered = action.Depfile is { } depfile && File.Exists(action.Full(depfile)) ? Depfiles.Inputs(File.ReadAllText(action.Full(depfile))) : []; foreach (var file in action.Inputs.Concat(discovered).Concat(action.Outputs).Select(action.Full)) { files[file] = digests.Of(file) ?? throw new IOException($"{file} was not written or cannot be read"); } var text = new StringBuilder().Append("key ").Append(action.Key).Append('\n'); foreach (var (file, digest) in files) { text.Append("file ").Append(digest).Append(' ').Append(file).Append('\n'); } File.WriteAllText(RecordOf(action), text.ToString()); } /// /// Forgets what this process knows of the outputs of and keeps its record, which a later /// build checks against the files before it trusts it. /// public void ForgetOutputs(BuildAction action) { foreach (var output in action.Outputs) { digests.Forget(action.Full(output)); } } /// Forgets , so that a failed or stopped run is redone. public void Forget(BuildAction action) { File.Delete(RecordOf(action)); foreach (var output in action.Outputs) { digests.Forget(action.Full(output)); } } private static string RecordOf(BuildAction action) => action.Full(action.Outputs[0]) + ".action"; private static (string Key, Dictionary Files)? Read(string file) { string[] lines; try { lines = File.ReadAllLines(file); } catch (IOException) { return null; } catch (UnauthorizedAccessException) { return null; } if (lines.Length == 0 || !lines[0].StartsWith("key ", StringComparison.Ordinal)) { return null; } var files = new Dictionary(StringComparer.Ordinal); foreach (var line in lines.Skip(1)) { if (!line.StartsWith("file ", StringComparison.Ordinal) || line.Length < 5 + 64 + 2) { return null; } files[line[(5 + 64 + 1)..]] = line[5..(5 + 64)]; } return (lines[0][4..], files); } } /// Make-style dependency files, as compilers write them with -MD -MF. internal static class Depfiles { /// /// The inputs a depfile names: the target, a colon, then the inputs, with \ for a space and a backslash at /// the end of a line to go on. /// public static IReadOnlyList Inputs(string text) { ArgumentNullException.ThrowIfNull(text); var colon = text.IndexOf(": ", StringComparison.Ordinal); if (colon < 0) { colon = text.IndexOf(":\n", StringComparison.Ordinal); } if (colon < 0) { return []; } var body = text[(colon + 1)..]; var inputs = new List(); var current = new StringBuilder(); var index = 0; while (index < body.Length) { var rest = body.AsSpan(index); var step = 1; if (rest.StartsWith("\\ ")) { current.Append(' '); step = 2; } else if (rest.StartsWith("\\\n")) { Flush(); step = 2; } else if (rest.StartsWith("\\\r\n")) { Flush(); step = 3; } else if (rest.StartsWith("$$")) { current.Append('$'); step = 2; } else if (char.IsWhiteSpace(rest[0])) { Flush(); } else { current.Append(rest[0]); } index += step; } Flush(); return inputs; void Flush() { if (current.Length > 0) { inputs.Add(current.ToString()); } current.Clear(); } } }