Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git

kumo_builder.cpp (77149B) · raw


      1 /// @file kumo_builder.cpp
      2 /// @brief The Kumo builder: the build script is itself a C++ program.
      3 ///
      4 /// Supported platforms: macOS, Linux and Windows (clang++ must be on `PATH`).
      5 /// The builder is built on the machine that uses it, so the host is also the
      6 /// target; cross-compilation is not supported.
      7 ///
      8 /// How the project is organized and compiled is described by `kumo.toml` in the
      9 /// project root, see "Project configuration" below; this file only holds the
     10 /// logic.
     11 ///
     12 /// Bootstrap (once, from the project root):
     13 /// @code
     14 ///    clang++ -std=c++20 kumo_builder.cpp -o kumoko        # macOS, Linux
     15 ///    clang++ -std=c++20 kumo_builder.cpp -o kumoko.exe    # Windows
     16 /// @endcode
     17 ///
     18 /// Usage (always from the project root; on Windows type `kumoko` without the
     19 /// leading `./`):
     20 /// @code
     21 ///    ./kumoko                # incremental build
     22 ///    ./kumoko run            # incremental build, then run the executable
     23 ///    ./kumoko test [name]    # build and run the tests, only those whose name
     24 ///                            # contains `name` if one is given
     25 ///    ./kumoko clean          # delete all build output
     26 ///    ./kumoko help           # show the usage; also -h and --help
     27 ///    ./kumoko -v ...         # print full commands
     28 ///    ./kumoko -q test        # one line per test program, not per test case
     29 /// @endcode
     30 ///
     31 /// Output is colored when it goes to a terminal; set `NO_COLOR` to turn that
     32 /// off. The exit status is 0 on success, 1 if building or a test failed (or the
     33 /// status of the program that `run` ran), and 2 for a mistake on the command
     34 /// line.
     35 ///
     36 /// Platform-specific source files are marked by their name, see
     37 /// is_built_here().
     38 ///
     39 /// @note There is no need to bootstrap again after editing this file: on the
     40 ///       next run the builder notices it is out of date and recompiles itself.
     41 ///       Editing `kumo.toml` needs no bootstrap either; it recompiles the
     42 ///       project.
     43 
     44 #if defined(_WIN32)
     45 #define WIN32_LEAN_AND_MEAN
     46 #define NOMINMAX
     47 #include <io.h>
     48 #include <windows.h>
     49 #else
     50 #include <spawn.h>
     51 #include <sys/wait.h>
     52 #include <unistd.h>
     53 #endif
     54 
     55 #include <algorithm>
     56 #include <cctype>
     57 #include <cerrno>
     58 #include <chrono>
     59 #include <cstddef>
     60 #include <cstdint>
     61 #include <cstdio>
     62 #include <cstdlib>
     63 #include <cstring>
     64 #include <filesystem>
     65 #include <fstream>
     66 #include <map>
     67 #include <sstream>
     68 #include <string>
     69 #include <string_view>
     70 #include <system_error>
     71 #include <thread>
     72 #include <vector>
     73 
     74 #if !defined(_WIN32)
     75 /// @brief The environment of the current process, provided by libc.
     76 ///
     77 /// Passed unchanged to every child process.
     78 extern char** environ;
     79 #endif
     80 
     81 namespace fs = std::filesystem;
     82 
     83 /// @brief A command as an argument list; element 0 is the program name.
     84 ///
     85 /// Commands are never joined into one string for a shell to parse, so paths
     86 /// containing spaces or quotes need no escaping.
     87 using Cmd = std::vector<std::string>;
     88 
     89 /// @name Builder constants
     90 /// What belongs to the builder itself. The settings of the project it builds
     91 /// live in `kumo.toml`, see "Project configuration".
     92 /// @{
     93 
     94 /// @brief Operating systems the builder knows about.
     95 enum class Platform { Mac, Linux, Windows };
     96 
     97 /// @brief The platform being built for.
     98 #if defined(__APPLE__)
     99 static constexpr Platform HOST = Platform::Mac;
    100 #elif defined(__linux__)
    101 static constexpr Platform HOST = Platform::Linux;
    102 #elif defined(_WIN32)
    103 static constexpr Platform HOST = Platform::Windows;
    104 #else
    105 #error "kumo_builder supports only macOS, Linux and Windows"
    106 #endif
    107 
    108 /// @brief The name of #HOST in `kumo.toml`, as a table header.
    109 static constexpr const char* HOST_NAME = HOST == Platform::Mac     ? "mac"
    110                                          : HOST == Platform::Linux ? "linux"
    111                                                                    : "windows";
    112 
    113 /// @brief File name extension of executables on this platform.
    114 static constexpr const char* EXE_SUFFIX =
    115     HOST == Platform::Windows ? ".exe" : "";
    116 
    117 /// @brief The compiler that rebuilds the builder itself.
    118 ///
    119 /// Fixed, because it is needed before `kumo.toml` is read. The compiler of the
    120 /// project is the `compiler` key of that file.
    121 static const char* const SELF_CXX = "clang++";
    122 static const fs::path SELF_SRC = "kumo_builder.cpp";
    123 
    124 /// @brief Path of the builder's own executable.
    125 ///
    126 /// A fixed name instead of `argv[0]`, because on Windows the user may type
    127 /// `kumoko` without the `.exe` that the file actually has.
    128 static const fs::path SELF_EXE = std::string("kumoko") + EXE_SUFFIX;
    129 
    130 /// @brief Where the running builder is moved to while it replaces itself.
    131 ///
    132 /// Windows refuses to overwrite a running executable but allows renaming it.
    133 static const fs::path SELF_OLD_EXE = std::string("kumoko.old") + EXE_SUFFIX;
    134 
    135 /// @brief The project configuration file, in the project root.
    136 static const fs::path CONFIG_FILE = "kumo.toml";
    137 
    138 /// @}
    139 
    140 /// @name Terminal output
    141 /// How the builder talks to the person at the terminal: colors, labels in a
    142 /// fixed column, durations, and errors.
    143 /// @{
    144 
    145 /// @brief Whether messages are colored. Set once by init_terminal().
    146 static bool color_enabled = false;
    147 
    148 /// @brief Whether commands are printed in full. Set by `-v` or `--verbose`.
    149 static bool verbose = false;
    150 
    151 /// @brief Whether `test` shows one line per test program instead of one per
    152 ///        test case. Set by `-q` or `--quiet`.
    153 static bool quiet = false;
    154 
    155 /// @brief The colors a message can have.
    156 enum class Style { Plain, Dim, Red, Green, Cyan };
    157 
    158 /// @brief Decides whether to use colors.
    159 ///
    160 /// Only when standard output is a terminal, and `NO_COLOR` is not set (see
    161 /// https://no-color.org). On Windows the terminal must also accept escape
    162 /// codes, which this turns on.
    163 static void init_terminal() {
    164   const char* no_color = std::getenv("NO_COLOR");
    165   if (no_color != nullptr && no_color[0] != '\0') return;
    166 #if defined(_WIN32)
    167   if (!_isatty(_fileno(stdout))) return;
    168   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
    169   DWORD mode = 0;
    170   if (out == INVALID_HANDLE_VALUE || !GetConsoleMode(out, &mode)) return;
    171   if (!SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) return;
    172   color_enabled = true;
    173 #else
    174   color_enabled = isatty(STDOUT_FILENO) != 0;
    175 #endif
    176 }
    177 
    178 /// @brief Wraps @p text in the escape codes of @p style, if colors are on.
    179 static std::string paint(Style style, const std::string& text) {
    180   if (!color_enabled || style == Style::Plain) return text;
    181   const char* code = "0";
    182   switch (style) {
    183     case Style::Dim:
    184       code = "2";
    185       break;
    186     case Style::Red:
    187       code = "31";
    188       break;
    189     case Style::Green:
    190       code = "32";
    191       break;
    192     case Style::Cyan:
    193       code = "36";
    194       break;
    195     case Style::Plain:
    196       break;
    197   }
    198   return std::string("\033[") + code + "m" + text + "\033[0m";
    199 }
    200 
    201 /// @brief Pads @p text on the right with spaces up to @p width characters.
    202 static std::string pad(const std::string& text, size_t width) {
    203   return text.size() >= width ? text
    204                               : text + std::string(width - text.size(), ' ');
    205 }
    206 
    207 /// @brief Pads @p text with spaces on the left up to @p width characters.
    208 static std::string pad_left(const std::string& text, size_t width) {
    209   return text.size() >= width ? text
    210                               : std::string(width - text.size(), ' ') + text;
    211 }
    212 
    213 /// @brief "1 test program" or "3 test programs".
    214 static std::string plural(size_t count, const std::string& noun) {
    215   return std::to_string(count) + " " + noun + (count == 1 ? "" : "s");
    216 }
    217 
    218 /// @brief Prints one line of progress: a label in a fixed column, then a text,
    219 ///        then an optional note in a dimmer color.
    220 ///
    221 /// @code
    222 ///     compile  src/main.cpp  [1/3]
    223 ///     link     build/kumo
    224 /// @endcode
    225 static void log_step(Style style, const std::string& label,
    226                      const std::string& text, const std::string& note = "") {
    227   std::string line = paint(style, pad(label, 8)) + " " + text;
    228   if (!note.empty()) line += "  " + paint(Style::Dim, note);
    229   std::printf("%s\n", line.c_str());
    230 }
    231 
    232 /// @brief The width of the lines drawn between test programs: that of the
    233 ///        longest line a test case takes, see `kNameWidth` in tests/check.h.
    234 constexpr size_t kRuleWidth = 75;
    235 
    236 /// @brief A dimmed line of @p fill characters, kRuleWidth wide, with the
    237 ///        @p title set into it if there is one:
    238 /// @code
    239 ///     -- unit/raster_test ---------------------------------------------------
    240 /// @endcode
    241 static std::string rule(char fill, const std::string& title = "") {
    242   if (title.empty()) return paint(Style::Dim, std::string(kRuleWidth, fill));
    243   const std::string lead(2, fill);
    244   const size_t used = lead.size() + 1 + title.size() + 1;
    245   const std::string tail(used < kRuleWidth ? kRuleWidth - used : 2, fill);
    246   return paint(Style::Dim, lead + " ") + paint(Style::Cyan, title) +
    247          paint(Style::Dim, " " + tail);
    248 }
    249 
    250 /// @brief Prints an error message on standard error.
    251 ///
    252 /// Standard output is flushed first, so that the message does not overtake
    253 /// lines printed before it when both go to the same place.
    254 static void print_error(const std::string& message) {
    255   std::fflush(stdout);
    256   std::fprintf(stderr, "%s %s\n", paint(Style::Red, "error:").c_str(),
    257                message.c_str());
    258 }
    259 
    260 /// @brief Formats a duration for people: `87 ms`, `1.24 s`, `2 min 3 s`.
    261 static std::string format_duration(std::chrono::steady_clock::duration time) {
    262   const auto ms =
    263       std::chrono::duration_cast<std::chrono::milliseconds>(time).count();
    264   char buffer[48];
    265   if (ms < 1000) {
    266     std::snprintf(buffer, sizeof(buffer), "%lld ms",
    267                   static_cast<long long>(ms));
    268   } else if (ms < 60000) {
    269     std::snprintf(buffer, sizeof(buffer), "%.2f s",
    270                   static_cast<double>(ms) / 1000.0);
    271   } else {
    272     std::snprintf(buffer, sizeof(buffer), "%lld min %lld s",
    273                   static_cast<long long>(ms / 60000),
    274                   static_cast<long long>(ms % 60000 / 1000));
    275   }
    276   return buffer;
    277 }
    278 
    279 /// @brief Prints a command on one line, dimmed, as `-v` does. Arguments with
    280 ///        spaces or quotes are put in quotes, which is for reading only.
    281 static void print_command(const Cmd& cmd) {
    282   std::string line = "$";
    283   for (const std::string& arg : cmd) {
    284     const bool plain =
    285         !arg.empty() && arg.find_first_of(" \t\"'") == std::string::npos;
    286     line += ' ';
    287     line += plain ? arg : "\"" + arg + "\"";
    288   }
    289   std::printf("  %s\n", paint(Style::Dim, line).c_str());
    290 }
    291 
    292 /// @}
    293 
    294 /// @name Project configuration
    295 /// Reading `kumo.toml`, which says how the project is organized and compiled.
    296 ///
    297 /// The file is a small subset of TOML (https://toml.io). The builder has no
    298 /// dependencies, so it parses the file itself, and accepts only this:
    299 /// - `#` starts a comment that runs to the end of the line;
    300 /// - `key = "text"` assigns a string; inside double quotes the only escapes
    301 ///   are a backslash followed by a backslash or by a double quote, and single
    302 ///   quotes take everything literally, backslashes included;
    303 /// - `key = ["a", "b"]` assigns a list of strings; it may span several lines,
    304 ///   end with a comma and contain comments;
    305 /// - `[mac]`, `[linux]` and `[windows]` start a table whose keys apply to that
    306 ///   platform only.
    307 ///
    308 /// Anything else (numbers, booleans, dates, inline tables, dotted keys,
    309 /// multi-line strings) is a syntax error. So is a key the builder does not
    310 /// know, so that a typo is never silently ignored.
    311 ///
    312 /// All top-level keys are optional:
    313 /// - `name`: name of the executable, without the `.exe` that Windows adds
    314 ///   (default: the name of the project directory);
    315 /// - `compiler`: the C++ compiler (default: `clang++`);
    316 /// - `src`: the source tree, searched recursively (default: `src`);
    317 /// - `out`: where all build output goes (default: `build`);
    318 /// - `entry`: the source file that holds `main` of the program (default:
    319 ///   `main.cpp` inside `src`); `test` mode leaves it out, because every test
    320 ///   program has a `main` of its own;
    321 /// - `tests`: the directory of test programs, see "Tests" (default: `tests`);
    322 /// - `flags`: compile flags for every source file;
    323 /// - `objcxx_flags`: extra compile flags for `.mm` files only;
    324 /// - `link`: link flags.
    325 ///
    326 /// A platform or profile table may hold `compiler`, `flags` and `link`. On that
    327 /// platform or profile `compiler` overrides the top-level setting, and
    328 /// `flags`/`link` are appended.
    329 /// A `[deps.name]` table declares a Git URL, a tag or full commit ID, and
    330 /// header directories relative to the dependency's checkout.
    331 /// @{
    332 
    333 /// @brief The source, revision and header directories of a Git dependency.
    334 struct Dependency {
    335   std::string name;
    336   std::string git;
    337   std::string rev;
    338   Cmd include_dirs;
    339 };
    340 
    341 /// @brief The settings of the project, as read from #CONFIG_FILE.
    342 ///
    343 /// Output layout, for `src = "src"`, `out = "build"`, `name = "kumo"` and the
    344 /// default `debug` profile:
    345 // clang-format off
    346 /// @code
    347 ///     build/debug/obj/src/foo/bar.cpp.o   object file (mirrors the source tree)
    348 ///     build/debug/obj/src/foo/bar.cpp.d   list of headers that file depends on
    349 ///     build/debug/kumo                    final executable (kumo.exe on Windows)
    350 /// @endcode
    351 // clang-format on
    352 struct Config {
    353   std::string compiler;
    354   fs::path src_dir;
    355   fs::path clean_dir;  ///< Root output directory deleted by `clean`.
    356   fs::path out_dir;    ///< Active profile directory inside #clean_dir.
    357   fs::path entry;      ///< The source file with `main`, inside #src_dir.
    358   fs::path tests_dir;  ///< Directory of test programs.
    359   fs::path exe;        ///< The final executable, inside #out_dir.
    360   Cmd flags;           ///< Compile flags, with platform and profile added.
    361   Cmd objcxx_flags;    ///< Extra compile flags for `.mm` files.
    362   Cmd link_flags;      ///< Link flags, with platform and profile added.
    363   std::vector<Dependency> dependencies;
    364 };
    365 
    366 /// @brief Reports a problem with #CONFIG_FILE and exits.
    367 ///
    368 /// @param line 1-based line the problem is on, or 0 if it is not about a line.
    369 /// @param msg  What is wrong.
    370 [[noreturn]] static void config_error(int line, const std::string& msg) {
    371   const std::string file = CONFIG_FILE.string();
    372   print_error(line > 0 ? file + ":" + std::to_string(line) + ": " + msg
    373                        : file + ": " + msg);
    374   std::exit(EXIT_FAILURE);
    375 }
    376 
    377 /// @brief The tables a platform can have, named like #HOST_NAME.
    378 static constexpr const char* PLATFORM_TABLES[] = {"mac", "linux", "windows"};
    379 /// @brief The profile tables supported in `kumo.toml`.
    380 static constexpr const char* PROFILE_TABLES[] = {"debug", "release", "asan"};
    381 static constexpr std::string_view DEPENDENCY_PREFIX = "deps.";
    382 static const fs::path DEPENDENCY_CACHE = ".cache/kumoko/deps";
    383 
    384 /// @brief One `key = value` pair of the file.
    385 struct Entry {
    386   bool is_list = false;  ///< Which of #text and #list holds the value.
    387   std::string text;
    388   Cmd list;
    389   int line = 0;  ///< Where the pair was written, for error messages.
    390 };
    391 
    392 /// @brief Every pair of the file; a key inside a table is stored as
    393 ///        `"table.key"`.
    394 using Table = std::map<std::string, Entry>;
    395 
    396 /// @brief Parser for the TOML subset described above.
    397 ///
    398 /// Reports a syntax error with config_error(), which exits.
    399 class ConfigParser {
    400  public:
    401   explicit ConfigParser(const std::string& text) : text_(text) {
    402     // Some Windows editors start a UTF-8 file with a byte order mark.
    403     if (text_.starts_with("\xEF\xBB\xBF")) text_.erase(0, 3);
    404   }
    405 
    406   /// @brief Parses the whole text.
    407   Table parse(std::map<std::string, int>& dependency_tables) {
    408     Table table;
    409     std::string section;  // the table being filled; empty at the top level
    410     std::vector<std::string> tables_seen;
    411     for (skip_blank(true); pos_ < text_.size(); skip_blank(true)) {
    412       if (text_[pos_] == '[') {
    413         const int line = line_here();
    414         section = parse_header();
    415         // A table may be opened only once, as in TOML, so that its keys are
    416         // never split over two places.
    417         if (std::find(tables_seen.begin(), tables_seen.end(), section) !=
    418             tables_seen.end()) {
    419           config_error(line_here(), "duplicate table '[" + section + "]'");
    420         }
    421         tables_seen.push_back(section);
    422         if (section.starts_with(DEPENDENCY_PREFIX)) {
    423           dependency_tables.emplace(section, line);
    424         }
    425       } else {
    426         parse_pair(section, table);
    427       }
    428     }
    429     return table;
    430   }
    431 
    432  private:
    433   std::string text_;
    434   size_t pos_ = 0;  // next character to read
    435 
    436   /// @brief The 1-based line @ref pos_ is on.
    437   int line_here() const {
    438     auto end = text_.begin() + static_cast<std::ptrdiff_t>(pos_);
    439     return 1 + static_cast<int>(std::count(text_.begin(), end, '\n'));
    440   }
    441 
    442   [[noreturn]] void fail(const std::string& msg) const {
    443     config_error(line_here(), msg);
    444   }
    445 
    446   /// @brief The next character, or a null character at the end of the text.
    447   char peek() const { return pos_ < text_.size() ? text_[pos_] : '\0'; }
    448 
    449   /// @brief Skips spaces, carriage returns and comments, and newlines too if
    450   ///        asked.
    451   ///
    452   /// A comment stops before its newline, so with @p newlines false the parser
    453   /// ends up at the end of the line.
    454   void skip_blank(bool newlines) {
    455     while (pos_ < text_.size()) {
    456       char c = text_[pos_];
    457       if (c == '#') {
    458         while (pos_ < text_.size() && text_[pos_] != '\n') ++pos_;
    459       } else if (c == ' ' || c == '\t' || c == '\r' ||
    460                  (newlines && c == '\n')) {
    461         ++pos_;
    462       } else {
    463         break;
    464       }
    465     }
    466   }
    467 
    468   /// @brief Requires that nothing but a comment is left on this line.
    469   void end_line() {
    470     skip_blank(false);
    471     if (pos_ < text_.size() && text_[pos_] != '\n') {
    472       fail("unexpected text at the end of the line");
    473     }
    474   }
    475 
    476   /// @brief Reads a key or table name: letters, digits, `_` and `-`.
    477   ///
    478   /// @param what What was expected, for the error message.
    479   std::string parse_name(const char* what) {
    480     size_t start = pos_;
    481     while (pos_ < text_.size() &&
    482            (std::isalnum(static_cast<unsigned char>(text_[pos_])) ||
    483             text_[pos_] == '_' || text_[pos_] == '-')) {
    484       ++pos_;
    485     }
    486     if (pos_ == start) fail(std::string("expected ") + what);
    487     return text_.substr(start, pos_ - start);
    488   }
    489 
    490   /// @brief Reads a `[name]` or `[deps.name]` table header.
    491   std::string parse_header() {
    492     ++pos_;  // '['
    493     skip_blank(false);
    494     std::string name = parse_name("a table name");
    495     skip_blank(false);
    496     if (name == "deps" && peek() == '.') {
    497       ++pos_;
    498       skip_blank(false);
    499       const std::string dependency = parse_name("a dependency name");
    500       if (dependency.find_first_not_of("abcdefghijklmnopqrstuvwxyz"
    501                                        "0123456789_-") != std::string::npos) {
    502         fail("dependency names use lowercase ASCII letters, digits, '_' and '-'");
    503       }
    504       name += "." + dependency;
    505       skip_blank(false);
    506     }
    507     if (peek() != ']') fail("expected ']'");
    508     ++pos_;
    509     end_line();
    510     // Checked here rather than with the keys, so that a misspelled table with
    511     // nothing in it is reported as well.
    512     const bool known_platform =
    513         std::find(std::begin(PLATFORM_TABLES), std::end(PLATFORM_TABLES),
    514                   name) != std::end(PLATFORM_TABLES);
    515     const bool known_profile =
    516         std::find(std::begin(PROFILE_TABLES), std::end(PROFILE_TABLES), name) !=
    517         std::end(PROFILE_TABLES);
    518     if (!known_platform && !known_profile &&
    519         !name.starts_with(DEPENDENCY_PREFIX)) {
    520       config_error(line_here(), "unknown table '[" + name + "]'");
    521     }
    522     return name;
    523   }
    524 
    525   /// @brief Reads one `key = value` line into @p table.
    526   ///
    527   /// @param section The table the pair belongs to; empty at the top level.
    528   /// @param table   Receives the pair.
    529   void parse_pair(const std::string& section, Table& table) {
    530     Entry entry;
    531     entry.line = line_here();
    532     std::string key = parse_name("a key");
    533     skip_blank(false);
    534     if (peek() != '=') fail("expected '=' after the key");
    535     ++pos_;
    536     skip_blank(false);
    537     if (peek() == '[') {
    538       entry.is_list = true;
    539       entry.list = parse_array();
    540     } else {
    541       entry.text = parse_string();
    542     }
    543     end_line();
    544 
    545     std::string full = section.empty() ? key : section + "." + key;
    546     if (!table.emplace(full, entry).second) {
    547       config_error(entry.line, "duplicate key '" + full + "'");
    548     }
    549   }
    550 
    551   /// @brief Reads a string in double or single quotes.
    552   std::string parse_string() {
    553     char quote = peek();
    554     if (quote != '"' && quote != '\'') fail("expected a quoted string");
    555     ++pos_;
    556 
    557     std::string out;
    558     for (;; ++pos_) {
    559       if (pos_ >= text_.size() || text_[pos_] == '\n') {
    560         fail("unterminated string");
    561       }
    562       char c = text_[pos_];
    563       if (c == quote) break;
    564       if (quote == '"' && c == '\\') {
    565         char next = pos_ + 1 < text_.size() ? text_[pos_ + 1] : '\0';
    566         if (next != '\\' && next != '"') {
    567           fail("unsupported escape; only \\\\ and \\\" are allowed");
    568         }
    569         c = next;
    570         ++pos_;
    571       }
    572       out += c;
    573     }
    574     ++pos_;  // the closing quote
    575     return out;
    576   }
    577 
    578   /// @brief Reads `[ "a", "b", ... ]`, possibly over several lines.
    579   Cmd parse_array() {
    580     ++pos_;  // '['
    581     Cmd items;
    582     for (;;) {
    583       skip_blank(true);
    584       if (pos_ >= text_.size()) fail("unterminated array");
    585       if (text_[pos_] == ']') {
    586         ++pos_;
    587         return items;
    588       }
    589       items.push_back(parse_string());
    590       skip_blank(true);
    591       if (peek() == ',') {
    592         ++pos_;
    593       } else if (peek() != ']') {
    594         fail(pos_ >= text_.size() ? "unterminated array"
    595                                   : "expected ',' or ']'");
    596       }
    597     }
    598   }
    599 };
    600 
    601 /// @brief Tells whether a path from the configuration stays inside the project.
    602 ///
    603 /// It must be relative, must not be empty or `.`, and must not climb out with
    604 /// `..`. Anything else could make the builder write, or `clean` delete, outside
    605 /// the project directory or the project directory itself.
    606 static bool is_inside_project(const fs::path& path) {
    607   if (path.empty() || path.is_absolute() || path.has_root_name()) return false;
    608   const fs::path normal = path.lexically_normal();
    609   if (normal == "." || normal.empty()) return false;
    610   for (const fs::path& part : normal) {
    611     if (part == "..") return false;
    612   }
    613   return true;
    614 }
    615 
    616 /// @brief Tells whether @p inner is @p outer itself or lies below it.
    617 static bool is_within(const fs::path& inner, const fs::path& outer) {
    618   // lexically_relative() yields "../..." when inner is not below outer, and
    619   // "." when the two are the same; trailing separators are ignored.
    620   fs::path relative =
    621       inner.lexically_normal().lexically_relative(outer.lexically_normal());
    622   return !relative.empty() && *relative.begin() != "..";
    623 }
    624 
    625 /// @brief Reads and checks #CONFIG_FILE.
    626 ///
    627 /// Exits with a message if the file is missing, malformed or contains a key
    628 /// the builder does not know.
    629 ///
    630 /// @return The settings, with the table of the current platform merged in.
    631 static Config load_config(const std::string& profile) {
    632   std::ifstream file(CONFIG_FILE);
    633   if (!file) {
    634     config_error(0, "cannot read it; run the builder from the project root");
    635   }
    636   std::stringstream buffer;
    637   buffer << file.rdbuf();
    638   std::map<std::string, int> dependency_tables;
    639   Table table = ConfigParser(buffer.str()).parse(dependency_tables);
    640 
    641   // Each take_*() removes the key from the table, so that what is left at the
    642   // end is exactly the unknown keys.
    643   auto take_string = [&table](const std::string& key,
    644                               const std::string& fallback) -> std::string {
    645     auto it = table.find(key);
    646     if (it == table.end()) return fallback;
    647     if (it->second.is_list) {
    648       config_error(it->second.line, "'" + key + "' must be a string");
    649     }
    650     std::string value = it->second.text;
    651     table.erase(it);
    652     return value;
    653   };
    654   auto take_list = [&table](const std::string& key) -> Cmd {
    655     auto it = table.find(key);
    656     if (it == table.end()) return {};
    657     if (!it->second.is_list) {
    658       config_error(it->second.line,
    659                    "'" + key + "' must be a list, e.g. [\"a\", \"b\"]");
    660     }
    661     Cmd value = it->second.list;
    662     table.erase(it);
    663     return value;
    664   };
    665 
    666   Config cfg;
    667   std::string name =
    668       take_string("name", fs::current_path().filename().string());
    669   cfg.compiler = take_string("compiler", "clang++");
    670   cfg.src_dir = take_string("src", "src");
    671   cfg.clean_dir = take_string("out", "build");
    672   cfg.out_dir = cfg.clean_dir / profile;
    673   cfg.entry = take_string("entry", (cfg.src_dir / "main.cpp").string());
    674   cfg.tests_dir = take_string("tests", "tests");
    675   cfg.flags = take_list("flags");
    676   cfg.objcxx_flags = take_list("objcxx_flags");
    677   cfg.link_flags = take_list("link");
    678 
    679   // Every platform's table is read, so that it counts as known, but only the
    680   // one of this platform is used.
    681   for (const char* platform : PLATFORM_TABLES) {
    682     const std::string section = platform;
    683     std::string compiler = take_string(section + ".compiler", "");
    684     Cmd flags = take_list(section + ".flags");
    685     Cmd link = take_list(section + ".link");
    686     if (section == HOST_NAME) {
    687       if (!compiler.empty()) cfg.compiler = compiler;
    688       cfg.flags.insert(cfg.flags.end(), flags.begin(), flags.end());
    689       cfg.link_flags.insert(cfg.link_flags.end(), link.begin(), link.end());
    690     }
    691   }
    692 
    693   for (const char* name_p : PROFILE_TABLES) {
    694     const std::string section = name_p;
    695     std::string compiler = take_string(section + ".compiler", "");
    696     Cmd flags = take_list(section + ".flags");
    697     Cmd link = take_list(section + ".link");
    698     if (section == profile) {
    699       if (!compiler.empty()) cfg.compiler = compiler;
    700       cfg.flags.insert(cfg.flags.end(), flags.begin(), flags.end());
    701       cfg.link_flags.insert(cfg.link_flags.end(), link.begin(), link.end());
    702     }
    703   }
    704 
    705   for (const auto& [section, line] : dependency_tables) {
    706     Dependency dep{
    707         section.substr(DEPENDENCY_PREFIX.size()),
    708         take_string(section + ".git", ""),
    709         take_string(section + ".rev", ""),
    710         take_list(section + ".include"),
    711     };
    712     if (dep.git.empty() || dep.rev.empty() || dep.include_dirs.empty()) {
    713       config_error(line, "'[" + section + "]' needs git, rev, and include");
    714     }
    715     if (dep.git.find_first_of("\r\n\0", 0, 3) != std::string::npos ||
    716         dep.rev.find_first_of("\r\n\0", 0, 3) != std::string::npos) {
    717       config_error(line, "dependency git and rev cannot contain line breaks or NUL");
    718     }
    719     for (const std::string& dir : dep.include_dirs) {
    720       const fs::path path(dir);
    721       if (dir.find('\0') != std::string::npos || path.has_root_path() ||
    722           (path != "." && !is_inside_project(path))) {
    723         config_error(line, "'" + section +
    724                                ".include' paths must stay inside the dependency");
    725       }
    726     }
    727     cfg.dependencies.push_back(std::move(dep));
    728   }
    729 
    730   // Report the unknown key that was written first.
    731   const Entry* first = nullptr;
    732   std::string first_key;
    733   for (const auto& [key, entry] : table) {
    734     if (!first || entry.line < first->line) {
    735       first = &entry;
    736       first_key = key;
    737     }
    738   }
    739   if (first) config_error(first->line, "unknown key '" + first_key + "'");
    740 
    741   if (cfg.compiler.empty()) config_error(0, "'compiler' must not be empty");
    742 
    743   if (name.empty()) config_error(0, "'name' must not be empty");
    744   if (name.find_first_of("/\\") != std::string::npos) {
    745     config_error(0, "'name' must be a file name, not a path");
    746   }
    747   // `clean` deletes the whole of `out`, so it must be a directory of its own:
    748   // not the project, not the sources, and not something holding them.
    749   if (!is_inside_project(cfg.src_dir)) {
    750     config_error(0,
    751                  "'src' must be a relative path inside the project, and "
    752                  "not the project directory itself");
    753   }
    754   if (!is_inside_project(cfg.clean_dir)) {
    755     config_error(0,
    756                  "'out' must be a relative path inside the project, and "
    757                  "not the project directory itself");
    758   }
    759   if (is_within(cfg.clean_dir, cfg.src_dir) ||
    760       is_within(cfg.src_dir, cfg.clean_dir)) {
    761     config_error(0,
    762                  "'out' and 'src' must not be the same directory or "
    763                  "contain one another");
    764   }
    765   if (!is_within(cfg.entry, cfg.src_dir) ||
    766       cfg.entry.lexically_normal() == cfg.src_dir.lexically_normal()) {
    767     config_error(0, "'entry' must be a file inside 'src'");
    768   }
    769   if (!is_inside_project(cfg.tests_dir)) {
    770     config_error(0,
    771                  "'tests' must be a relative path inside the project, and "
    772                  "not the project directory itself");
    773   }
    774   for (const fs::path* other : {&cfg.src_dir, &cfg.clean_dir}) {
    775     if (is_within(cfg.tests_dir, *other) || is_within(*other, cfg.tests_dir)) {
    776       config_error(0,
    777                    "'tests' must not be the same directory as 'src' or 'out', "
    778                    "nor inside or around either of them");
    779     }
    780   }
    781   cfg.exe = cfg.out_dir / (name + EXE_SUFFIX);
    782   return cfg;
    783 }
    784 
    785 /// @}
    786 
    787 /// @name Platform selection
    788 /// Deciding which source files belong to the current platform.
    789 /// @{
    790 
    791 /// @brief Tells whether a source file is built on the current platform.
    792 ///
    793 /// Platform-specific code is marked by its name:
    794 /// - `.mm` (Objective-C++) files build on macOS only;
    795 /// - a `_mac`, `_linux` or `_win` suffix on the file name, before the
    796 ///   extension, restricts the file to that platform.
    797 ///
    798 /// Everything else builds everywhere. The suffix test is purely textual, so
    799 /// avoid ending a portable file's name with one of them (e.g. `big_win.cpp`).
    800 ///
    801 /// A `_test` at the end of the name is ignored first, so `window_mac_test.cpp`
    802 /// belongs to macOS like `window_mac.cpp` does.
    803 ///
    804 /// @param src Path of the source file.
    805 /// @return `true` if the file must be compiled on this platform.
    806 static bool is_built_here(const fs::path& src) {
    807   if (src.extension() == ".mm") return HOST == Platform::Mac;
    808 
    809   static const struct {
    810     const char* suffix;
    811     Platform platform;
    812   } SUFFIXES[] = {
    813       {"_mac", Platform::Mac},
    814       {"_linux", Platform::Linux},
    815       {"_win", Platform::Windows},
    816   };
    817   std::string stem = src.stem().string();
    818   if (stem.ends_with("_test")) stem.resize(stem.size() - 5);
    819   for (const auto& entry : SUFFIXES) {
    820     if (stem.ends_with(entry.suffix)) return entry.platform == HOST;
    821   }
    822   return true;
    823 }
    824 
    825 /// @}
    826 
    827 /// @name Processes
    828 /// Spawning children and limiting how many run at once.
    829 /// @{
    830 
    831 /// @brief Handle of a running child: a process id on POSIX, a `HANDLE` on
    832 ///        Windows.
    833 #if defined(_WIN32)
    834 using Process = HANDLE;
    835 #else
    836 using Process = pid_t;
    837 #endif
    838 
    839 #if defined(_WIN32)
    840 /// @brief Quotes one argument for a Windows command line.
    841 ///
    842 /// Windows passes a child its arguments as a single string, which the child's
    843 /// runtime splits again. The rules: an argument containing a space, tab or
    844 /// quote is wrapped in quotes; inside it a quote becomes a backslash-quote, and
    845 /// backslashes directly before a quote (or before the closing quote) are
    846 /// doubled.
    847 ///
    848 /// @param arg Raw argument.
    849 /// @return The argument, quoted if necessary.
    850 static std::string quote_arg(const std::string& arg) {
    851   if (!arg.empty() && arg.find_first_of(" \t\"") == std::string::npos) {
    852     return arg;
    853   }
    854   std::string out = "\"";
    855   size_t backslashes = 0;  // run of backslashes not yet written
    856   for (char c : arg) {
    857     if (c == '\\') {
    858       ++backslashes;
    859       continue;
    860     }
    861     if (c == '"') {
    862       out.append(backslashes * 2 + 1, '\\');  // double them, then escape the "
    863     } else {
    864       out.append(backslashes, '\\');  // not before a quote: written as is
    865     }
    866     out += c;
    867     backslashes = 0;
    868   }
    869   out.append(backslashes * 2, '\\');  // they now sit before the closing quote
    870   out += '"';
    871   return out;
    872 }
    873 #endif
    874 
    875 /// @brief Starts a child process without waiting for it.
    876 ///
    877 /// Exits the builder if the process cannot be started.
    878 ///
    879 /// @param cmd Command to run; `cmd[0]` is looked up in `PATH`.
    880 /// @return Handle of the child.
    881 static Process spawn(const Cmd& cmd) {
    882   // Our own log lines may still sit in stdout's buffer. Flushing before the
    883   // child starts keeps them ahead of the child's output even when stdout is a
    884   // pipe or a file.
    885   std::fflush(stdout);
    886 
    887 #if defined(_WIN32)
    888   std::string line;
    889   for (size_t i = 0; i < cmd.size(); ++i) {
    890     if (i > 0) line += ' ';
    891     line += quote_arg(cmd[i]);
    892   }
    893 
    894   // Hand our standard streams to the child explicitly, so redirected output
    895   // (a pipe or a file) is inherited as well.
    896   STARTUPINFOA startup = {};
    897   startup.cb = sizeof(startup);
    898   startup.dwFlags = STARTF_USESTDHANDLES;
    899   startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
    900   startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    901   startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
    902 
    903   // With no application name, the first word of the command line is looked up
    904   // in PATH and ".exe" is appended if needed. The command line buffer must be
    905   // writable, which std::string::data() is.
    906   PROCESS_INFORMATION info = {};
    907   if (!CreateProcessA(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr,
    908                       nullptr, &startup, &info)) {
    909     print_error("cannot start " + cmd[0] + " (error " +
    910                 std::to_string(static_cast<unsigned long>(GetLastError())) +
    911                 ")");
    912     std::exit(EXIT_FAILURE);
    913   }
    914   CloseHandle(info.hThread);  // only the process handle is needed
    915   return info.hProcess;
    916 #else
    917   // posix_spawnp wants a C-style argv: an array of char* ending in nullptr.
    918   std::vector<char*> argv;
    919   for (const std::string& arg : cmd) {
    920     argv.push_back(const_cast<char*>(arg.c_str()));
    921   }
    922   argv.push_back(nullptr);
    923 
    924   // The trailing "p" means the program is looked up in PATH, so "clang++"
    925   // does not have to be an absolute path.
    926   pid_t pid = 0;
    927   if (posix_spawnp(&pid, argv[0], nullptr, nullptr, argv.data(), environ) !=
    928       0) {
    929     print_error(std::string("cannot start ") + argv[0]);
    930     std::exit(EXIT_FAILURE);
    931   }
    932   return pid;
    933 #endif
    934 }
    935 
    936 /// @brief How a child process ended.
    937 struct ExitStatus {
    938   int code = 0;    ///< Exit status; -1 if waiting for the child failed.
    939   int signal = 0;  ///< The signal that killed it (macOS, Linux), or 0.
    940 
    941   bool ok() const { return code == 0 && signal == 0; }
    942 };
    943 
    944 /// @brief A running child and the index of the command it was started for.
    945 struct Child {
    946   Process process;
    947   size_t index;
    948 };
    949 
    950 /// @brief "No command": the index wait_any() reports when waiting itself
    951 /// failed.
    952 constexpr size_t kNoIndex = static_cast<size_t>(-1);
    953 
    954 /// @brief Blocks until any one of the running children exits.
    955 ///
    956 /// The child that finished is removed from @p running.
    957 ///
    958 /// @param running Children that were started and not yet waited for.
    959 /// @param index   Receives the index of the command of the child that finished,
    960 ///                or #kNoIndex if waiting itself failed; in that case @p
    961 ///                running is emptied, since the remaining children can no
    962 ///                longer be tracked.
    963 /// @return How that child ended.
    964 static ExitStatus wait_any(std::vector<Child>& running, size_t* index) {
    965   ExitStatus status;
    966   *index = kNoIndex;
    967 #if defined(_WIN32)
    968   std::vector<HANDLE> handles;
    969   for (const Child& child : running) handles.push_back(child.process);
    970   DWORD which = WaitForMultipleObjects(static_cast<DWORD>(handles.size()),
    971                                        handles.data(), FALSE, INFINITE);
    972   // On success the result is WAIT_OBJECT_0 (== 0) plus the index of the handle
    973   // that became signaled; anything else is an error.
    974   if (which >= handles.size()) {
    975     running.clear();
    976     status.code = -1;
    977     return status;
    978   }
    979   DWORD code = 1;
    980   GetExitCodeProcess(handles[which], &code);
    981   CloseHandle(handles[which]);
    982   *index = running[which].index;
    983   running.erase(running.begin() + which);
    984   status.code = static_cast<int>(code);
    985   return status;
    986 #else
    987   int raw = 0;
    988   pid_t done;
    989   do {
    990     done = waitpid(-1, &raw, 0);  // -1 means "any child"
    991   } while (done < 0 && errno == EINTR);  // retry if a signal interrupted us
    992   if (done < 0) {
    993     running.clear();
    994     status.code = -1;
    995     return status;
    996   }
    997   auto it = std::find_if(running.begin(), running.end(),
    998                          [done](const Child& c) { return c.process == done; });
    999   if (it != running.end()) {
   1000     *index = it->index;
   1001     running.erase(it);
   1002   }
   1003   if (WIFSIGNALED(raw)) {
   1004     status.signal = WTERMSIG(raw);
   1005   } else if (WIFEXITED(raw)) {
   1006     status.code = WEXITSTATUS(raw);
   1007   } else {
   1008     status.code = -1;
   1009   }
   1010   return status;
   1011 #endif
   1012 }
   1013 
   1014 /// @brief Runs a batch of commands with bounded parallelism.
   1015 ///
   1016 /// No threads are needed: the parallelism comes from the child processes, and
   1017 /// this is just a scheduling loop. Each iteration does one of two things:
   1018 /// - commands remain and we are below the limit: start one more;
   1019 /// - otherwise: wait for one to finish.
   1020 ///
   1021 /// After the first failure no new commands are started, but the ones already
   1022 /// running are still waited for so that no orphan processes are left behind.
   1023 ///
   1024 /// @param cmds       Commands to run, started in order.
   1025 /// @param max_jobs   Maximum number of commands running at the same time.
   1026 ///                   Capped at 60, because Windows can wait on at most 64
   1027 ///                   handles at once.
   1028 /// @param failed     If not null, receives the indices of the commands that
   1029 ///                   failed.
   1030 /// @return `true` only if every command succeeded.
   1031 static bool run_all(const std::vector<Cmd>& cmds, unsigned max_jobs,
   1032                     std::vector<size_t>* failed = nullptr) {
   1033   max_jobs = std::min(max_jobs, 60u);
   1034   size_t next = 0;             // index of the next command to start
   1035   std::vector<Child> running;  // children currently running
   1036   bool ok = true;
   1037   while ((ok && next < cmds.size()) || !running.empty()) {
   1038     if (ok && next < cmds.size() && running.size() < max_jobs) {
   1039       running.push_back({spawn(cmds[next]), next});
   1040       ++next;
   1041     } else {
   1042       size_t index = kNoIndex;
   1043       if (!wait_any(running, &index).ok()) {
   1044         ok = false;
   1045         if (failed != nullptr && index != kNoIndex) failed->push_back(index);
   1046       }
   1047     }
   1048   }
   1049   return ok;
   1050 }
   1051 
   1052 /// @brief Runs a single command and waits for it.
   1053 ///
   1054 /// @param cmd Command to run.
   1055 /// @return How it ended.
   1056 static ExitStatus run_status(const Cmd& cmd) {
   1057   std::vector<Child> running = {{spawn(cmd), 0}};
   1058   size_t ignored = kNoIndex;
   1059   return wait_any(running, &ignored);
   1060 }
   1061 
   1062 /// @brief Runs a single command and waits for it.
   1063 ///
   1064 /// @param cmd Command to run.
   1065 /// @return `true` if the command succeeded.
   1066 static bool run(const Cmd& cmd) { return run_status(cmd).ok(); }
   1067 
   1068 /// @brief Runs a command and captures its stdout and stderr (empty on failure).
   1069 static std::string capture(const Cmd& cmd) {
   1070   if (cmd.empty()) return {};
   1071   std::fflush(stdout);
   1072 
   1073 #if defined(_WIN32)
   1074   SECURITY_ATTRIBUTES sa = {sizeof(sa), nullptr, TRUE};
   1075   HANDLE read_pipe = nullptr;
   1076   HANDLE write_pipe = nullptr;
   1077   if (!CreatePipe(&read_pipe, &write_pipe, &sa, 0)) return {};
   1078   SetHandleInformation(read_pipe, HANDLE_FLAG_INHERIT, 0);
   1079 
   1080   std::string line;
   1081   for (size_t i = 0; i < cmd.size(); ++i) {
   1082     if (i > 0) line += ' ';
   1083     line += quote_arg(cmd[i]);
   1084   }
   1085   STARTUPINFOA startup = {};
   1086   startup.cb = sizeof(startup);
   1087   startup.dwFlags = STARTF_USESTDHANDLES;
   1088   startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
   1089   startup.hStdOutput = write_pipe;
   1090   startup.hStdError = write_pipe;
   1091   PROCESS_INFORMATION info = {};
   1092   if (!CreateProcessA(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr,
   1093                       nullptr, &startup, &info)) {
   1094     CloseHandle(read_pipe);
   1095     CloseHandle(write_pipe);
   1096     return {};
   1097   }
   1098   CloseHandle(write_pipe);
   1099   CloseHandle(info.hThread);
   1100   std::string out;
   1101   char buf[512];
   1102   DWORD n = 0;
   1103   while (ReadFile(read_pipe, buf, sizeof(buf), &n, nullptr) && n > 0) {
   1104     out.append(buf, n);
   1105   }
   1106   CloseHandle(read_pipe);
   1107   WaitForSingleObject(info.hProcess, INFINITE);
   1108   DWORD code = 1;
   1109   GetExitCodeProcess(info.hProcess, &code);
   1110   CloseHandle(info.hProcess);
   1111   return code == 0 ? out : std::string{};
   1112 #else
   1113   int fds[2];
   1114   if (pipe(fds) != 0) return {};
   1115 
   1116   posix_spawn_file_actions_t actions;
   1117   posix_spawn_file_actions_init(&actions);
   1118   posix_spawn_file_actions_addclose(&actions, fds[0]);
   1119   posix_spawn_file_actions_adddup2(&actions, fds[1], STDOUT_FILENO);
   1120   posix_spawn_file_actions_adddup2(&actions, fds[1], STDERR_FILENO);
   1121   posix_spawn_file_actions_addclose(&actions, fds[1]);
   1122 
   1123   std::vector<char*> argv;
   1124   for (const std::string& arg : cmd) {
   1125     argv.push_back(const_cast<char*>(arg.c_str()));
   1126   }
   1127   argv.push_back(nullptr);
   1128 
   1129   pid_t pid = 0;
   1130   int err =
   1131       posix_spawnp(&pid, argv[0], &actions, nullptr, argv.data(), environ);
   1132   posix_spawn_file_actions_destroy(&actions);
   1133   close(fds[1]);
   1134   if (err != 0) {
   1135     close(fds[0]);
   1136     return {};
   1137   }
   1138 
   1139   std::string out;
   1140   char buf[512];
   1141   for (;;) {
   1142     ssize_t n = read(fds[0], buf, sizeof(buf));
   1143     if (n > 0) {
   1144       out.append(buf, static_cast<size_t>(n));
   1145     } else if (n == 0) {
   1146       break;
   1147     } else if (errno != EINTR) {
   1148       break;
   1149     }
   1150   }
   1151   close(fds[0]);
   1152 
   1153   int raw = 0;
   1154   while (waitpid(pid, &raw, 0) < 0 && errno == EINTR) {
   1155   }
   1156   if (!WIFEXITED(raw) || WEXITSTATUS(raw) != 0) return {};
   1157   return out;
   1158 #endif
   1159 }
   1160 
   1161 /// @brief Says in words how a child ended, to follow the name of the program:
   1162 ///        `exited with status 3` or `was killed by signal 11 (Segmentation
   1163 ///        fault)`.
   1164 static std::string describe(const ExitStatus& status) {
   1165   if (status.signal != 0) {
   1166 #if defined(_WIN32)
   1167     return "was stopped by signal " + std::to_string(status.signal);
   1168 #else
   1169     const char* name = strsignal(status.signal);
   1170     return "was killed by signal " + std::to_string(status.signal) +
   1171            (name != nullptr ? " (" + std::string(name) + ")" : "");
   1172 #endif
   1173   }
   1174   if (status.code == -1) return "could not be waited for";
   1175 #if defined(_WIN32)
   1176   // Windows reports a crash as an exit status such as 0xC0000005.
   1177   if (static_cast<unsigned>(status.code) >= 0xC0000000u) {
   1178     char buffer[32];
   1179     std::snprintf(buffer, sizeof(buffer), "crashed with code 0x%08X",
   1180                   static_cast<unsigned>(status.code));
   1181     return buffer;
   1182   }
   1183 #endif
   1184   return "exited with status " + std::to_string(status.code);
   1185 }
   1186 
   1187 /// @brief The exit status the builder itself should end with when it passes on
   1188 ///        the failure of a program it ran: its status, or 128 plus the signal,
   1189 ///        and never 0 for a failure.
   1190 static int exit_code_of(const ExitStatus& status) {
   1191   if (status.signal != 0) return 128 + status.signal;
   1192   if (status.code <= 0 || status.code > 255) return status.ok() ? 0 : 1;
   1193   return status.code;
   1194 }
   1195 
   1196 /// @}
   1197 
   1198 /// @name Incremental compilation
   1199 /// Deciding whether a source file must be recompiled.
   1200 /// @{
   1201 
   1202 /// @brief Reads a dependency file written by the compiler's `-MD` flag.
   1203 ///
   1204 /// The file uses Makefile syntax: `obj: dep dep dep`, where a backslash at the
   1205 /// end of a line continues the list on the next line. Only these rules matter:
   1206 /// - the dependency list starts after the first `": "`;
   1207 /// - dependencies are separated by whitespace or a line continuation;
   1208 /// - a space inside a path is escaped with a backslash;
   1209 /// - any other backslash is part of the path, which is how Windows paths
   1210 ///   appear: a drive letter, then names separated by backslashes.
   1211 ///
   1212 /// @param path Path of the `.d` file.
   1213 /// @return Every dependency listed in the file; empty if it cannot be parsed.
   1214 static std::vector<fs::path> read_depfile(const fs::path& path) {
   1215   // Read the whole file into one string.
   1216   std::ifstream file(path);
   1217   std::stringstream buffer;
   1218   buffer << file.rdbuf();
   1219   std::string text = buffer.str();
   1220 
   1221   std::vector<fs::path> deps;
   1222   size_t i = text.find(": ");
   1223   if (i == std::string::npos) return deps;
   1224 
   1225   std::string token;  // the path currently being accumulated
   1226   // The loop deliberately runs one step past the end (i == size) and treats
   1227   // end-of-file as a newline, so the last path is flushed as well.
   1228   for (i += 2; i <= text.size(); ++i) {
   1229     char c = i < text.size() ? text[i] : '\n';
   1230     char next = i + 1 < text.size() ? text[i + 1] : '\0';
   1231     if (c == '\\' && next == ' ') {
   1232       // An escaped space that belongs to the current path.
   1233       token += ' ';
   1234       ++i;
   1235     } else if (c == '\\' && (next == '\n' || next == '\r')) {
   1236       // A line continuation: the current path ends here. The newline itself
   1237       // is a separator too and is handled by the next iteration.
   1238       if (!token.empty()) deps.push_back(token);
   1239       token.clear();
   1240     } else if (c == ' ' || c == '\n' || c == '\r') {
   1241       // A separator: the current path ends here.
   1242       if (!token.empty()) deps.push_back(token);
   1243       token.clear();
   1244     } else {
   1245       token += c;  // includes a backslash that is part of a Windows path
   1246     }
   1247   }
   1248   return deps;
   1249 }
   1250 
   1251 /// @brief Tells whether an object file is out of date.
   1252 ///
   1253 /// Any one of these is enough:
   1254 /// -# @p obj or @p dep is missing (never built, or cleaned);
   1255 /// -# the builder or `kumo.toml` is newer than @p obj (the compile flags come
   1256 ///    from those two, so a change to either may mean different flags);
   1257 /// -# some dependency (the source itself or a header it includes) is newer
   1258 ///    than @p obj, or has been deleted.
   1259 ///
   1260 /// @param obj        Path of the object file.
   1261 /// @param dep        Path of the dependency file written alongside it.
   1262 /// @param flags_time Modification time of whatever the flags come from: the
   1263 ///                   newer of the builder binary and `kumo.toml`.
   1264 /// @return `true` if the source must be recompiled.
   1265 static bool needs_compile(const fs::path& obj, const fs::path& dep,
   1266                           fs::file_time_type flags_time) {
   1267   if (!fs::exists(obj) || !fs::exists(dep)) return true;
   1268 
   1269   fs::file_time_type obj_time = fs::last_write_time(obj);
   1270   if (flags_time > obj_time) return true;
   1271 
   1272   for (const fs::path& d : read_depfile(dep)) {
   1273     if (!fs::exists(d) || fs::last_write_time(d) > obj_time) return true;
   1274   }
   1275   return false;
   1276 }
   1277 
   1278 static void append_list(std::ostringstream& ss, const char* key,
   1279                         const Cmd& list) {
   1280   ss << key << "=" << list.size() << "\n";
   1281   for (const std::string& item : list) {
   1282     ss << " " << item << "\n";
   1283   }
   1284 }
   1285 
   1286 /// @brief Computes a fingerprint of the active compiler and build flags.
   1287 static std::string toolchain_fingerprint(const Config& cfg,
   1288                                          const Cmd& dependency_commits) {
   1289   const std::string version = capture({cfg.compiler, "--version"});
   1290   if (version.empty()) {
   1291     print_error("cannot run compiler '" + cfg.compiler + "'");
   1292     std::exit(EXIT_FAILURE);
   1293   }
   1294   std::ostringstream ss;
   1295   ss << "compiler=" << cfg.compiler << "\n"
   1296      << "version:\n"
   1297      << version << "\n";
   1298   append_list(ss, "flags", cfg.flags);
   1299   append_list(ss, "objcxx_flags", cfg.objcxx_flags);
   1300   append_list(ss, "link", cfg.link_flags);
   1301   if (!dependency_commits.empty()) {
   1302     append_list(ss, "dependencies", dependency_commits);
   1303   }
   1304   return ss.str();
   1305 }
   1306 
   1307 /// @brief Clears stale build outputs if the compiler or flags changed.
   1308 static void check_toolchain_cache(const Config& cfg,
   1309                                   const Cmd& dependency_commits) {
   1310   const fs::path stamp = cfg.out_dir / ".toolchain";
   1311   const std::string current = toolchain_fingerprint(cfg, dependency_commits);
   1312 
   1313   if (fs::exists(stamp)) {
   1314     std::ifstream in(stamp, std::ios::binary);
   1315     std::ostringstream old;
   1316     old << in.rdbuf();
   1317     if (old.str() == current) return;
   1318     in.close();  // Windows cannot remove the stamp while this stream is open.
   1319     log_step(Style::Cyan, "rebuild",
   1320              "toolchain or flags changed, clearing " +
   1321                  cfg.out_dir.generic_string() + "/");
   1322     fs::remove_all(cfg.out_dir);
   1323   } else if (fs::exists(cfg.out_dir)) {
   1324     // Existing build directory without a stamp: clear once so objects from
   1325     // an unknown compiler cannot linger.
   1326     log_step(
   1327         Style::Cyan, "rebuild",
   1328         "no toolchain stamp, clearing " + cfg.out_dir.generic_string() + "/");
   1329     fs::remove_all(cfg.out_dir);
   1330   }
   1331 
   1332   fs::create_directories(cfg.out_dir);
   1333   std::ofstream out(stamp, std::ios::binary);
   1334   out << current;
   1335 }
   1336 
   1337 /// @}
   1338 
   1339 /// @name Header-only dependencies
   1340 /// @{
   1341 
   1342 static bool dependency_error(const Dependency& dep, const std::string& message) {
   1343   print_error("dependency '" + dep.name + "' (" + dep.rev + "): " + message);
   1344   return false;
   1345 }
   1346 
   1347 static bool is_commit_id(std::string_view rev) {
   1348   return (rev.size() == 40 || rev.size() == 64) &&
   1349          rev.find_first_not_of("0123456789abcdefABCDEF") == std::string_view::npos;
   1350 }
   1351 
   1352 /// @brief A portable cache name derived from a dependency's URL and revision.
   1353 ///
   1354 /// The receipt also records the original values to detect a hash collision.
   1355 static std::string dependency_cache_key(const Dependency& dep) {
   1356   std::uint64_t hash = 14695981039346656037ull;
   1357   for (unsigned char byte : dep.git + "\n" + dep.rev) {
   1358     hash ^= byte;
   1359     hash *= 1099511628211ull;
   1360   }
   1361   return std::to_string(hash);
   1362 }
   1363 
   1364 static bool dependency_path_within(const fs::path& inner, const fs::path& outer) {
   1365   auto component = inner.begin();
   1366   for (const fs::path& part : outer) {
   1367     if (component == inner.end()) return false;
   1368 #if defined(_WIN32)
   1369     if (CompareStringOrdinal(component->c_str(), -1, part.c_str(), -1, TRUE) !=
   1370         CSTR_EQUAL) {
   1371       return false;
   1372     }
   1373 #else
   1374     if (*component != part) return false;
   1375 #endif
   1376     ++component;
   1377   }
   1378   return true;
   1379 }
   1380 
   1381 static bool valid_dependency_cache(const Config& cfg) {
   1382   const fs::path project = fs::canonical(fs::current_path());
   1383   const fs::path cache = fs::weakly_canonical(fs::absolute(DEPENDENCY_CACHE));
   1384   if (!dependency_path_within(cache, project) ||
   1385       dependency_path_within(project, cache)) {
   1386     print_error("dependency cache must be inside the project");
   1387     return false;
   1388   }
   1389   for (const fs::path* dir : {&cfg.src_dir, &cfg.tests_dir, &cfg.clean_dir}) {
   1390     const fs::path resolved = fs::weakly_canonical(fs::absolute(*dir));
   1391     if (dependency_path_within(cache, resolved) ||
   1392         dependency_path_within(resolved, cache)) {
   1393       print_error("dependency cache overlaps " + dir->generic_string());
   1394       return false;
   1395     }
   1396   }
   1397   return true;
   1398 }
   1399 
   1400 static bool dependency_include_flags(const Dependency& dep,
   1401                                      const fs::path& entry, Cmd& flags) {
   1402   const fs::path source = entry / "source";
   1403   if (!fs::is_directory(source)) {
   1404     return dependency_error(dep, "missing dependency checkout");
   1405   }
   1406   const fs::path root = fs::canonical(source);
   1407   if (!dependency_path_within(root, fs::canonical(entry))) {
   1408     return dependency_error(dep, "checkout points outside its cache entry");
   1409   }
   1410   for (const std::string& dir : dep.include_dirs) {
   1411     const fs::path path = (source / dir).lexically_normal();
   1412     if (!fs::is_directory(path) ||
   1413         !dependency_path_within(fs::canonical(path), root)) {
   1414       return dependency_error(dep, "missing or invalid include directory '" + dir +
   1415                                         "'");
   1416     }
   1417     flags.push_back("-I" + path.generic_string());
   1418   }
   1419   return true;
   1420 }
   1421 
   1422 /// @brief Fetches and validates a dependency before it enters the build cache.
   1423 static bool populate_dependency(const Dependency& dep, const fs::path& staging) {
   1424   std::string ref = dep.rev;
   1425   const bool is_tag = !is_commit_id(ref);
   1426   if (is_tag) {
   1427     if (!ref.starts_with("refs/tags/")) ref = "refs/tags/" + ref;
   1428     if (!run({"git", "check-ref-format", ref})) {
   1429       return dependency_error(dep, "invalid Git tag");
   1430     }
   1431   }
   1432 
   1433   log_step(Style::Cyan, "fetch", dep.name + " " + dep.rev);
   1434   const std::string source = (staging / "source").generic_string();
   1435   if (!run({"git", "clone", "--no-checkout", "--no-hardlinks",
   1436             "--no-recurse-submodules", "--", dep.git, source})) {
   1437     return dependency_error(dep, "git clone failed");
   1438   }
   1439   std::string commit = capture({"git", "-C", source, "rev-parse", "--verify",
   1440                                 "--end-of-options", ref + "^{commit}"});
   1441   while (!commit.empty() && (commit.back() == '\n' || commit.back() == '\r')) {
   1442     commit.pop_back();
   1443   }
   1444   const bool matches_commit =
   1445       is_tag || (commit.size() == ref.size() &&
   1446                  std::equal(commit.begin(), commit.end(), ref.begin(),
   1447                             [](unsigned char a, unsigned char b) {
   1448                               return std::tolower(a) == std::tolower(b);
   1449                             }));
   1450   if (!is_commit_id(commit) || !matches_commit) {
   1451     return dependency_error(dep, is_tag ? "Git tag not found"
   1452                                         : "Git commit not found");
   1453   }
   1454   if (!run({"git", "-C", source, "checkout", "--quiet", "--detach",
   1455             "--no-recurse-submodules", commit})) {
   1456     return dependency_error(dep, "git checkout failed");
   1457   }
   1458 
   1459   Cmd flags;
   1460   if (!dependency_include_flags(dep, staging, flags)) return false;
   1461   std::ofstream receipt(staging / "revision", std::ios::binary);
   1462   receipt << dep.git << '\n' << dep.rev << '\n' << commit << '\n';
   1463   receipt.close();
   1464   if (!receipt) return dependency_error(dep, "cannot write cache receipt");
   1465   return true;
   1466 }
   1467 
   1468 static bool prepare_dependency(const Dependency& dep, Cmd& flags, Cmd& commits) {
   1469   const fs::path parent = DEPENDENCY_CACHE / ("dep-" + dep.name);
   1470   const fs::path root = fs::weakly_canonical(fs::absolute(DEPENDENCY_CACHE));
   1471   const std::string key = dependency_cache_key(dep);
   1472   const fs::path entry = parent / key;
   1473   if (!dependency_path_within(fs::weakly_canonical(fs::absolute(entry)), root)) {
   1474     return dependency_error(dep, "cache entry points outside the dependency cache");
   1475   }
   1476 
   1477   if (!fs::exists(entry)) {
   1478     fs::create_directories(parent);
   1479     std::error_code error;
   1480     auto nonce = std::chrono::steady_clock::now().time_since_epoch().count();
   1481     fs::path staging;
   1482     do {
   1483       staging = parent / (".tmp-" + key + "-" + std::to_string(nonce++));
   1484       error.clear();
   1485     } while (!fs::create_directory(staging, error) && !error);
   1486     if (error) return dependency_error(dep, error.message());
   1487 
   1488     const bool ready = populate_dependency(dep, staging);
   1489     if (ready) fs::rename(staging, entry, error);
   1490     if (!ready || error) {
   1491       std::error_code ignored;
   1492       const fs::path resolved = fs::canonical(staging, ignored);
   1493       if (!ignored && !dependency_path_within(root, resolved) &&
   1494           dependency_path_within(resolved, root)) {
   1495         fs::remove_all(fs::absolute(staging), ignored);
   1496       }
   1497     }
   1498     if (!ready) return false;
   1499     // Another invocation may have published the same dependency first.
   1500     if (error && !fs::exists(entry)) return dependency_error(dep, error.message());
   1501   }
   1502 
   1503   std::ifstream receipt(entry / "revision", std::ios::binary);
   1504   std::string git, rev, commit;
   1505   if (!std::getline(receipt, git) || !std::getline(receipt, rev) ||
   1506       !std::getline(receipt, commit) || git != dep.git || rev != dep.rev ||
   1507       !is_commit_id(commit)) {
   1508     return dependency_error(dep, "invalid cache receipt in " +
   1509                                       entry.generic_string());
   1510   }
   1511   if (!dependency_include_flags(dep, entry, flags)) return false;
   1512   commits.push_back(commit);
   1513   return true;
   1514 }
   1515 
   1516 static bool prepare_dependencies(Config& cfg, Cmd& commits) {
   1517   for (const Dependency& dep : cfg.dependencies) {
   1518     try {
   1519       if (!prepare_dependency(dep, cfg.flags, commits)) return false;
   1520     } catch (const fs::filesystem_error& error) {
   1521       return dependency_error(dep, error.what());
   1522     }
   1523   }
   1524   return true;
   1525 }
   1526 
   1527 /// @}
   1528 
   1529 /// @name compile_commands.json
   1530 /// Tells clangd how each file is compiled.
   1531 /// @{
   1532 
   1533 /// @brief Escapes a string for use inside a JSON string literal.
   1534 ///
   1535 /// Only double quotes and backslashes are handled; paths and flags never
   1536 /// contain control characters.
   1537 ///
   1538 /// @param s Raw string.
   1539 /// @return The escaped string, without surrounding quotes.
   1540 static std::string json_escape(const std::string& s) {
   1541   std::string out;
   1542   for (char c : s) {
   1543     if (c == '"' || c == '\\') out += '\\';
   1544     out += c;
   1545   }
   1546   return out;
   1547 }
   1548 
   1549 /// @brief Writes `compile_commands.json` to the current directory.
   1550 ///
   1551 /// One object is written per file:
   1552 /// @code{.json}
   1553 ///     {"directory": "<cwd>", "file": "<source>", "arguments": ["<argv>", ...]}
   1554 /// @endcode
   1555 ///
   1556 /// @param sources Every source file.
   1557 /// @param cmds    Compile commands; `cmds[i]` compiles `sources[i]`.
   1558 static void write_compile_commands(const std::vector<fs::path>& sources,
   1559                                    const std::vector<Cmd>& cmds) {
   1560   std::ofstream out("compile_commands.json");
   1561   std::string dir = json_escape(fs::current_path().string());
   1562   out << "[\n";
   1563   for (size_t i = 0; i < sources.size(); ++i) {
   1564     out << "  {\"directory\": \"" << dir << "\", \"file\": \""
   1565         << json_escape(sources[i].generic_string()) << "\", \"arguments\": [";
   1566     for (size_t j = 0; j < cmds[i].size(); j++) {
   1567       out << (j ? ", " : "") << '"' << json_escape(cmds[i][j]) << '"';
   1568     }
   1569     // JSON forbids a trailing comma, so the last entry gets none.
   1570     out << "]}" << (i + 1 < sources.size() ? "," : "") << "\n";
   1571   }
   1572   out << "]\n";
   1573 }
   1574 
   1575 /// @}
   1576 
   1577 /// @name Compiling and linking
   1578 /// The steps shared by building the program and building the tests.
   1579 /// @{
   1580 
   1581 /// @brief One source file and how it is compiled.
   1582 struct Unit {
   1583   fs::path src;
   1584   fs::path obj;  ///< Where the compiled object goes.
   1585   Cmd cmd;       ///< The command that compiles #src into #obj.
   1586   bool stale;    ///< Whether #obj is out of date.
   1587 };
   1588 
   1589 /// @brief Plans the compilation of the sources found under a directory.
   1590 ///
   1591 /// Nothing is compiled here. The result is sorted by path, so that the order of
   1592 /// the output and of the link line does not depend on the file system.
   1593 ///
   1594 /// @param cfg         Project settings.
   1595 /// @param dir         Directory searched recursively for `.cpp` and `.mm`.
   1596 /// @param tests_only  Take only files whose name ends in `_test`.
   1597 /// @param extra_flags Flags added after the project's compile flags.
   1598 /// @param flags_time  Modification time of whatever the flags come from.
   1599 /// @return One unit per file that is built on this platform.
   1600 static std::vector<Unit> plan_units(const Config& cfg, const fs::path& dir,
   1601                                     bool tests_only, const Cmd& extra_flags,
   1602                                     fs::file_time_type flags_time) {
   1603   std::vector<Unit> units;
   1604   for (const fs::directory_entry& entry :
   1605        fs::recursive_directory_iterator(dir)) {
   1606     fs::path src = entry.path();
   1607     if (src.extension() != ".cpp" && src.extension() != ".mm") continue;
   1608     if (tests_only && !src.stem().string().ends_with("_test")) continue;
   1609     if (!is_built_here(src)) continue;
   1610 
   1611     // src/foo/bar.cpp -> build/obj/src/foo/bar.cpp.o
   1612     // The full file name is kept and a suffix appended, so bar.cpp and
   1613     // bar.mm do not collide.
   1614     fs::path obj = cfg.out_dir / "obj" / (src.string() + ".o");
   1615     fs::path dep = cfg.out_dir / "obj" / (src.string() + ".d");
   1616     fs::create_directories(obj.parent_path());
   1617 
   1618     // -MD -MF <dep>: write the dependency list to dep while compiling.
   1619     Cmd cmd = {cfg.compiler};
   1620     cmd.insert(cmd.end(), cfg.flags.begin(), cfg.flags.end());
   1621     cmd.insert(cmd.end(), extra_flags.begin(), extra_flags.end());
   1622     if (src.extension() == ".mm") {
   1623       cmd.insert(cmd.end(), cfg.objcxx_flags.begin(), cfg.objcxx_flags.end());
   1624     }
   1625     cmd.insert(cmd.end(), {"-MD", "-MF", dep.string(), "-c", src.string(), "-o",
   1626                            obj.string()});
   1627 
   1628     units.push_back({src, obj, cmd, needs_compile(obj, dep, flags_time)});
   1629   }
   1630   std::sort(units.begin(), units.end(),
   1631             [](const Unit& a, const Unit& b) { return a.src < b.src; });
   1632   return units;
   1633 }
   1634 
   1635 /// @brief Compiles those of the given units that are stale, in parallel.
   1636 ///
   1637 /// Each file is announced with a counter, and a failure ends with a line naming
   1638 /// the files that did not compile, after the diagnostics of the compiler.
   1639 ///
   1640 /// @param units    The units to consider; the up to date ones are skipped.
   1641 /// @param compiled If not null, receives the number of files compiled.
   1642 /// @return `true` if every compilation succeeded.
   1643 static bool compile_stale(const std::vector<const Unit*>& units,
   1644                           size_t* compiled = nullptr) {
   1645   std::vector<const Unit*> stale;
   1646   for (const Unit* unit : units) {
   1647     if (unit->stale) stale.push_back(unit);
   1648   }
   1649   if (compiled != nullptr) *compiled = stale.size();
   1650 
   1651   std::vector<Cmd> cmds;
   1652   for (size_t i = 0; i < stale.size(); ++i) {
   1653     log_step(
   1654         Style::Cyan, "compile", stale[i]->src.generic_string(),
   1655         "[" + std::to_string(i + 1) + "/" + std::to_string(stale.size()) + "]");
   1656     if (verbose) print_command(stale[i]->cmd);
   1657     cmds.push_back(stale[i]->cmd);
   1658   }
   1659 
   1660   // hardware_concurrency may return 0, meaning "unknown".
   1661   unsigned jobs = std::thread::hardware_concurrency();
   1662   std::vector<size_t> failed;
   1663   if (run_all(cmds, jobs ? jobs : 4, &failed)) return true;
   1664 
   1665   std::string names;
   1666   for (size_t index : failed) {
   1667     names += (names.empty() ? "" : ", ") + stale[index]->src.generic_string();
   1668   }
   1669   print_error("failed to compile " + (names.empty() ? "the sources" : names));
   1670   return false;
   1671 }
   1672 
   1673 /// @brief Links object files into an executable, unless it is up to date.
   1674 ///
   1675 /// "Did we compile anything this time?" is not a valid test for being up to
   1676 /// date: if the last run compiled successfully but failed to link, nothing is
   1677 /// stale now and yet the link is still needed. So the executable is compared
   1678 /// with the objects themselves.
   1679 ///
   1680 /// @param cfg     Project settings.
   1681 /// @param objects The objects to link.
   1682 /// @param exe     The executable to produce.
   1683 /// @param linked  If not null, tells whether a link was done.
   1684 /// @return `true` if the executable is up to date afterwards.
   1685 static bool link_if_needed(const Config& cfg,
   1686                            const std::vector<fs::path>& objects,
   1687                            const fs::path& exe, bool* linked = nullptr) {
   1688   if (linked != nullptr) *linked = false;
   1689   bool needed = !fs::exists(exe);
   1690   for (const fs::path& obj : objects) {
   1691     if (!needed && fs::last_write_time(obj) > fs::last_write_time(exe)) {
   1692       needed = true;
   1693     }
   1694   }
   1695   if (!needed) return true;
   1696 
   1697   log_step(Style::Cyan, "link", exe.generic_string());
   1698   fs::create_directories(exe.parent_path());
   1699   Cmd link = {cfg.compiler};
   1700   for (const fs::path& obj : objects) link.push_back(obj.string());
   1701   link.insert(link.end(), cfg.link_flags.begin(), cfg.link_flags.end());
   1702   link.insert(link.end(), {"-o", exe.string()});
   1703   if (verbose) print_command(link);
   1704   if (linked != nullptr) *linked = true;
   1705   if (run(link)) return true;
   1706   print_error("failed to link " + exe.generic_string());
   1707   return false;
   1708 }
   1709 
   1710 /// @}
   1711 
   1712 /// @name Tests
   1713 /// Every `*_test.cpp` under the tests directory is a program of its own. It is
   1714 /// linked with all the sources of the project except the entry point, and it
   1715 /// passes if it exits with status 0.
   1716 /// @{
   1717 
   1718 /// @brief The name a test is listed and selected by: its path inside the tests
   1719 ///        directory, without the extension (`render/raster_test`).
   1720 static std::string test_name(const Config& cfg, const fs::path& src) {
   1721   fs::path name = src.lexically_relative(cfg.tests_dir);
   1722   name.replace_extension("");
   1723   return name.generic_string();
   1724 }
   1725 
   1726 /// @brief Where the executable of a test is put.
   1727 static fs::path test_exe(const Config& cfg, const fs::path& src) {
   1728   return cfg.out_dir / "tests" / (test_name(cfg, src) + EXE_SUFFIX);
   1729 }
   1730 
   1731 /// @}
   1732 
   1733 /// @name Command line
   1734 /// @{
   1735 
   1736 /// @brief Prints the usage of the builder.
   1737 static void print_usage(std::FILE* out) {
   1738   std::fputs(R"usage(kumoko, the build tool of Kumo
   1739 
   1740 Usage:
   1741   kumoko [options] [command] [name]
   1742 
   1743 Commands:
   1744   build          Compile and link the program (the default)
   1745   run            Build, then run the program
   1746   test [name]    Build and run the tests; with a name, only those whose path
   1747                  contains it, e.g. `test raster` or `test e2e/`
   1748   clean          Delete all build output
   1749   help           Show this text
   1750 
   1751 Options:
   1752   --debug        Build with debug symbols and no optimization (default)
   1753   --release      Build with optimizations enabled
   1754   --asan         Build with Address and UndefinedBehavior sanitizers
   1755   -v, --verbose  Print full commands
   1756   -q, --quiet    With test: one line per test program, not one per test case
   1757   -h, --help     Show this text
   1758 
   1759 Run it from the project root; its settings are in kumo.toml. Output is colored
   1760 on a terminal; set NO_COLOR to turn that off.
   1761 )usage",
   1762              out);
   1763 }
   1764 
   1765 /// @brief What the command line asks for.
   1766 struct Args {
   1767   std::string command = "build";
   1768   std::string pattern;  ///< For `test`: part of the name of the tests to run.
   1769   std::string profile = "debug";  ///< Build profile: debug, release, or asan.
   1770 };
   1771 
   1772 /// @brief Reads the command line.
   1773 ///
   1774 /// Prints the usage and exits for `help`, `-h` and `--help`; prints an error
   1775 /// and exits with status 2 for anything it does not understand, instead of
   1776 /// guessing what was meant.
   1777 static Args parse_args(int argc, char** argv) {
   1778   const auto mistake = [](const std::string& message) {
   1779     print_error(message);
   1780     std::fprintf(stderr, "Run `kumoko help` for the usage.\n");
   1781     std::exit(2);
   1782   };
   1783 
   1784   Args args;
   1785   std::vector<std::string> words;
   1786   for (int i = 1; i < argc; ++i) {
   1787     const std::string arg = argv[i];
   1788     if (arg == "-h" || arg == "--help") {
   1789       print_usage(stdout);
   1790       std::exit(0);
   1791     } else if (arg == "--debug") {
   1792       args.profile = "debug";
   1793     } else if (arg == "--release") {
   1794       args.profile = "release";
   1795     } else if (arg == "--asan") {
   1796       args.profile = "asan";
   1797     } else if (arg == "-v" || arg == "--verbose") {
   1798       verbose = true;
   1799     } else if (arg == "-q" || arg == "--quiet") {
   1800       quiet = true;
   1801     } else if (arg.size() > 1 && arg[0] == '-') {
   1802       mistake("unknown option '" + arg + "'");
   1803     } else {
   1804       words.push_back(arg);
   1805     }
   1806   }
   1807 
   1808   if (!words.empty()) args.command = words[0];
   1809   if (args.command == "help") {
   1810     print_usage(stdout);
   1811     std::exit(0);
   1812   }
   1813   if (args.command != "build" && args.command != "run" &&
   1814       args.command != "test" && args.command != "clean") {
   1815     mistake("unknown command '" + args.command + "'");
   1816   }
   1817   if (words.size() > (args.command == "test" ? 2u : 1u)) {
   1818     mistake("too many arguments for '" + args.command + "'");
   1819   }
   1820   if (words.size() == 2) args.pattern = words[1];
   1821   return args;
   1822 }
   1823 
   1824 /// @}
   1825 
   1826 /// @name Entry point
   1827 /// @{
   1828 
   1829 /// @brief Recompiles and restarts the builder if its source has changed.
   1830 ///
   1831 /// If #SELF_SRC is newer than the builder's executable, it is recompiled
   1832 /// and the new binary takes over with the same arguments. The new binary is
   1833 /// always newer than the source, so this cannot loop forever.
   1834 ///
   1835 /// On macOS and Linux `execv` replaces the current process. Windows has no
   1836 /// equivalent, so the running executable is renamed out of the way, the new
   1837 /// one is built under the original name, and it is then run as a child
   1838 /// whose exit status becomes ours.
   1839 ///
   1840 /// @param argc Argument count of main().
   1841 /// @param argv Argument vector of main(), forwarded to the new binary.
   1842 static void rebuild_self([[maybe_unused]] int argc, char** argv) {
   1843 #if defined(_WIN32)
   1844   // Left over from the previous self-rebuild; it could not be deleted then
   1845   // because it was still running. Failure to delete it is harmless.
   1846   std::error_code ignored;
   1847   fs::remove(SELF_OLD_EXE, ignored);
   1848 #endif
   1849 
   1850   if (fs::last_write_time(SELF_SRC) <= fs::last_write_time(SELF_EXE)) return;
   1851 
   1852   log_step(Style::Cyan, "self",
   1853            SELF_SRC.generic_string() + " changed, rebuilding the builder");
   1854   const Cmd compile = {SELF_CXX, "-std=c++20", SELF_SRC.string(), "-o",
   1855                        SELF_EXE.string()};
   1856 
   1857 #if defined(_WIN32)
   1858   std::error_code ec;
   1859   fs::rename(SELF_EXE, SELF_OLD_EXE, ec);
   1860   if (ec) {
   1861     print_error("cannot move " + SELF_EXE.string() + " aside: " + ec.message());
   1862     std::exit(1);
   1863   }
   1864   if (!run(compile)) {
   1865     // Put the old builder back so the next run can try again.
   1866     fs::rename(SELF_OLD_EXE, SELF_EXE, ec);
   1867     print_error("failed to rebuild " + SELF_SRC.generic_string());
   1868     std::exit(1);
   1869   }
   1870   Cmd relaunch(argv, argv + argc);
   1871   relaunch[0] = SELF_EXE.string();
   1872   std::exit(run(relaunch) ? 0 : 1);
   1873 #else
   1874   if (!run(compile)) {
   1875     print_error("failed to rebuild " + SELF_SRC.generic_string());
   1876     std::exit(1);
   1877   }
   1878 
   1879   execv(SELF_EXE.c_str(), argv);
   1880   // execv does not return on success; reaching this line means it failed.
   1881   print_error(std::string("cannot restart the builder: ") +
   1882               std::strerror(errno));
   1883   std::exit(1);
   1884 #endif
   1885 }
   1886 
   1887 /// @brief Builds the project, runs it, or builds and runs its tests.
   1888 ///
   1889 /// @param argc Argument count.
   1890 /// @param argv The command line, see print_usage().
   1891 /// @return 0 on success, 1 if building failed or a test failed, 2 for a
   1892 ///         mistake on the command line; for `run`, the status of the program if
   1893 ///         it failed.
   1894 int main(int argc, char** argv) {
   1895   using Clock = std::chrono::steady_clock;
   1896   init_terminal();
   1897   rebuild_self(argc, argv);
   1898   const Args args = parse_args(argc, argv);
   1899   Config cfg = load_config(args.profile);
   1900   const Clock::time_point began = Clock::now();
   1901 
   1902   if (!cfg.dependencies.empty() && !valid_dependency_cache(cfg)) return 1;
   1903   if (args.command == "clean") {
   1904     const std::uintmax_t removed = fs::remove_all(cfg.clean_dir);
   1905     if (removed > 0) {
   1906       log_step(Style::Cyan, "clean",
   1907                "removed " + cfg.clean_dir.generic_string() + "/");
   1908     } else {
   1909       log_step(Style::Cyan, "clean",
   1910                "nothing to remove, " + cfg.clean_dir.generic_string() +
   1911                    "/ does not exist");
   1912     }
   1913     return 0;
   1914   }
   1915   const bool testing = args.command == "test";
   1916   const std::string& filter = args.pattern;
   1917 
   1918   if (!fs::is_directory(cfg.src_dir)) {
   1919     config_error(0, "the source directory '" + cfg.src_dir.string() +
   1920                         "' (key 'src') does not exist");
   1921   }
   1922   const bool has_tests = fs::is_directory(cfg.tests_dir);
   1923   if (testing && !has_tests) {
   1924     config_error(0, "the tests directory '" + cfg.tests_dir.string() +
   1925                         "' (key 'tests') does not exist");
   1926   }
   1927 
   1928   Cmd dependency_commits;
   1929   if (!prepare_dependencies(cfg, dependency_commits)) return 1;
   1930   check_toolchain_cache(cfg, dependency_commits);
   1931 
   1932   // The compile flags come from the builder and from kumo.toml, so an object
   1933   // file older than either is stale.
   1934   fs::file_time_type flags_time =
   1935       std::max(fs::last_write_time(SELF_EXE), fs::last_write_time(CONFIG_FILE));
   1936 
   1937   // Step 1: plan the compilation of the sources and of the tests, and tell
   1938   // clangd about all of them whatever the mode.
   1939   std::vector<Unit> units = plan_units(cfg, cfg.src_dir, false, {}, flags_time);
   1940   std::vector<Unit> tests;
   1941   if (has_tests) {
   1942     tests = plan_units(cfg, cfg.tests_dir, true,
   1943                        {"-I" + cfg.tests_dir.generic_string()}, flags_time);
   1944   }
   1945   std::vector<fs::path> sources;
   1946   std::vector<Cmd> all_cmds;
   1947   for (const std::vector<Unit>* group : {&units, &tests}) {
   1948     for (const Unit& unit : *group) {
   1949       sources.push_back(unit.src);
   1950       all_cmds.push_back(unit.cmd);
   1951     }
   1952   }
   1953   write_compile_commands(sources, all_cmds);
   1954 
   1955   // Step 2: decide what to compile. In test mode the entry point is left out
   1956   // of the program's objects, because every test has a `main` of its own.
   1957   std::vector<const Unit*> to_compile;
   1958   std::vector<fs::path> objects;  // what a final link gets, tests excluded
   1959   bool found_entry = false;
   1960   for (const Unit& unit : units) {
   1961     if (testing &&
   1962         unit.src.lexically_normal() == cfg.entry.lexically_normal()) {
   1963       found_entry = true;
   1964       continue;
   1965     }
   1966     objects.push_back(unit.obj);
   1967     to_compile.push_back(&unit);
   1968   }
   1969   if (testing && !found_entry) {
   1970     config_error(0, "the entry file '" + cfg.entry.string() +
   1971                         "' (key 'entry') is not among the sources");
   1972   }
   1973 
   1974   std::vector<const Unit*> selected;  // the tests to build and run
   1975   if (testing) {
   1976     for (const Unit& test : tests) {
   1977       if (test_name(cfg, test.src).find(filter) == std::string::npos) continue;
   1978       selected.push_back(&test);
   1979       to_compile.push_back(&test);
   1980     }
   1981     if (selected.empty()) {
   1982       print_error(filter.empty() ? "there are no tests in " +
   1983                                        cfg.tests_dir.generic_string() + "/"
   1984                                  : "no test matches '" + filter + "'");
   1985       return 1;
   1986     }
   1987   }
   1988 
   1989   // Step 3: compile whatever is stale, in parallel.
   1990   size_t compiled = 0;
   1991   if (!compile_stale(to_compile, &compiled)) return 1;
   1992 
   1993   // Step 4: link, and run or report.
   1994   if (!testing) {
   1995     bool linked = false;
   1996     if (!link_if_needed(cfg, objects, cfg.exe, &linked)) return 1;
   1997     if (args.command == "run") {
   1998       log_step(Style::Cyan, "run", cfg.exe.generic_string());
   1999       // Windows wants backslashes in the path of a program to start.
   2000       fs::path program = cfg.exe;
   2001       program.make_preferred();
   2002       const ExitStatus status = run_status({program.string()});
   2003       if (status.ok()) return 0;
   2004       print_error(cfg.exe.generic_string() + " " + describe(status));
   2005       return exit_code_of(status);
   2006     }
   2007     const std::string took = format_duration(Clock::now() - began);
   2008     if (compiled == 0 && !linked) {
   2009       log_step(Style::Green, "built",
   2010                cfg.exe.generic_string() + " is up to date");
   2011     } else {
   2012       log_step(Style::Green, "built", cfg.exe.generic_string(),
   2013                plural(compiled, "file") + " compiled in " + took);
   2014     }
   2015     return 0;
   2016   }
   2017 
   2018   size_t name_width = 0;
   2019   for (const Unit* test : selected) {
   2020     name_width = std::max(name_width, test_name(cfg, test->src).size());
   2021   }
   2022 
   2023   // First every test program is linked, so that the lines about building stay
   2024   // together and none of them falls between the blocks of two programs; a
   2025   // program that does not link stops the run before any test has started.
   2026   bool built_something = compiled > 0;
   2027   for (const Unit* test : selected) {
   2028     std::vector<fs::path> test_objects = {test->obj};
   2029     test_objects.insert(test_objects.end(), objects.begin(), objects.end());
   2030     bool linked = false;
   2031     if (!link_if_needed(cfg, test_objects, test_exe(cfg, test->src), &linked)) {
   2032       return 1;
   2033     }
   2034     built_something = built_something || linked;
   2035   }
   2036   if (built_something && !quiet) std::printf("\n");
   2037 
   2038   std::vector<std::string> failed;
   2039   for (const Unit* test : selected) {
   2040     const fs::path exe = test_exe(cfg, test->src);
   2041 
   2042     // The test program lists its cases as it runs them. It is told whether it
   2043     // may color its output and rewrite its current line, which a terminal
   2044     // allows and a pipe or a file does not, and whether to list only failures.
   2045     const std::string name = test_name(cfg, test->src);
   2046     fs::path program = exe;
   2047     program.make_preferred();
   2048     Cmd command = {program.string()};
   2049     if (color_enabled) {
   2050       command.push_back("--color");
   2051       command.push_back("--live");
   2052     }
   2053     if (quiet) {
   2054       command.push_back("--quiet");
   2055     } else {
   2056       std::printf("%s\n", rule('-', name).c_str());
   2057     }
   2058 
   2059     const Clock::time_point test_began = Clock::now();
   2060     const ExitStatus status = run_status(command);
   2061     const std::string took = format_duration(Clock::now() - test_began);
   2062 
   2063     // A test program that fails its checks exits with status 1; anything else
   2064     // that is not success (a signal, another status) is a crash.
   2065     const bool crashed =
   2066         !status.ok() && !(status.signal == 0 && status.code == 1);
   2067     // A crash leaves the line of the test case that was running unfinished.
   2068     if (crashed && !quiet) std::printf("\n");
   2069     // The verdict is in the same column as the labels of the other lines, the
   2070     // name is padded to the longest one and the time is right aligned, so that
   2071     // the lines of all the programs line up.
   2072     const std::string verdict = status.ok() ? "PASS"
   2073                                 : crashed   ? "CRASH"
   2074                                             : "FAIL";
   2075     if (!status.ok()) failed.push_back(name);
   2076     std::printf(
   2077         "%s %s  %s%s\n",
   2078         paint(status.ok() ? Style::Green : Style::Red, pad(verdict, 8)).c_str(),
   2079         pad(name, name_width).c_str(),
   2080         paint(Style::Dim, pad_left(took, 7)).c_str(),
   2081         crashed ? ("  " + paint(Style::Red, describe(status))).c_str() : "");
   2082     if (!quiet) std::printf("\n");
   2083   }
   2084 
   2085   // A heavier rule sets the summary off from the programs above it.
   2086   const std::string total = " in " + format_duration(Clock::now() - began);
   2087   if (quiet) {
   2088     std::printf("\n");
   2089   } else {
   2090     std::printf("%s\n", rule('=').c_str());
   2091   }
   2092   if (failed.empty()) {
   2093     std::printf(
   2094         "%s%s\n",
   2095         paint(Style::Green, plural(selected.size(), "test program") + " passed")
   2096             .c_str(),
   2097         paint(Style::Dim, total).c_str());
   2098     return 0;
   2099   }
   2100   std::printf(
   2101       "%s%s\n",
   2102       paint(Style::Red, std::to_string(failed.size()) + " of " +
   2103                             plural(selected.size(), "test program") + " failed")
   2104           .c_str(),
   2105       paint(Style::Dim, total).c_str());
   2106   return 1;
   2107 }
   2108 
   2109 /// @}