tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Split the long methods of building and reading command lines
- Commit
7c7bd3be645ec0e001dba12cef9aa3c2ed1d078b- Author
- Leitwolf11 ·
- Parents
bb29c1e19035
Changes
src/Progmasoft.Tazel/Cli/CommandLine.cs | 255 +++++++++++++++--------------- src/Progmasoft.Tazel/Cli/Commands.cs | 126 +++++++++------ src/Progmasoft.Tazel/Driver/CCPlanner.cs | 253 ++++++++++++++++------------- src/Progmasoft.Tazel/Driver/Executor.cs | 43 +++-- src/Progmasoft.Tazel/Driver/Planner.cs | 53 +++---- src/Progmasoft.Tazel/Driver/ZigPlanner.cs | 159 +++++++++---------- 6 files changed, 476 insertions(+), 413 deletions(-) diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs index 0caf9a3..c617c67 100644 --- a/src/Progmasoft.Tazel/Cli/CommandLine.cs +++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs @@ -163,6 +163,48 @@ internal static class CommandLine public static Command Parse(IReadOnlyList<string> arguments) { ArgumentNullException.ThrowIfNull(arguments); + var scanned = Scan(arguments); + var command = scanned.Command; + var unscoped = scanned.Seen.FirstOrDefault(entry => + entry.Option.Scope.Length > 0 && !entry.Option.Scope.Contains(command, StringComparer.Ordinal)); + if (unscoped.Option is not null) + { + throw new CommandLineException($"{unscoped.Written} is not an option of tazel {command}"); + } + + var output = new OutputOptions( + ParseWhen(Last(scanned.Seen, "color")) ?? When.Auto, + ParseWhen(Last(scanned.Seen, "progress")) ?? When.Auto, + scanned.Has("quiet")); + if (scanned.Has("help") && command != "help") + { + return new HelpCommand(output, command); + } + + if (command == "portal-modules") + { + // After -- a query may start with a dash. + scanned.Positional.AddRange(scanned.AfterDashes); + scanned.AfterDashes.Clear(); + } + + if (scanned.AfterDashes.Count > 0 && command != "run") + { + throw new CommandLineException($"tazel {command} takes nothing after --; only tazel run passes arguments on"); + } + + return Makers.TryGetValue(command, out var make) ? make(scanned, output) : MakeHelp(scanned, output); + } + + /// <summary>The words of a command line, read: the command, the words that are not options, and the options.</summary> + private sealed record Scanned( + string Command, List<string> Positional, List<string> AfterDashes, List<(Option Option, List<string> Values, string Written)> Seen) + { + public bool Has(string option) => Seen.Any(entry => entry.Option.Long == option); + } + + private static Scanned Scan(IReadOnlyList<string> arguments) + { string? command = null; var positional = new List<string>(); var afterDashes = new List<string>(); @@ -175,16 +217,13 @@ internal static class CommandLine { // Everything after `tazel custom` belongs to the custom command, its options too. positional.Add(argument); - continue; } - - if (argument == "--") + else if (argument == "--") { afterDashes.AddRange(arguments.Skip(index)); break; } - - if (argument.StartsWith("--", StringComparison.Ordinal)) + else if (argument.StartsWith("--", StringComparison.Ordinal)) { ReadLong(argument, arguments, ref index, seen); } @@ -202,104 +241,71 @@ internal static class CommandLine } } - command ??= "help"; - foreach (var (option, _, written) in seen) - { - if (option.Scope.Length > 0 && !option.Scope.Contains(command, StringComparer.Ordinal)) - { - throw new CommandLineException($"{written} is not an option of tazel {command}"); - } - } + return new Scanned(command ?? "help", positional, afterDashes, seen); + } - var output = new OutputOptions( - ParseWhen(Last(seen, "color")) ?? When.Auto, - ParseWhen(Last(seen, "progress")) ?? When.Auto, - seen.Any(entry => entry.Option.Long == "quiet")); - if (seen.Any(entry => entry.Option.Long == "help") && command != "help") - { - return new HelpCommand(output, command); - } + /// <summary>How each command is made from what was scanned; tazel help is the rest.</summary> + private static readonly Dictionary<string, Func<Scanned, OutputOptions, Command>> Makers = new(StringComparer.Ordinal) + { + ["build"] = (scanned, output) => new BuildCommand(output, scanned.Positional, Flags(scanned.Seen)), + ["test"] = (scanned, output) => new TestCommand(output, scanned.Positional, Flags(scanned.Seen)), + ["coverage"] = (scanned, output) => new CoverageCommand(output, scanned.Positional, Flags(scanned.Seen)), + ["run"] = MakeRun, + ["query"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.Query), + ["cquery"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.CQuery), + ["aquery"] = (scanned, output) => MakeQuery(scanned, output, QueryKind.AQuery), + ["explain"] = (scanned, output) => Explain(output, scanned.Positional, scanned.Has("long")), + ["fetch"] = (scanned, output) => Bare(scanned, new FetchCommand(output)), + ["vendor"] = (scanned, output) => Bare(scanned, new VendorCommand(output)), + ["portal-modules"] = (scanned, output) => PortalModules(output, scanned.Positional, scanned.Has("exact")), + ["clean"] = (scanned, output) => Bare(scanned, new CleanCommand(output, scanned.Has("expunge"))), + ["package"] = (scanned, output) => Bare(scanned, new PackageCommand(output)), + ["custom"] = (scanned, output) => scanned.Positional.Count == 0 + ? throw new CommandLineException("tazel custom needs the name of a command of tazel_custom.txt") + : new CustomCommandLine(output, scanned.Positional), + ["version"] = (scanned, output) => Bare(scanned, new VersionCommand(output)), + ["dotnet"] = MakeDaemon, + }; - if (command == "portal-modules") - { - // After -- a query may start with a dash. - positional.AddRange(afterDashes); - afterDashes.Clear(); - } + private static Command Bare(Scanned scanned, Command command) + { + NoPositional(scanned.Command, scanned.Positional); + return command; + } - if (afterDashes.Count > 0 && command != "run") - { - throw new CommandLineException($"tazel {command} takes nothing after --; only tazel run passes arguments on"); - } + private static Command MakeRun(Scanned scanned, OutputOptions output) + { + var positional = scanned.Positional; + return positional.Count > 1 + ? throw new CommandLineException( + $"tazel run takes one target; the program's own arguments go after --: tazel run {positional[0]} -- {string.Join(' ', positional.Skip(1))}") + : new RunCommand(output, positional.FirstOrDefault(), Flags(scanned.Seen), scanned.AfterDashes); + } - switch (command) + private static Command MakeQuery(Scanned scanned, OutputOptions output, QueryKind kind) => + scanned.Positional.Count == 0 + ? throw new CommandLineException($"tazel {scanned.Command} needs an expression, such as deps(//app:greeter)") + : new QueryCommand(output, kind, string.Join(' ', scanned.Positional), Flags(scanned.Seen), Last(scanned.Seen, "output") ?? "label"); + + private static Command MakeDaemon(Scanned scanned, OutputOptions output) + { + var actions = new[] { "start-daemon", "restart-daemon", "stop-daemon" }; + var positional = scanned.Positional; + if (positional.Count == 1 && actions.Contains(positional[0], StringComparer.Ordinal)) { - case "build": - return new BuildCommand(output, positional, Flags(seen)); - case "test": - return new TestCommand(output, positional, Flags(seen)); - case "run": - if (positional.Count > 1) - { - throw new CommandLineException( - $"tazel run takes one target; the program's own arguments go after --: tazel run {positional[0]} -- {string.Join(' ', positional.Skip(1))}"); - } - - return new RunCommand(output, positional.FirstOrDefault(), Flags(seen), afterDashes); - case "coverage": - return new CoverageCommand(output, positional, Flags(seen)); - case "query" or "cquery" or "aquery": - if (positional.Count == 0) - { - throw new CommandLineException($"tazel {command} needs an expression, such as deps(//app:greeter)"); - } - - return new QueryCommand(output, command switch - { - "query" => QueryKind.Query, - "cquery" => QueryKind.CQuery, - _ => QueryKind.AQuery, - }, string.Join(' ', positional), Flags(seen), Last(seen, "output") ?? "label"); - case "explain": - return Explain(output, positional, seen.Any(entry => entry.Option.Long == "long")); - case "fetch": - NoPositional(command, positional); - return new FetchCommand(output); - case "vendor": - NoPositional(command, positional); - return new VendorCommand(output); - case "portal-modules": - return PortalModules(output, positional, seen.Any(entry => entry.Option.Long == "exact")); - case "clean": - NoPositional(command, positional); - return new CleanCommand(output, seen.Any(entry => entry.Option.Long == "expunge")); - case "package": - NoPositional(command, positional); - return new PackageCommand(output); - case "custom": - return positional.Count == 0 - ? throw new CommandLineException("tazel custom needs the name of a command of tazel_custom.txt") - : new CustomCommandLine(output, positional); - case "version": - NoPositional(command, positional); - return new VersionCommand(output); - case "dotnet": - var actions = new[] { "start-daemon", "restart-daemon", "stop-daemon" }; - if (positional.Count != 1 || !actions.Contains(positional[0], StringComparer.Ordinal)) - { - var near = positional.Count == 1 ? Suggestions.Nearest(positional[0], actions) : null; - throw new CommandLineException( - $"tazel dotnet takes start-daemon, restart-daemon or stop-daemon{(near is null ? "" : $"; did you mean {near}?")}"); - } - - return new DaemonCommand(output, positional[0]); - default: - return positional.Count > 1 - ? throw new CommandLineException("tazel help takes one command") - : new HelpCommand(output, positional.FirstOrDefault(), seen.Any(entry => entry.Option.Long == "long")); + return new DaemonCommand(output, positional[0]); } + + var near = positional.Count == 1 ? Suggestions.Nearest(positional[0], actions) : null; + throw new CommandLineException( + $"tazel dotnet takes start-daemon, restart-daemon or stop-daemon{(near is null ? "" : $"; did you mean {near}?")}"); } + private static Command MakeHelp(Scanned scanned, OutputOptions output) => + scanned.Positional.Count > 1 + ? throw new CommandLineException("tazel help takes one command") + : new HelpCommand(output, scanned.Positional.FirstOrDefault(), scanned.Has("long")); + /// <summary>Splits a list at commas; <c>\,</c> is a comma of a value.</summary> public static IReadOnlyList<string> SplitList(string text) { @@ -333,30 +339,23 @@ internal static class CommandLine return items; } + private static CommandLineException UnknownOption(string name, string rest) + { + var near = Suggestions.Nearest(name, Options.Select(o => o.Long)); + return new CommandLineException($"--{name} is not an option{(near is null ? "" : $"; did you mean --{near}{rest}?")}"); + } + private static void ReadLong( string argument, IReadOnlyList<string> arguments, ref int index, List<(Option, List<string>, string)> seen) { var body = argument[2..]; var separator = body.IndexOfAny(['=', ':']); var name = separator < 0 ? body : body[..separator]; - var option = Options.FirstOrDefault(o => o.Long == name); - if (option is null) - { - var near = Suggestions.Nearest(name, Options.Select(o => o.Long)); - var rest = separator < 0 ? "" : body[separator..]; - throw new CommandLineException( - $"--{name} is not an option{(near is null ? "" : $"; did you mean --{near}{rest}?")}"); - } - + var option = Options.FirstOrDefault(o => o.Long == name) ?? throw UnknownOption(name, separator < 0 ? "" : body[separator..]); List<string> values; if (option.Kind == Kind.Flag) { - if (separator >= 0) - { - throw new CommandLineException($"--{name} takes no value"); - } - - values = []; + values = separator < 0 ? [] : throw new CommandLineException($"--{name} takes no value"); } else if (separator >= 0) { @@ -366,13 +365,8 @@ internal static class CommandLine } else { - if (index >= arguments.Count) - { - throw new CommandLineException($"--{name} needs a value"); - } - // Whitespace gives one value, whatever it holds. - values = [arguments[index++]]; + values = index < arguments.Count ? [arguments[index++]] : throw new CommandLineException($"--{name} needs a value"); Check(option, values, $"--{name} "); } @@ -467,6 +461,22 @@ internal static class CommandLine return flags; } + /// <summary>A query is module or group:module, and group:module with --exact.</summary> + private static void CheckModuleQuery(string action, string query, bool exact) + { + var parts = query.Split(':'); + if (exact && (parts.Length != 2 || parts[0].Length == 0)) + { + throw new CommandLineException( + $"with -e or --exact, tazel portal-modules {action} needs the group too: group:{query.TrimStart(':')}"); + } + + if (parts.Length > 2 || parts.Any(part => part.Length == 0)) + { + throw new CommandLineException($"'{query}' is not module or group:module"); + } + } + private static PortalModulesCommand PortalModules(OutputOptions output, List<string> positional, bool exact) { var actions = new[] { "search", "info" }; @@ -483,18 +493,7 @@ internal static class CommandLine } var query = positional[1]; - var colon = query.IndexOf(':', StringComparison.Ordinal); - if (exact && colon <= 0) - { - throw new CommandLineException( - $"with -e or --exact, tazel portal-modules {positional[0]} needs the group too: group:{query.TrimStart(':')}"); - } - - if (colon >= 0 && (colon == 0 || colon == query.Length - 1 || query.IndexOf(':', colon + 1) >= 0)) - { - throw new CommandLineException($"'{query}' is not module or group:module"); - } - + CheckModuleQuery(positional[0], query, exact); return new PortalModulesCommand(output, positional[0] == "search" ? PortalAction.Search : PortalAction.Info, query, exact); } diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index ada470b..e8dd0c1 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -203,6 +203,11 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector return 0; } + /// <summary>What a build command works on: its options, its targets, and the planner that planned them.</summary> + private sealed record Built( + BuildOptions Options, Planner Planner, ToolchainChooser Chooser, Executor Executor, bool Succeeded, + List<(ProjectTarget Target, TargetProducts Products)> Planned); + private async Task<int> BuildAsync( IReadOnlyList<string> labels, BuildFlags flags, BuildKind kind, IReadOnlyList<string>? programArguments, CancellationToken cancel) @@ -215,8 +220,19 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(mode, platform), TazelVersion, reporter.Status).ConfigureAwait(false); WarnAboutWhatThisTazelDoesNotDo(workspace.Main.Globals); - var execution = workspace.Main.Globals.execution?.Settings; - var buildOptions = new BuildOptions + var buildOptions = OptionsOf(flags, workspace.Main.Globals.execution?.Settings, kind, platform, mode); + var selected = Select(new Selector(workspace, platform), labels, kind, platform); + var built = await RunBuildAsync(workspace, buildOptions, selected, kind, cancel).ConfigureAwait(false); + return kind switch + { + BuildKind.Test or BuildKind.Coverage => await FinishTestsAsync(built, kind, cancel).ConfigureAwait(false), + BuildKind.Run => built.Succeeded ? RunProgram(built, programArguments) : 1, + _ => FinishBuild(built, selected.Count), + }; + } + + private static BuildOptions OptionsOf( + BuildFlags flags, Dsl.Module.Prelude.ExecutionSettings? execution, BuildKind kind, Platform platform, BuildMode mode) => new() { Mode = mode, Platform = platform, @@ -232,7 +248,9 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector Coverage = kind == BuildKind.Coverage, }; - var selector = new Selector(workspace, platform); + /// <summary>The targets of a command: tests for test and coverage, one program for run, anything for build.</summary> + private List<ProjectTarget> Select(Selector selector, IReadOnlyList<string> labels, BuildKind kind, Platform platform) + { var selected = kind switch { BuildKind.Test or BuildKind.Coverage => @@ -252,63 +270,67 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector reporter.Status($"left out {selector.Skipped} target{(selector.Skipped == 1 ? "" : "s")} that do not build for {platform.Name()}"); } - var chooser = new ToolchainChooser(workspace, platform); + return selected; + } + + private async Task<Built> RunBuildAsync( + Workspace workspace, BuildOptions buildOptions, List<ProjectTarget> selected, BuildKind kind, CancellationToken cancel) + { + var chooser = new ToolchainChooser(workspace, buildOptions.Platform); var planner = new Planner(workspace, buildOptions, chooser); var planned = selected.Select(target => (Target: target, Products: planner.Plan(target))).ToList(); planner.CheckCommandLineFeatures(chooser.UsedCC); var goals = planned.Select(entry => entry.Products.Main).OfType<BuildAction>().Distinct().ToList(); reporter.Status($"building {selected.Count} target{(selected.Count == 1 ? "" : "s")}"); - var digests = new Digests(); var cacheSettings = workspace.Main.Globals.cache?.Settings; var executor = new Executor(buildOptions.Jobs, buildOptions.KeepGoing || kind is BuildKind.Test or BuildKind.Coverage, - new ActionCache(digests, enabled: cacheSettings?.Local ?? true), reporter); - var built = await executor.RunAsync(goals, cancel).ConfigureAwait(false); - switch (kind) + new ActionCache(new Digests(), enabled: cacheSettings?.Local ?? true), reporter); + var succeeded = await executor.RunAsync(goals, cancel).ConfigureAwait(false); + return new Built(buildOptions, planner, chooser, executor, succeeded, planned); + } + + private async Task<int> FinishTestsAsync(Built built, BuildKind kind, CancellationToken cancel) + { + var tests = built.Planned.Select(entry => (entry.Target, entry.Products, + Built: entry.Products.Main is { } main && built.Executor.Succeeded(main))).ToList(); + var outcomes = await new TestRunner(built.Planner.Layout, built.Options.Jobs, reporter, built.Options.Coverage) + .RunAsync(tests, cancel).ConfigureAwait(false); + reporter.TestSummary(outcomes); + var passed = outcomes.All(outcome => outcome.Status is TestStatus.Passed or TestStatus.Cached or TestStatus.Flaky); + var reported = kind != BuildKind.Coverage || + await CoverageReport.WriteAsync(built.Planner, built.Chooser, tests, reporter, cancel).ConfigureAwait(false); + return passed && reported ? 0 : 1; + } + + private static int RunProgram(Built built, IReadOnlyList<string>? programArguments) + { + var (target, products) = built.Planned[0]; + var layout = built.Planner.Layout; + var runfiles = Runfiles.Prepare(target, products, layout); + var environment = Processes.Inherited(); + var settings = (IRunSettings)target.Settings; + foreach (var (name, value) in settings.EnvironmentVariables) { - case BuildKind.Test or BuildKind.Coverage: - var tests = planned.Select(entry => (entry.Target, entry.Products, - Built: entry.Products.Main is { } main && executor.Succeeded(main))).ToList(); - var outcomes = await new TestRunner(planner.Layout, buildOptions.Jobs, reporter, buildOptions.Coverage) - .RunAsync(tests, cancel).ConfigureAwait(false); - reporter.TestSummary(outcomes); - var passed = outcomes.All(outcome => outcome.Status is TestStatus.Passed or TestStatus.Cached or TestStatus.Flaky); - if (kind == BuildKind.Coverage) - { - var reported = await CoverageReport.WriteAsync(planner, chooser, tests, reporter, cancel).ConfigureAwait(false); - return passed && reported ? 0 : 1; - } - - return passed ? 0 : 1; - case BuildKind.Run: - if (!built) - { - return 1; - } - - var (target, products) = planned[0]; - var runfiles = Runfiles.Prepare(target, products, planner.Layout); - var environment = Processes.Inherited(); - var settings = (IRunSettings)target.Settings; - foreach (var (name, value) in settings.EnvironmentVariables) - { - environment[name] = value; - } - - Runfiles.AddLibraryPath(environment, products, planner.Layout); - var command = new List<string> { planner.Layout.Full(products.Executable!) }; - command.AddRange(settings.Arguments); - command.AddRange(programArguments ?? []); - return Processes.RunAttached(command, runfiles, environment); - default: - if (!built) - { - reporter.Error(ErrorCodes.ActionsFailed, $"{executor.Failed} action{(executor.Failed == 1 ? "" : "s")} failed", "the FAILED lines above say what each one printed; --keep-going shows every failure at once", - Dsl.Custom.Jokes.ForProject($"{executor.Failed}")); - return 1; - } - - reporter.Success($"built {selected.Count} target{(selected.Count == 1 ? "" : "s")}"); - return 0; + environment[name] = value; } + + Runfiles.AddLibraryPath(environment, products, layout); + List<string> command = [layout.Full(products.Executable!), .. settings.Arguments, .. programArguments ?? []]; + return Processes.RunAttached(command, runfiles, environment); + } + + private int FinishBuild(Built built, int targets) + { + if (!built.Succeeded) + { + var failed = built.Executor.Failed; + reporter.Error(ErrorCodes.ActionsFailed, $"{failed} action{(failed == 1 ? "" : "s")} failed", + "the FAILED lines above say what each one printed; --keep-going shows every failure at once", + Dsl.Custom.Jokes.ForProject($"{failed}")); + return 1; + } + + reporter.Success($"built {targets} target{(targets == 1 ? "" : "s")}"); + return 0; } } diff --git a/src/Progmasoft.Tazel/Driver/CCPlanner.cs b/src/Progmasoft.Tazel/Driver/CCPlanner.cs index d20c164..3810044 100644 --- a/src/Progmasoft.Tazel/Driver/CCPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/CCPlanner.cs @@ -39,32 +39,67 @@ internal sealed partial class Planner _ => null, }; + /// <summary>What every compilation of one target shares.</summary> + private sealed record CompileContext( + ProjectTarget Target, CCSettings Settings, CCToolchain Toolchain, IReadOnlyList<Feature> Features, + List<string> Includes, List<string> Defines, List<string> HeaderInputs, List<BuildAction> HeaderActions, + string ObjectsDirectory, string PackageRoot, bool Pic, IObjectiveCSettings? ObjC, HashSet<string> NonArc); + private TargetProducts PlanCC(ProjectTarget target) { var settings = (CCSettings)target.Settings; var toolchain = Toolchains.CC(target.Family); var products = new TargetProducts(); - var moduleRoot = FileSets.ToRoot(target.Module.Root, Layout.MainRoot); var sources = FileSets.Resolve(settings.Sources, target.PackageDirectory, Layout.MainRoot, target.Place); + var context = ContextOf(target, settings, toolchain, products); + var objects = new List<string>(); + var compiles = new List<BuildAction>(); + foreach (var source in sources.Concat(context.NonArc.Where(file => !sources.Contains(file)))) + { + if (Compile(context, source) is { } compile) + { + compiles.Add(compile); + objects.Add(compile.Outputs[0]); + } + } + + products.LinkTail.AddRange(settings.LinkerOptions); + products.LinkTail.AddRange(settings.SdkFrameworks.SelectMany(framework => new[] { "-framework", framework })); + products.LinkTail.AddRange(settings.WeakSdkFrameworks.SelectMany(framework => new[] { "-weak_framework", framework })); + products.LinkTail.AddRange(settings.SdkDynamicLibraries.Select(library => "-l" + library)); + var directory = Layout.PackageOut(target); + if (target.Kind == TargetKind.StaticLibrary) + { + PlanArchive(target, toolchain, context.Features, products, directory, objects, compiles); + } + else + { + PlanLink(target, toolchain, context.Features, products, directory, objects, compiles, + shared: target.Kind == TargetKind.SharedLibrary); + } + + return products; + } + + /// <summary> + /// The includes, macros and headers of a target and of what it depends on; dependents see its headers below the + /// root of its module and below its include directories. + /// </summary> + private CompileContext ContextOf(ProjectTarget target, CCSettings settings, CCToolchain toolchain, TargetProducts products) + { var headers = FileSets.Resolve(settings.Headers, target.PackageDirectory, Layout.MainRoot, target.Place) .Concat(FileSets.Resolve(settings.TextualHeaders, target.PackageDirectory, Layout.MainRoot, target.Place)) .ToList(); - var ownIncludes = settings.IncludeDirectories - .Select(directory => FileSets.PathIn(directory, target.PackageDirectory, Layout.MainRoot, target.Place, mustExist: true)) - .ToList(); - - // Dependents see this target's headers below the root of its module, and below its include directories. - products.PublicIncludes.Add(moduleRoot); - products.PublicIncludes.AddRange(ownIncludes); + products.PublicIncludes.Add(FileSets.ToRoot(target.Module.Root, Layout.MainRoot)); + products.PublicIncludes.AddRange(settings.IncludeDirectories + .Select(directory => FileSets.PathIn(directory, target.PackageDirectory, Layout.MainRoot, target.Place, mustExist: true))); products.PublicDefines.AddRange(settings.PreprocessorDefinitions); products.PublicHeaders.AddRange(headers); var includes = new List<string>(products.PublicIncludes); var defines = new List<string>(settings.PreprocessorDefinitions); var headerInputs = new List<string>(headers); - var headerActions = new List<BuildAction>(); - foreach (var dependency in Closure(target)) + foreach (var planned in Closure(target).Select(Plan)) { - var planned = Plan(dependency); Add(products.PublicIncludes, planned.PublicIncludes); Add(products.PublicDefines, planned.PublicDefines); Add(products.PublicHeaders, planned.PublicHeaders); @@ -74,7 +109,6 @@ internal sealed partial class Planner Add(includes, products.PublicIncludes); Add(defines, products.PublicDefines); Add(headerInputs, products.PublicHeaders); - headerActions.AddRange(products.HeaderActions); defines.AddRange(settings.LocalPreprocessorDefinitions); if (settings is CCExecutableSettings { StampBuildInformation: true }) { @@ -82,119 +116,122 @@ internal sealed partial class Planner defines.Add($"TAZEL_BUILD_VERSION=\"{target.Module.Info.Version}\""); } - var features = EnabledFeatures(target, toolchain, settings.Features); - var directory = Layout.PackageOut(target); - var objectsDirectory = $"{directory}/_objs/{target.Label.Name}"; - var packageRoot = FileSets.ToRoot(target.PackageDirectory, Layout.MainRoot); - var pic = target.Kind != TargetKind.Executable && target.Kind != TargetKind.Test && - Options.Platform.GetOS() != OS.Windows; var objc = settings as IObjectiveCSettings; var nonArc = objc is null ? new HashSet<string>(StringComparer.Ordinal) : FileSets.Resolve(objc.NonAutomaticReferenceCountingSources, target.PackageDirectory, Layout.MainRoot, target.Place) .ToHashSet(StringComparer.Ordinal); - var objects = new List<string>(); - var compiles = new List<BuildAction>(); - foreach (var source in sources.Concat(nonArc.Where(file => !sources.Contains(file)))) + var pic = target.Kind is not (TargetKind.Executable or TargetKind.Test) && Options.Platform.GetOS() != OS.Windows; + return new CompileContext(target, settings, toolchain, EnabledFeatures(target, toolchain, settings.Features), includes, defines, + headerInputs, [.. products.HeaderActions], $"{Layout.PackageOut(target)}/_objs/{target.Label.Name}", + FileSets.ToRoot(target.PackageDirectory, Layout.MainRoot), pic, objc, nonArc); + } + + /// <summary>The compilation of one source, or null for a header, which later compilations read.</summary> + private BuildAction? Compile(CompileContext context, string source) + { + var target = context.Target; + var language = LanguageOf(source) ?? throw new ProjectException( + $"{target.Place}: {target.Label} cannot compile '{source}'; its extension is not C, C++, Objective-C or assembly"); + if (language == SourceLanguage.Header) { - var language = LanguageOf(source) ?? throw new ProjectException( - $"{target.Place}: {target.Label} cannot compile '{source}'; its extension is not C, C++, Objective-C or assembly"); - if (language == SourceLanguage.Header) - { - headerInputs.Add(source); - continue; - } + context.HeaderInputs.Add(source); + return null; + } - if (language is SourceLanguage.ObjectiveC or SourceLanguage.ObjectiveCpp && target.Family != Family.ObjectiveC) - { - throw new ProjectException($"{target.Place}: '{source}' is Objective-C; declare {target.Label} with ObjectiveC"); - } + if (language is SourceLanguage.ObjectiveC or SourceLanguage.ObjectiveCpp && target.Family != Family.ObjectiveC) + { + throw new ProjectException($"{target.Place}: '{source}' is Objective-C; declare {target.Label} with ObjectiveC"); + } - var relative = source.StartsWith(packageRoot + "/", StringComparison.Ordinal) ? source[(packageRoot.Length + 1)..] : source; - var objectFile = $"{objectsDirectory}/{relative}.o"; - var cxx = language is SourceLanguage.Cpp or SourceLanguage.ObjectiveCpp; - var action = language switch - { - SourceLanguage.C => CCAction.CCompile, - SourceLanguage.Cpp => CCAction.CppCompile, - SourceLanguage.ObjectiveC => CCAction.ObjectiveCCompile, - SourceLanguage.ObjectiveCpp => CCAction.ObjectiveCppCompile, - _ => CCAction.Assemble, - }; - var command = new List<string>((cxx ? toolchain.Cpp : toolchain.C).Command); - command.AddRange(ModeFlags()); - command.AddRange(Flags(features, action)); - if (pic) - { - command.Add("-fPIC"); - } + var relative = source.StartsWith(context.PackageRoot + "/", StringComparison.Ordinal) ? source[(context.PackageRoot.Length + 1)..] : source; + var objectFile = $"{context.ObjectsDirectory}/{relative}.o"; + var cxx = language is SourceLanguage.Cpp or SourceLanguage.ObjectiveCpp; + var settings = context.Settings; + var command = new List<string>((cxx ? context.Toolchain.Cpp : context.Toolchain.C).Command); + command.AddRange(ModeFlags()); + command.AddRange(Flags(context.Features, ActionOf(language))); + if (context.Pic) + { + command.Add("-fPIC"); + } - command.AddRange(includes.Select(include => "-I" + include)); - command.AddRange(defines.Select(define => "-D" + define)); - command.AddRange(settings.CompilerOptions); - command.AddRange(cxx ? settings.CppCompilerOptions : settings.CCompilerOptions); - if (objc is not null && language is SourceLanguage.ObjectiveC or SourceLanguage.ObjectiveCpp) - { - command.Add(nonArc.Contains(source) ? "-fno-objc-arc" : "-fobjc-arc"); - } + command.AddRange(context.Includes.Select(include => "-I" + include)); + command.AddRange(context.Defines.Select(define => "-D" + define)); + command.AddRange(settings.CompilerOptions); + command.AddRange(cxx ? settings.CppCompilerOptions : settings.CCompilerOptions); + command.AddRange(ObjectiveCFlags(context, language, source)); + command.AddRange(CoverageFlags(context)); + command.AddRange(Options.CompilerOptions); + command.AddRange(cxx ? Options.CppCompilerOptions : Options.CCompilerOptions); + command.AddRange(["-MD", "-MF", objectFile + ".d", "-c", source, "-o", objectFile]); + var compile = new BuildAction + { + Description = $"Compiling {target.Label} {relative}", + Command = command, + Directory = Layout.MainRoot, + Inputs = context.HeaderInputs.Prepend(source).Distinct(StringComparer.Ordinal).ToList(), + Outputs = [objectFile], + Environment = ActionEnvironment, + Depfile = objectFile + ".d", + }; + compile.Prerequisites.AddRange(context.HeaderActions); + return compile; + } - if (objc is { EnableClangModules: true }) - { - command.Add("-fmodules"); - if (objc.ModuleName is { } moduleName) - { - command.Add($"-fmodule-name={moduleName}"); - } - - if (objc.ModuleMap is { } map) - { - command.Add("-fmodule-map-file=" + - FileSets.PathIn(map, target.PackageDirectory, Layout.MainRoot, target.Place, mustExist: true)); - } - } + private static CCAction ActionOf(SourceLanguage language) => language switch + { + SourceLanguage.C => CCAction.CCompile, + SourceLanguage.Cpp => CCAction.CppCompile, + SourceLanguage.ObjectiveC => CCAction.ObjectiveCCompile, + SourceLanguage.ObjectiveCpp => CCAction.ObjectiveCppCompile, + _ => CCAction.Assemble, + }; - if (Options.Coverage) - { - RequireClang(toolchain, target); - command.AddRange(["-fprofile-instr-generate", "-fcoverage-mapping"]); - } + /// <summary>Automatic reference counting per file, and clang modules, for an Objective-C target.</summary> + private List<string> ObjectiveCFlags(CompileContext context, SourceLanguage language, string source) + { + var flags = new List<string>(); + var objc = context.ObjC; + if (objc is null) + { + return flags; + } - command.AddRange(Options.CompilerOptions); - command.AddRange(cxx ? Options.CppCompilerOptions : Options.CCompilerOptions); - command.AddRange(["-MD", "-MF", objectFile + ".d", "-c", source, "-o", objectFile]); - var compile = new BuildAction - { - Description = $"Compiling {target.Label} {relative}", - Command = command, - Directory = Layout.MainRoot, - Inputs = headerInputs.Prepend(source).Distinct(StringComparer.Ordinal).ToList(), - Outputs = [objectFile], - Environment = ActionEnvironment, - Depfile = objectFile + ".d", - }; - compile.Prerequisites.AddRange(headerActions); - compiles.Add(compile); - objects.Add(objectFile); + if (language is SourceLanguage.ObjectiveC or SourceLanguage.ObjectiveCpp) + { + flags.Add(context.NonArc.Contains(source) ? "-fno-objc-arc" : "-fobjc-arc"); } - products.LinkTail.AddRange(settings.LinkerOptions); - products.LinkTail.AddRange(settings.SdkFrameworks.SelectMany(framework => new[] { "-framework", framework })); - products.LinkTail.AddRange(settings.WeakSdkFrameworks.SelectMany(framework => new[] { "-weak_framework", framework })); - products.LinkTail.AddRange(settings.SdkDynamicLibraries.Select(library => "-l" + library)); - switch (target.Kind) + if (!objc.EnableClangModules) { - case TargetKind.StaticLibrary: - PlanArchive(target, toolchain, features, products, directory, objects, compiles); - break; - case TargetKind.SharedLibrary: - PlanLink(target, toolchain, features, products, directory, objects, compiles, shared: true); - break; - default: - PlanLink(target, toolchain, features, products, directory, objects, compiles, shared: false); - break; + return flags; } - return products; + flags.Add("-fmodules"); + if (objc.ModuleName is { } moduleName) + { + flags.Add($"-fmodule-name={moduleName}"); + } + + if (objc.ModuleMap is { } map) + { + var target = context.Target; + flags.Add("-fmodule-map-file=" + FileSets.PathIn(map, target.PackageDirectory, Layout.MainRoot, target.Place, mustExist: true)); + } + + return flags; + } + + private string[] CoverageFlags(CompileContext context) + { + if (!Options.Coverage) + { + return []; + } + + RequireClang(context.Toolchain, context.Target); + return ["-fprofile-instr-generate", "-fcoverage-mapping"]; } private void PlanArchive( diff --git a/src/Progmasoft.Tazel/Driver/Executor.cs b/src/Progmasoft.Tazel/Driver/Executor.cs index e52b24a..d754137 100644 --- a/src/Progmasoft.Tazel/Driver/Executor.cs +++ b/src/Progmasoft.Tazel/Driver/Executor.cs @@ -28,6 +28,30 @@ internal sealed class Executor(int jobs, bool keepGoing, ActionCache cache, Repo /// <summary>How many actions failed.</summary> public int Failed => _failed; + /// <summary> + /// Whether <paramref name="action"/> failed: its program said so, or an output it should have written is not there. + /// A failure is reported, and stops the build unless it keeps going. + /// </summary> + private async Task<bool> FailedAsync(BuildAction action, ProcessResult result, CancellationTokenSource stop) + { + var missing = action.Outputs.FirstOrDefault(output => !File.Exists(action.Full(output))); + if (result.ExitCode == 0 && missing is null) + { + return false; + } + + var hint = missing is not null && action.MissingOutputHints.TryGetValue(missing, out var said) ? $"; {said}" : ""; + var output = result.ExitCode == 0 ? result.Output + $"{missing} was not written{hint}\n" : result.Output; + Interlocked.Increment(ref _failed); + reporter.ActionFailed(action.Description, action.Command, output); + if (!keepGoing) + { + await stop.CancelAsync().ConfigureAwait(false); + } + + return true; + } + /// <summary>Runs <paramref name="goals"/> and what they need; true when all of them were made.</summary> public async Task<bool> RunAsync(IReadOnlyCollection<BuildAction> goals, CancellationToken cancel) { @@ -81,24 +105,9 @@ internal sealed class Executor(int jobs, bool keepGoing, ActionCache cache, Repo ? await work(stop.Token).ConfigureAwait(false) : await Processes.RunAsync(action.Command, action.Directory, action.Environment, null, stop.Token) .ConfigureAwait(false); - if (result.Canceled) + // Stopped because another action failed: that one is reported, this one did not fail. + if (result.Canceled || await FailedAsync(action, result, stop).ConfigureAwait(false)) { - // Stopped because another action failed: that one is reported, this one did not fail. - return false; - } - - var missing = action.Outputs.FirstOrDefault(output => !File.Exists(action.Full(output))); - if (result.ExitCode != 0 || missing is not null) - { - var hint = missing is not null && action.MissingOutputHints.TryGetValue(missing, out var said) ? $"; {said}" : ""; - var output = result.ExitCode == 0 ? result.Output + $"{missing} was not written{hint}\n" : result.Output; - Interlocked.Increment(ref _failed); - reporter.ActionFailed(action.Description, action.Command, output); - if (!keepGoing) - { - await stop.CancelAsync().ConfigureAwait(false); - } - return false; } diff --git a/src/Progmasoft.Tazel/Driver/Planner.cs b/src/Progmasoft.Tazel/Driver/Planner.cs index dc6ad9e..f73598d 100644 --- a/src/Progmasoft.Tazel/Driver/Planner.cs +++ b/src/Progmasoft.Tazel/Driver/Planner.cs @@ -140,6 +140,25 @@ internal sealed partial class Planner } } + /// <summary>A library on the link line; one linked whole is wrapped so that none of its objects is dropped.</summary> + 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"]; + + /// <summary>Where a program finds a shared library at run time, relative to itself; Windows has no run path.</summary> + 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}"], + }; + } + /// <summary>The linker arguments for the libraries of <paramref name="target"/>, and the actions that make them.</summary> private (List<string> Arguments, List<string> Inputs, List<BuildAction> Actions, List<string> SharedDirectories) LinkLibraries(ProjectTarget target, string outputDirectory, bool forZig = false) @@ -160,42 +179,20 @@ internal sealed partial class Planner if (products.Library is { } library) { inputs.Add(library); - if (products.AlwaysLink && !products.IsShared && !forZig) - { - arguments.AddRange(os == OS.MacOS - ? [$"-Wl,-force_load,{library}"] - : ["-Wl,--whole-archive", library, "-Wl,--no-whole-archive"]); - } - else + arguments.AddRange(LibraryArguments(library, products.AlwaysLink && !products.IsShared && !forZig, os)); + var directory = Path.GetDirectoryName(library)!.Replace('\\', '/'); + if (products.IsShared && !sharedDirectories.Contains(directory)) { - arguments.Add(library); - } - - if (products.IsShared) - { - var directory = Path.GetDirectoryName(library)!.Replace('\\', '/'); - if (!sharedDirectories.Contains(directory)) - { - sharedDirectories.Add(directory); - } + sharedDirectories.Add(directory); } } tail.AddRange(products.LinkTail); } - foreach (var directory in forZig ? [] : sharedDirectories) + if (!forZig) { - var relative = Path.GetRelativePath(outputDirectory, directory).Replace('\\', '/'); - var suffix = relative == "." ? "" : "/" + relative; - if (os == OS.MacOS) - { - arguments.Add($"-Wl,-rpath,@loader_path{suffix}"); - } - else if (os != OS.Windows) - { - arguments.Add($"-Wl,-rpath,$ORIGIN{suffix}"); - } + arguments.AddRange(sharedDirectories.SelectMany(directory => RunPath(outputDirectory, directory, os))); } arguments.AddRange(tail); diff --git a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs index fffc4e8..d16329c 100644 --- a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs @@ -33,6 +33,81 @@ internal sealed partial class Planner private static string OptimizationName(ZigOptimization optimization) => optimization.ToString(); + /// <summary>The file a Zig target makes, and what it tells dependents.</summary> + private (string Output, Action? After) ZigOutput( + ProjectTarget target, ZigCompiledSettings settings, TargetProducts products, string directory, List<string> command) + { + if (target.Kind == TargetKind.StaticLibrary) + { + var library = $"{directory}/{StaticLibraryName(target.Label.Name)}"; + products.Library = library; + return (library, null); + } + + if (target.Kind != TargetKind.SharedLibrary) + { + var program = $"{directory}/{ExecutableName(target.Label.Name)}"; + products.Executable = program; + return (program, null); + } + + var version = ((ZigSharedLibrarySettings)settings).LibraryVersion; + var (file, linkWith, soname) = SharedLibraryNames(directory, target.Label.Name, version); + products.Library = linkWith; + products.IsShared = true; + if (soname is not null && Options.Platform.GetOS() != OS.Windows) + { + command.Add($"-fsoname={soname}"); + } + + return (file, SonameLinks(file, soname, target.Label.Name)); + } + + /// <summary>The switches of the settings: libc, stripping, LTO and the test filter.</summary> + private static List<string> Switches(ZigCompiledSettings settings) + { + var switches = new List<string>(); + switches.AddRange(settings.LinkCStandardLibrary ? ["-lc"] : []); + switches.AddRange(settings.StripSymbols ? ["-fstrip"] : []); + switches.AddRange(settings.LinkTimeOptimization ? ["-flto"] : []); + if (settings is ZigTestSettings test) + { + switches.AddRange(test.TestFilter is { } filter ? ["--test-filter", filter] : []); + switches.Add("--test-no-exec"); + } + + return switches; + } + + /// <summary> + /// The root module and those it imports: per-module options come before the -M of the module they belong to, + /// the root module first. Returns the files they read. + /// </summary> + private List<string> AddModules( + ProjectTarget target, ZigCompiledSettings settings, ZigOptimization defaultOptimization, List<string> includeDirectories, + List<string> command) + { + var inputs = new List<string>(); + command.AddRange(ModuleOptions(target, settings, settings.OptimizationMode ?? defaultOptimization, inputs, includeDirectories)); + var cSources = FileSets.Resolve(settings.CSources, target.PackageDirectory, Layout.MainRoot, target.Place); + AddCSources(command, settings, cSources); + inputs.AddRange(cSources); + var modules = ImportedModules(target); + var names = ModuleNames(modules); + command.AddRange(target.ZigImports.SelectMany(entry => new[] { "--dep", $"{entry.Key}={names[entry.Value]}" })); + command.Add($"-Mroot={RootFile(target)}"); + foreach (var module in modules) + { + var moduleSettings = (ZigModuleSettings)module.Settings; + command.AddRange(ModuleOptions(module, moduleSettings, + moduleSettings.OptimizationMode ?? settings.OptimizationMode ?? defaultOptimization, inputs, [])); + command.AddRange(module.ZigImports.SelectMany(entry => new[] { "--dep", $"{entry.Key}={names[entry.Value]}" })); + command.Add($"-M{names[module]}={RootFile(module)}"); + } + + return inputs; + } + private TargetProducts PlanZig(ProjectTarget target) { var products = new TargetProducts(); @@ -61,36 +136,9 @@ internal sealed partial class Planner } command.AddRange(["--cache-dir", Layout.ZigCache]); - string output; - Action? after = null; - var outputs = new List<string>(); - switch (target.Kind) - { - case TargetKind.StaticLibrary: - output = $"{directory}/{StaticLibraryName(target.Label.Name)}"; - products.Library = output; - break; - case TargetKind.SharedLibrary: - var version = ((ZigSharedLibrarySettings)settings).LibraryVersion; - var (file, linkWith, soname) = SharedLibraryNames(directory, target.Label.Name, version); - output = file; - products.Library = linkWith; - products.IsShared = true; - if (soname is not null && Options.Platform.GetOS() != OS.Windows) - { - command.Add($"-fsoname={soname}"); - } - - after = SonameLinks(file, soname, target.Label.Name); - break; - default: - output = $"{directory}/{ExecutableName(target.Label.Name)}"; - products.Executable = output; - break; - } - + var (output, after) = ZigOutput(target, settings, products, directory, command); command.Add($"-femit-bin={output}"); - outputs.Add(output); + var outputs = new List<string> { output }; var emitHeader = settings switch { ZigStaticLibrarySettings library => library.EmitHeader, @@ -105,31 +153,7 @@ internal sealed partial class Planner products.PublicIncludes.Add(Path.GetDirectoryName(header)!.Replace('\\', '/')); } - if (settings.LinkCStandardLibrary) - { - command.Add("-lc"); - } - - if (settings.StripSymbols) - { - command.Add("-fstrip"); - } - - if (settings.LinkTimeOptimization) - { - command.Add("-flto"); - } - - if (settings is ZigTestSettings test) - { - if (test.TestFilter is { } filter) - { - command.AddRange(["--test-filter", filter]); - } - - command.Add("--test-no-exec"); - } - + command.AddRange(Switches(settings)); command.AddRange(settings.ZigCompilerOptions); command.AddRange(Options.ZigCompilerOptions); @@ -152,32 +176,7 @@ internal sealed partial class Planner command.AddRange(settings.LinkerOptions); command.AddRange(Options.LinkerOptions); - // Per-module options come before the -M of the module they belong to: first the root module. - var inputs = new List<string>(); - command.AddRange(ModuleOptions(target, settings, settings.OptimizationMode ?? defaultOptimization, inputs, includeDirectories)); - var cSources = FileSets.Resolve(settings.CSources, target.PackageDirectory, Layout.MainRoot, target.Place); - AddCSources(command, settings, cSources); - inputs.AddRange(cSources); - var modules = ImportedModules(target); - var names = ModuleNames(modules); - foreach (var (import, module) in target.ZigImports) - { - command.AddRange(["--dep", $"{import}={names[module]}"]); - } - - command.Add($"-Mroot={RootFile(target)}"); - foreach (var module in modules) - { - var moduleSettings = (ZigModuleSettings)module.Settings; - command.AddRange(ModuleOptions(module, moduleSettings, - moduleSettings.OptimizationMode ?? settings.OptimizationMode ?? defaultOptimization, inputs, [])); - foreach (var (import, imported) in module.ZigImports) - { - command.AddRange(["--dep", $"{import}={names[imported]}"]); - } - - command.Add($"-M{names[module]}={RootFile(module)}"); - } + var inputs = AddModules(target, settings, defaultOptimization, includeDirectories, command); var action = new BuildAction {