// SPDX-FileCopyrightText: 2026 Progmasoft // SPDX-License-Identifier: MIT using System; using System.Collections.Generic; using System.IO; using System.Linq; using Progmasoft.Tazel.Dsl; using Progmasoft.Tazel.Dsl.Build.Prelude; using Progmasoft.Tazel.Dsl.Common; using Progmasoft.Tazel.Project; namespace Progmasoft.Tazel.Driver; /// What a planned target makes, and what its dependents take from it. internal sealed class TargetProducts { /// The action that makes the target's main file: the archive, the link or the zig command. public BuildAction? Main { get; set; } /// The file dependents link: a static library, a shared library or its import library. public string? Library { get; set; } public bool IsShared { get; set; } public bool AlwaysLink { get; set; } /// The program, for executables and tests. public string? Executable { get; set; } /// The directories of the shared libraries a program loads, for rpath and PATH. public List SharedLibraryDirectories { get; } = []; /// Include directories for this target's dependents. public List PublicIncludes { get; } = []; /// Macros for this target's dependents. public List PublicDefines { get; } = []; /// Headers dependents may include, for the inputs of their compilations. public List PublicHeaders { get; } = []; /// Actions whose outputs dependents' compilations read, such as headers zig emits. public List HeaderActions { get; } = []; /// Linker options, frameworks and libraries that go to whatever links this library. public List LinkTail { get; } = []; } /// Turns targets into the actions that build them. internal sealed partial class Planner { private readonly Dictionary _planned = []; public Planner(Workspace workspace, BuildOptions options, ToolchainChooser toolchains) { Workspace = workspace; Options = options; Toolchains = toolchains; Layout = new OutputLayout(workspace.Main.Root, options); ActionEnvironment = Processes.ForActions(); } public Workspace Workspace { get; } public BuildOptions Options { get; } public ToolchainChooser Toolchains { get; } public OutputLayout Layout { get; } public Dictionary ActionEnvironment { get; } /// What makes, planning it and what it depends on once. public TargetProducts Plan(ProjectTarget target) { if (_planned.TryGetValue(target, out var known)) { return known; } var products = target.Family switch { Family.Zig => PlanZig(target), Family.Plugin => PlanStep(target), _ => PlanCC(target), }; _planned[target] = products; return products; } /// Checks the features the command line names against the toolchains the build used. public void CheckCommandLineFeatures(IEnumerable used) { var known = used.SelectMany(toolchain => toolchain.Features).Select(feature => feature.Name).ToHashSet(StringComparer.Ordinal); foreach (var name in Options.FeaturesOn.Concat(Options.FeaturesOff)) { if (!known.Contains(name)) { var near = Cli.Suggestions.Nearest(name, known); throw new ProjectException( $"no toolchain of this build has the feature '{name}'{(near is null ? "" : $"; did you mean '{near}'?")}"); } } } /// The libraries a link takes for 's dependencies, each before what it needs. private List<(ProjectTarget Target, TargetProducts Products)> LinkOrder(ProjectTarget target) { var post = new List<(ProjectTarget Target, TargetProducts Products)>(); var seen = new HashSet<(ProjectTarget, bool)>(); foreach (var dependency in target.Dependencies) { Visit(dependency, belowShared: false); } // Reversed, each library comes before the libraries it needs; a library reached twice keeps its last place. post.Reverse(); var placed = new HashSet(); return post.Where(entry => placed.Add(entry.Target)).ToList(); void Visit(ProjectTarget library, bool belowShared) { if (!seen.Add((library, belowShared))) { return; } var products = Plan(library); // What a shared library links statically is inside it; only its shared libraries still have to be found. foreach (var next in library.Dependencies) { Visit(next, belowShared || products.IsShared); } if (!belowShared || products.IsShared) { post.Add((library, products)); } } } /// A library on the link line; one linked whole is wrapped so that none of its objects is dropped. private static string[] LibraryArguments(string library, bool whole, OS os) => !whole ? [library] : os == OS.MacOS ? [$"-Wl,-force_load,{library}"] : ["-Wl,--whole-archive", library, "-Wl,--no-whole-archive"]; /// Where a program finds a shared library at run time, relative to itself; Windows has no run path. private static string[] RunPath(string outputDirectory, string directory, OS os) { var relative = Path.GetRelativePath(outputDirectory, directory).Replace('\\', '/'); var suffix = relative == "." ? "" : "/" + relative; return os switch { OS.MacOS => [$"-Wl,-rpath,@loader_path{suffix}"], OS.Windows => [], _ => [$"-Wl,-rpath,$ORIGIN{suffix}"], }; } /// The linker arguments for the libraries of , and the actions that make them. private (List Arguments, List Inputs, List Actions, List SharedDirectories) LinkLibraries(ProjectTarget target, string outputDirectory, bool forZig = false) { var arguments = new List(); var inputs = new List(); var actions = new List(); var sharedDirectories = new List(); var tail = new List(); var os = Options.Platform.GetOS(); foreach (var (_, products) in LinkOrder(target)) { if (products.Main is { } main) { actions.Add(main); } if (products.Library is { } library) { inputs.Add(library); arguments.AddRange(LibraryArguments(library, products.AlwaysLink && !products.IsShared && !forZig, os)); var directory = Path.GetDirectoryName(library)!.Replace('\\', '/'); if (products.IsShared && !sharedDirectories.Contains(directory)) { sharedDirectories.Add(directory); } } tail.AddRange(products.LinkTail); } if (!forZig) { arguments.AddRange(sharedDirectories.SelectMany(directory => RunPath(outputDirectory, directory, os))); } arguments.AddRange(tail); return (arguments, inputs, actions, sharedDirectories); } private static string Sanitized(string text) => new(text.Select(c => char.IsAsciiLetterOrDigit(c) ? c : '_').ToArray()); /// The file names of libraries and programs on the platform of the build. private string StaticLibraryName(string name) => Options.Platform.GetOS() == OS.Windows ? $"{name}.lib" : $"lib{name}.a"; private string ExecutableName(string name) => Options.Platform.GetOS() == OS.Windows ? $"{name}.exe" : name; /// The file a shared library is written to, the file its dependents link, and its soname. private (string File, string LinkWith, string? Soname) SharedLibraryNames(string directory, string name, Version? version) { switch (Options.Platform.GetOS()) { case OS.Windows: return ($"{directory}/{name}.dll", $"{directory}/{name}.lib", null); case OS.MacOS: var mac = version is null ? $"lib{name}.dylib" : $"lib{name}.{version.Major}.dylib"; return ($"{directory}/{mac}", $"{directory}/{mac}", mac); default: if (version is null) { return ($"{directory}/lib{name}.so", $"{directory}/lib{name}.so", $"lib{name}.so"); } var full = $"lib{name}.so.{version.ToString(Math.Min(3, FieldCount(version)))}"; return ($"{directory}/{full}", $"{directory}/{full}", $"lib{name}.so.{version.Major}"); } } private static int FieldCount(Version version) => version.Build >= 0 ? 3 : version.Minor >= 0 ? 2 : 1; /// Makes libx.so.1 and libx.so point at libx.so.1.2.0. private Action? SonameLinks(string file, string? soname, string name) { if (Options.Platform.GetOS() is OS.Windows or OS.MacOS || soname is null || Path.GetFileName(file) == soname) { return null; } var directory = Layout.Full(Path.GetDirectoryName(file)!); var target = Path.GetFileName(file); return () => { foreach (var link in new[] { soname, $"lib{name}.so" }) { var path = Path.Combine(directory, link); File.Delete(path); File.CreateSymbolicLink(path, target); } }; } }