/// @file kumo_builder.cpp /// @brief The Kumo builder: the build script is itself a C++ program. /// /// Supported platforms: macOS, Linux and Windows (clang++ must be on `PATH`). /// The builder is built on the machine that uses it, so the host is also the /// target; cross-compilation is not supported. /// /// How the project is organized and compiled is described by `kumo.toml` in the /// project root, see "Project configuration" below; this file only holds the /// logic. /// /// Bootstrap (once, from the project root): /// @code /// clang++ -std=c++20 kumo_builder.cpp -o kumoko # macOS, Linux /// clang++ -std=c++20 kumo_builder.cpp -o kumoko.exe # Windows /// @endcode /// /// Usage (always from the project root; on Windows type `kumoko` without the /// leading `./`): /// @code /// ./kumoko # incremental build /// ./kumoko run # incremental build, then run the executable /// ./kumoko test [name] # build and run the tests, only those whose name /// # contains `name` if one is given /// ./kumoko clean # delete all build output /// ./kumoko help # show the usage; also -h and --help /// ./kumoko -v ... # print full commands /// ./kumoko -q test # one line per test program, not per test case /// @endcode /// /// Output is colored when it goes to a terminal; set `NO_COLOR` to turn that /// off. The exit status is 0 on success, 1 if building or a test failed (or the /// status of the program that `run` ran), and 2 for a mistake on the command /// line. /// /// Platform-specific source files are marked by their name, see /// is_built_here(). /// /// @note There is no need to bootstrap again after editing this file: on the /// next run the builder notices it is out of date and recompiles itself. /// Editing `kumo.toml` needs no bootstrap either; it recompiles the /// project. #if defined(_WIN32) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include #include #else #include #include #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if !defined(_WIN32) /// @brief The environment of the current process, provided by libc. /// /// Passed unchanged to every child process. extern char** environ; #endif namespace fs = std::filesystem; /// @brief A command as an argument list; element 0 is the program name. /// /// Commands are never joined into one string for a shell to parse, so paths /// containing spaces or quotes need no escaping. using Cmd = std::vector; /// @name Builder constants /// What belongs to the builder itself. The settings of the project it builds /// live in `kumo.toml`, see "Project configuration". /// @{ /// @brief Operating systems the builder knows about. enum class Platform { Mac, Linux, Windows }; /// @brief The platform being built for. #if defined(__APPLE__) static constexpr Platform HOST = Platform::Mac; #elif defined(__linux__) static constexpr Platform HOST = Platform::Linux; #elif defined(_WIN32) static constexpr Platform HOST = Platform::Windows; #else #error "kumo_builder supports only macOS, Linux and Windows" #endif /// @brief The name of #HOST in `kumo.toml`, as a table header. static constexpr const char* HOST_NAME = HOST == Platform::Mac ? "mac" : HOST == Platform::Linux ? "linux" : "windows"; /// @brief File name extension of executables on this platform. static constexpr const char* EXE_SUFFIX = HOST == Platform::Windows ? ".exe" : ""; /// @brief The compiler that rebuilds the builder itself. /// /// Fixed, because it is needed before `kumo.toml` is read. The compiler of the /// project is the `compiler` key of that file. static const char* const SELF_CXX = "clang++"; static const fs::path SELF_SRC = "kumo_builder.cpp"; /// @brief Path of the builder's own executable. /// /// A fixed name instead of `argv[0]`, because on Windows the user may type /// `kumoko` without the `.exe` that the file actually has. static const fs::path SELF_EXE = std::string("kumoko") + EXE_SUFFIX; /// @brief Where the running builder is moved to while it replaces itself. /// /// Windows refuses to overwrite a running executable but allows renaming it. static const fs::path SELF_OLD_EXE = std::string("kumoko.old") + EXE_SUFFIX; /// @brief The project configuration file, in the project root. static const fs::path CONFIG_FILE = "kumo.toml"; /// @} /// @name Terminal output /// How the builder talks to the person at the terminal: colors, labels in a /// fixed column, durations, and errors. /// @{ /// @brief Whether messages are colored. Set once by init_terminal(). static bool color_enabled = false; /// @brief Whether commands are printed in full. Set by `-v` or `--verbose`. static bool verbose = false; /// @brief Whether `test` shows one line per test program instead of one per /// test case. Set by `-q` or `--quiet`. static bool quiet = false; /// @brief The colors a message can have. enum class Style { Plain, Dim, Red, Green, Cyan }; /// @brief Decides whether to use colors. /// /// Only when standard output is a terminal, and `NO_COLOR` is not set (see /// https://no-color.org). On Windows the terminal must also accept escape /// codes, which this turns on. static void init_terminal() { const char* no_color = std::getenv("NO_COLOR"); if (no_color != nullptr && no_color[0] != '\0') return; #if defined(_WIN32) if (!_isatty(_fileno(stdout))) return; HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); DWORD mode = 0; if (out == INVALID_HANDLE_VALUE || !GetConsoleMode(out, &mode)) return; if (!SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) return; color_enabled = true; #else color_enabled = isatty(STDOUT_FILENO) != 0; #endif } /// @brief Wraps @p text in the escape codes of @p style, if colors are on. static std::string paint(Style style, const std::string& text) { if (!color_enabled || style == Style::Plain) return text; const char* code = "0"; switch (style) { case Style::Dim: code = "2"; break; case Style::Red: code = "31"; break; case Style::Green: code = "32"; break; case Style::Cyan: code = "36"; break; case Style::Plain: break; } return std::string("\033[") + code + "m" + text + "\033[0m"; } /// @brief Pads @p text on the right with spaces up to @p width characters. static std::string pad(const std::string& text, size_t width) { return text.size() >= width ? text : text + std::string(width - text.size(), ' '); } /// @brief Pads @p text with spaces on the left up to @p width characters. static std::string pad_left(const std::string& text, size_t width) { return text.size() >= width ? text : std::string(width - text.size(), ' ') + text; } /// @brief "1 test program" or "3 test programs". static std::string plural(size_t count, const std::string& noun) { return std::to_string(count) + " " + noun + (count == 1 ? "" : "s"); } /// @brief Prints one line of progress: a label in a fixed column, then a text, /// then an optional note in a dimmer color. /// /// @code /// compile src/main.cpp [1/3] /// link build/kumo /// @endcode static void log_step(Style style, const std::string& label, const std::string& text, const std::string& note = "") { std::string line = paint(style, pad(label, 8)) + " " + text; if (!note.empty()) line += " " + paint(Style::Dim, note); std::printf("%s\n", line.c_str()); } /// @brief The width of the lines drawn between test programs: that of the /// longest line a test case takes, see `kNameWidth` in tests/check.h. constexpr size_t kRuleWidth = 75; /// @brief A dimmed line of @p fill characters, kRuleWidth wide, with the /// @p title set into it if there is one: /// @code /// -- unit/raster_test --------------------------------------------------- /// @endcode static std::string rule(char fill, const std::string& title = "") { if (title.empty()) return paint(Style::Dim, std::string(kRuleWidth, fill)); const std::string lead(2, fill); const size_t used = lead.size() + 1 + title.size() + 1; const std::string tail(used < kRuleWidth ? kRuleWidth - used : 2, fill); return paint(Style::Dim, lead + " ") + paint(Style::Cyan, title) + paint(Style::Dim, " " + tail); } /// @brief Prints an error message on standard error. /// /// Standard output is flushed first, so that the message does not overtake /// lines printed before it when both go to the same place. static void print_error(const std::string& message) { std::fflush(stdout); std::fprintf(stderr, "%s %s\n", paint(Style::Red, "error:").c_str(), message.c_str()); } /// @brief Formats a duration for people: `87 ms`, `1.24 s`, `2 min 3 s`. static std::string format_duration(std::chrono::steady_clock::duration time) { const auto ms = std::chrono::duration_cast(time).count(); char buffer[48]; if (ms < 1000) { std::snprintf(buffer, sizeof(buffer), "%lld ms", static_cast(ms)); } else if (ms < 60000) { std::snprintf(buffer, sizeof(buffer), "%.2f s", static_cast(ms) / 1000.0); } else { std::snprintf(buffer, sizeof(buffer), "%lld min %lld s", static_cast(ms / 60000), static_cast(ms % 60000 / 1000)); } return buffer; } /// @brief Prints a command on one line, dimmed, as `-v` does. Arguments with /// spaces or quotes are put in quotes, which is for reading only. static void print_command(const Cmd& cmd) { std::string line = "$"; for (const std::string& arg : cmd) { const bool plain = !arg.empty() && arg.find_first_of(" \t\"'") == std::string::npos; line += ' '; line += plain ? arg : "\"" + arg + "\""; } std::printf(" %s\n", paint(Style::Dim, line).c_str()); } /// @} /// @name Project configuration /// Reading `kumo.toml`, which says how the project is organized and compiled. /// /// The file is a small subset of TOML (https://toml.io). The builder has no /// dependencies, so it parses the file itself, and accepts only this: /// - `#` starts a comment that runs to the end of the line; /// - `key = "text"` assigns a string; inside double quotes the only escapes /// are a backslash followed by a backslash or by a double quote, and single /// quotes take everything literally, backslashes included; /// - `key = ["a", "b"]` assigns a list of strings; it may span several lines, /// end with a comma and contain comments; /// - `[mac]`, `[linux]` and `[windows]` start a table whose keys apply to that /// platform only. /// /// Anything else (numbers, booleans, dates, inline tables, dotted keys, /// multi-line strings) is a syntax error. So is a key the builder does not /// know, so that a typo is never silently ignored. /// /// All top-level keys are optional: /// - `name`: name of the executable, without the `.exe` that Windows adds /// (default: the name of the project directory); /// - `compiler`: the C++ compiler (default: `clang++`); /// - `src`: the source tree, searched recursively (default: `src`); /// - `out`: where all build output goes (default: `build`); /// - `entry`: the source file that holds `main` of the program (default: /// `main.cpp` inside `src`); `test` mode leaves it out, because every test /// program has a `main` of its own; /// - `tests`: the directory of test programs, see "Tests" (default: `tests`); /// - `flags`: compile flags for every source file; /// - `objcxx_flags`: extra compile flags for `.mm` files only; /// - `link`: link flags. /// /// A platform or profile table may hold `compiler`, `flags` and `link`. On that /// platform or profile `compiler` overrides the top-level setting, and /// `flags`/`link` are appended. /// A `[deps.name]` table declares a Git URL, a tag or full commit ID, and /// header directories relative to the dependency's checkout. /// @{ /// @brief The source, revision and header directories of a Git dependency. struct Dependency { std::string name; std::string git; std::string rev; Cmd include_dirs; }; /// @brief The settings of the project, as read from #CONFIG_FILE. /// /// Output layout, for `src = "src"`, `out = "build"`, `name = "kumo"` and the /// default `debug` profile: // clang-format off /// @code /// build/debug/obj/src/foo/bar.cpp.o object file (mirrors the source tree) /// build/debug/obj/src/foo/bar.cpp.d list of headers that file depends on /// build/debug/kumo final executable (kumo.exe on Windows) /// @endcode // clang-format on struct Config { std::string compiler; fs::path src_dir; fs::path clean_dir; ///< Root output directory deleted by `clean`. fs::path out_dir; ///< Active profile directory inside #clean_dir. fs::path entry; ///< The source file with `main`, inside #src_dir. fs::path tests_dir; ///< Directory of test programs. fs::path exe; ///< The final executable, inside #out_dir. Cmd flags; ///< Compile flags, with platform and profile added. Cmd objcxx_flags; ///< Extra compile flags for `.mm` files. Cmd link_flags; ///< Link flags, with platform and profile added. std::vector dependencies; }; /// @brief Reports a problem with #CONFIG_FILE and exits. /// /// @param line 1-based line the problem is on, or 0 if it is not about a line. /// @param msg What is wrong. [[noreturn]] static void config_error(int line, const std::string& msg) { const std::string file = CONFIG_FILE.string(); print_error(line > 0 ? file + ":" + std::to_string(line) + ": " + msg : file + ": " + msg); std::exit(EXIT_FAILURE); } /// @brief The tables a platform can have, named like #HOST_NAME. static constexpr const char* PLATFORM_TABLES[] = {"mac", "linux", "windows"}; /// @brief The profile tables supported in `kumo.toml`. static constexpr const char* PROFILE_TABLES[] = {"debug", "release", "asan"}; static constexpr std::string_view DEPENDENCY_PREFIX = "deps."; static const fs::path DEPENDENCY_CACHE = ".cache/kumoko/deps"; /// @brief One `key = value` pair of the file. struct Entry { bool is_list = false; ///< Which of #text and #list holds the value. std::string text; Cmd list; int line = 0; ///< Where the pair was written, for error messages. }; /// @brief Every pair of the file; a key inside a table is stored as /// `"table.key"`. using Table = std::map; /// @brief Parser for the TOML subset described above. /// /// Reports a syntax error with config_error(), which exits. class ConfigParser { public: explicit ConfigParser(const std::string& text) : text_(text) { // Some Windows editors start a UTF-8 file with a byte order mark. if (text_.starts_with("\xEF\xBB\xBF")) text_.erase(0, 3); } /// @brief Parses the whole text. Table parse(std::map& dependency_tables) { Table table; std::string section; // the table being filled; empty at the top level std::vector tables_seen; for (skip_blank(true); pos_ < text_.size(); skip_blank(true)) { if (text_[pos_] == '[') { const int line = line_here(); section = parse_header(); // A table may be opened only once, as in TOML, so that its keys are // never split over two places. if (std::find(tables_seen.begin(), tables_seen.end(), section) != tables_seen.end()) { config_error(line_here(), "duplicate table '[" + section + "]'"); } tables_seen.push_back(section); if (section.starts_with(DEPENDENCY_PREFIX)) { dependency_tables.emplace(section, line); } } else { parse_pair(section, table); } } return table; } private: std::string text_; size_t pos_ = 0; // next character to read /// @brief The 1-based line @ref pos_ is on. int line_here() const { auto end = text_.begin() + static_cast(pos_); return 1 + static_cast(std::count(text_.begin(), end, '\n')); } [[noreturn]] void fail(const std::string& msg) const { config_error(line_here(), msg); } /// @brief The next character, or a null character at the end of the text. char peek() const { return pos_ < text_.size() ? text_[pos_] : '\0'; } /// @brief Skips spaces, carriage returns and comments, and newlines too if /// asked. /// /// A comment stops before its newline, so with @p newlines false the parser /// ends up at the end of the line. void skip_blank(bool newlines) { while (pos_ < text_.size()) { char c = text_[pos_]; if (c == '#') { while (pos_ < text_.size() && text_[pos_] != '\n') ++pos_; } else if (c == ' ' || c == '\t' || c == '\r' || (newlines && c == '\n')) { ++pos_; } else { break; } } } /// @brief Requires that nothing but a comment is left on this line. void end_line() { skip_blank(false); if (pos_ < text_.size() && text_[pos_] != '\n') { fail("unexpected text at the end of the line"); } } /// @brief Reads a key or table name: letters, digits, `_` and `-`. /// /// @param what What was expected, for the error message. std::string parse_name(const char* what) { size_t start = pos_; while (pos_ < text_.size() && (std::isalnum(static_cast(text_[pos_])) || text_[pos_] == '_' || text_[pos_] == '-')) { ++pos_; } if (pos_ == start) fail(std::string("expected ") + what); return text_.substr(start, pos_ - start); } /// @brief Reads a `[name]` or `[deps.name]` table header. std::string parse_header() { ++pos_; // '[' skip_blank(false); std::string name = parse_name("a table name"); skip_blank(false); if (name == "deps" && peek() == '.') { ++pos_; skip_blank(false); const std::string dependency = parse_name("a dependency name"); if (dependency.find_first_not_of("abcdefghijklmnopqrstuvwxyz" "0123456789_-") != std::string::npos) { fail("dependency names use lowercase ASCII letters, digits, '_' and '-'"); } name += "." + dependency; skip_blank(false); } if (peek() != ']') fail("expected ']'"); ++pos_; end_line(); // Checked here rather than with the keys, so that a misspelled table with // nothing in it is reported as well. const bool known_platform = std::find(std::begin(PLATFORM_TABLES), std::end(PLATFORM_TABLES), name) != std::end(PLATFORM_TABLES); const bool known_profile = std::find(std::begin(PROFILE_TABLES), std::end(PROFILE_TABLES), name) != std::end(PROFILE_TABLES); if (!known_platform && !known_profile && !name.starts_with(DEPENDENCY_PREFIX)) { config_error(line_here(), "unknown table '[" + name + "]'"); } return name; } /// @brief Reads one `key = value` line into @p table. /// /// @param section The table the pair belongs to; empty at the top level. /// @param table Receives the pair. void parse_pair(const std::string& section, Table& table) { Entry entry; entry.line = line_here(); std::string key = parse_name("a key"); skip_blank(false); if (peek() != '=') fail("expected '=' after the key"); ++pos_; skip_blank(false); if (peek() == '[') { entry.is_list = true; entry.list = parse_array(); } else { entry.text = parse_string(); } end_line(); std::string full = section.empty() ? key : section + "." + key; if (!table.emplace(full, entry).second) { config_error(entry.line, "duplicate key '" + full + "'"); } } /// @brief Reads a string in double or single quotes. std::string parse_string() { char quote = peek(); if (quote != '"' && quote != '\'') fail("expected a quoted string"); ++pos_; std::string out; for (;; ++pos_) { if (pos_ >= text_.size() || text_[pos_] == '\n') { fail("unterminated string"); } char c = text_[pos_]; if (c == quote) break; if (quote == '"' && c == '\\') { char next = pos_ + 1 < text_.size() ? text_[pos_ + 1] : '\0'; if (next != '\\' && next != '"') { fail("unsupported escape; only \\\\ and \\\" are allowed"); } c = next; ++pos_; } out += c; } ++pos_; // the closing quote return out; } /// @brief Reads `[ "a", "b", ... ]`, possibly over several lines. Cmd parse_array() { ++pos_; // '[' Cmd items; for (;;) { skip_blank(true); if (pos_ >= text_.size()) fail("unterminated array"); if (text_[pos_] == ']') { ++pos_; return items; } items.push_back(parse_string()); skip_blank(true); if (peek() == ',') { ++pos_; } else if (peek() != ']') { fail(pos_ >= text_.size() ? "unterminated array" : "expected ',' or ']'"); } } } }; /// @brief Tells whether a path from the configuration stays inside the project. /// /// It must be relative, must not be empty or `.`, and must not climb out with /// `..`. Anything else could make the builder write, or `clean` delete, outside /// the project directory or the project directory itself. static bool is_inside_project(const fs::path& path) { if (path.empty() || path.is_absolute() || path.has_root_name()) return false; const fs::path normal = path.lexically_normal(); if (normal == "." || normal.empty()) return false; for (const fs::path& part : normal) { if (part == "..") return false; } return true; } /// @brief Tells whether @p inner is @p outer itself or lies below it. static bool is_within(const fs::path& inner, const fs::path& outer) { // lexically_relative() yields "../..." when inner is not below outer, and // "." when the two are the same; trailing separators are ignored. fs::path relative = inner.lexically_normal().lexically_relative(outer.lexically_normal()); return !relative.empty() && *relative.begin() != ".."; } /// @brief Reads and checks #CONFIG_FILE. /// /// Exits with a message if the file is missing, malformed or contains a key /// the builder does not know. /// /// @return The settings, with the table of the current platform merged in. static Config load_config(const std::string& profile) { std::ifstream file(CONFIG_FILE); if (!file) { config_error(0, "cannot read it; run the builder from the project root"); } std::stringstream buffer; buffer << file.rdbuf(); std::map dependency_tables; Table table = ConfigParser(buffer.str()).parse(dependency_tables); // Each take_*() removes the key from the table, so that what is left at the // end is exactly the unknown keys. auto take_string = [&table](const std::string& key, const std::string& fallback) -> std::string { auto it = table.find(key); if (it == table.end()) return fallback; if (it->second.is_list) { config_error(it->second.line, "'" + key + "' must be a string"); } std::string value = it->second.text; table.erase(it); return value; }; auto take_list = [&table](const std::string& key) -> Cmd { auto it = table.find(key); if (it == table.end()) return {}; if (!it->second.is_list) { config_error(it->second.line, "'" + key + "' must be a list, e.g. [\"a\", \"b\"]"); } Cmd value = it->second.list; table.erase(it); return value; }; Config cfg; std::string name = take_string("name", fs::current_path().filename().string()); cfg.compiler = take_string("compiler", "clang++"); cfg.src_dir = take_string("src", "src"); cfg.clean_dir = take_string("out", "build"); cfg.out_dir = cfg.clean_dir / profile; cfg.entry = take_string("entry", (cfg.src_dir / "main.cpp").string()); cfg.tests_dir = take_string("tests", "tests"); cfg.flags = take_list("flags"); cfg.objcxx_flags = take_list("objcxx_flags"); cfg.link_flags = take_list("link"); // Every platform's table is read, so that it counts as known, but only the // one of this platform is used. for (const char* platform : PLATFORM_TABLES) { const std::string section = platform; std::string compiler = take_string(section + ".compiler", ""); Cmd flags = take_list(section + ".flags"); Cmd link = take_list(section + ".link"); if (section == HOST_NAME) { if (!compiler.empty()) cfg.compiler = compiler; cfg.flags.insert(cfg.flags.end(), flags.begin(), flags.end()); cfg.link_flags.insert(cfg.link_flags.end(), link.begin(), link.end()); } } for (const char* name_p : PROFILE_TABLES) { const std::string section = name_p; std::string compiler = take_string(section + ".compiler", ""); Cmd flags = take_list(section + ".flags"); Cmd link = take_list(section + ".link"); if (section == profile) { if (!compiler.empty()) cfg.compiler = compiler; cfg.flags.insert(cfg.flags.end(), flags.begin(), flags.end()); cfg.link_flags.insert(cfg.link_flags.end(), link.begin(), link.end()); } } for (const auto& [section, line] : dependency_tables) { Dependency dep{ section.substr(DEPENDENCY_PREFIX.size()), take_string(section + ".git", ""), take_string(section + ".rev", ""), take_list(section + ".include"), }; if (dep.git.empty() || dep.rev.empty() || dep.include_dirs.empty()) { config_error(line, "'[" + section + "]' needs git, rev, and include"); } if (dep.git.find_first_of("\r\n\0", 0, 3) != std::string::npos || dep.rev.find_first_of("\r\n\0", 0, 3) != std::string::npos) { config_error(line, "dependency git and rev cannot contain line breaks or NUL"); } for (const std::string& dir : dep.include_dirs) { const fs::path path(dir); if (dir.find('\0') != std::string::npos || path.has_root_path() || (path != "." && !is_inside_project(path))) { config_error(line, "'" + section + ".include' paths must stay inside the dependency"); } } cfg.dependencies.push_back(std::move(dep)); } // Report the unknown key that was written first. const Entry* first = nullptr; std::string first_key; for (const auto& [key, entry] : table) { if (!first || entry.line < first->line) { first = &entry; first_key = key; } } if (first) config_error(first->line, "unknown key '" + first_key + "'"); if (cfg.compiler.empty()) config_error(0, "'compiler' must not be empty"); if (name.empty()) config_error(0, "'name' must not be empty"); if (name.find_first_of("/\\") != std::string::npos) { config_error(0, "'name' must be a file name, not a path"); } // `clean` deletes the whole of `out`, so it must be a directory of its own: // not the project, not the sources, and not something holding them. if (!is_inside_project(cfg.src_dir)) { config_error(0, "'src' must be a relative path inside the project, and " "not the project directory itself"); } if (!is_inside_project(cfg.clean_dir)) { config_error(0, "'out' must be a relative path inside the project, and " "not the project directory itself"); } if (is_within(cfg.clean_dir, cfg.src_dir) || is_within(cfg.src_dir, cfg.clean_dir)) { config_error(0, "'out' and 'src' must not be the same directory or " "contain one another"); } if (!is_within(cfg.entry, cfg.src_dir) || cfg.entry.lexically_normal() == cfg.src_dir.lexically_normal()) { config_error(0, "'entry' must be a file inside 'src'"); } if (!is_inside_project(cfg.tests_dir)) { config_error(0, "'tests' must be a relative path inside the project, and " "not the project directory itself"); } for (const fs::path* other : {&cfg.src_dir, &cfg.clean_dir}) { if (is_within(cfg.tests_dir, *other) || is_within(*other, cfg.tests_dir)) { config_error(0, "'tests' must not be the same directory as 'src' or 'out', " "nor inside or around either of them"); } } cfg.exe = cfg.out_dir / (name + EXE_SUFFIX); return cfg; } /// @} /// @name Platform selection /// Deciding which source files belong to the current platform. /// @{ /// @brief Tells whether a source file is built on the current platform. /// /// Platform-specific code is marked by its name: /// - `.mm` (Objective-C++) files build on macOS only; /// - a `_mac`, `_linux` or `_win` suffix on the file name, before the /// extension, restricts the file to that platform. /// /// Everything else builds everywhere. The suffix test is purely textual, so /// avoid ending a portable file's name with one of them (e.g. `big_win.cpp`). /// /// A `_test` at the end of the name is ignored first, so `window_mac_test.cpp` /// belongs to macOS like `window_mac.cpp` does. /// /// @param src Path of the source file. /// @return `true` if the file must be compiled on this platform. static bool is_built_here(const fs::path& src) { if (src.extension() == ".mm") return HOST == Platform::Mac; static const struct { const char* suffix; Platform platform; } SUFFIXES[] = { {"_mac", Platform::Mac}, {"_linux", Platform::Linux}, {"_win", Platform::Windows}, }; std::string stem = src.stem().string(); if (stem.ends_with("_test")) stem.resize(stem.size() - 5); for (const auto& entry : SUFFIXES) { if (stem.ends_with(entry.suffix)) return entry.platform == HOST; } return true; } /// @} /// @name Processes /// Spawning children and limiting how many run at once. /// @{ /// @brief Handle of a running child: a process id on POSIX, a `HANDLE` on /// Windows. #if defined(_WIN32) using Process = HANDLE; #else using Process = pid_t; #endif #if defined(_WIN32) /// @brief Quotes one argument for a Windows command line. /// /// Windows passes a child its arguments as a single string, which the child's /// runtime splits again. The rules: an argument containing a space, tab or /// quote is wrapped in quotes; inside it a quote becomes a backslash-quote, and /// backslashes directly before a quote (or before the closing quote) are /// doubled. /// /// @param arg Raw argument. /// @return The argument, quoted if necessary. static std::string quote_arg(const std::string& arg) { if (!arg.empty() && arg.find_first_of(" \t\"") == std::string::npos) { return arg; } std::string out = "\""; size_t backslashes = 0; // run of backslashes not yet written for (char c : arg) { if (c == '\\') { ++backslashes; continue; } if (c == '"') { out.append(backslashes * 2 + 1, '\\'); // double them, then escape the " } else { out.append(backslashes, '\\'); // not before a quote: written as is } out += c; backslashes = 0; } out.append(backslashes * 2, '\\'); // they now sit before the closing quote out += '"'; return out; } #endif /// @brief Starts a child process without waiting for it. /// /// Exits the builder if the process cannot be started. /// /// @param cmd Command to run; `cmd[0]` is looked up in `PATH`. /// @return Handle of the child. static Process spawn(const Cmd& cmd) { // Our own log lines may still sit in stdout's buffer. Flushing before the // child starts keeps them ahead of the child's output even when stdout is a // pipe or a file. std::fflush(stdout); #if defined(_WIN32) std::string line; for (size_t i = 0; i < cmd.size(); ++i) { if (i > 0) line += ' '; line += quote_arg(cmd[i]); } // Hand our standard streams to the child explicitly, so redirected output // (a pipe or a file) is inherited as well. STARTUPINFOA startup = {}; startup.cb = sizeof(startup); startup.dwFlags = STARTF_USESTDHANDLES; startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); startup.hStdError = GetStdHandle(STD_ERROR_HANDLE); // With no application name, the first word of the command line is looked up // in PATH and ".exe" is appended if needed. The command line buffer must be // writable, which std::string::data() is. PROCESS_INFORMATION info = {}; if (!CreateProcessA(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &info)) { print_error("cannot start " + cmd[0] + " (error " + std::to_string(static_cast(GetLastError())) + ")"); std::exit(EXIT_FAILURE); } CloseHandle(info.hThread); // only the process handle is needed return info.hProcess; #else // posix_spawnp wants a C-style argv: an array of char* ending in nullptr. std::vector argv; for (const std::string& arg : cmd) { argv.push_back(const_cast(arg.c_str())); } argv.push_back(nullptr); // The trailing "p" means the program is looked up in PATH, so "clang++" // does not have to be an absolute path. pid_t pid = 0; if (posix_spawnp(&pid, argv[0], nullptr, nullptr, argv.data(), environ) != 0) { print_error(std::string("cannot start ") + argv[0]); std::exit(EXIT_FAILURE); } return pid; #endif } /// @brief How a child process ended. struct ExitStatus { int code = 0; ///< Exit status; -1 if waiting for the child failed. int signal = 0; ///< The signal that killed it (macOS, Linux), or 0. bool ok() const { return code == 0 && signal == 0; } }; /// @brief A running child and the index of the command it was started for. struct Child { Process process; size_t index; }; /// @brief "No command": the index wait_any() reports when waiting itself /// failed. constexpr size_t kNoIndex = static_cast(-1); /// @brief Blocks until any one of the running children exits. /// /// The child that finished is removed from @p running. /// /// @param running Children that were started and not yet waited for. /// @param index Receives the index of the command of the child that finished, /// or #kNoIndex if waiting itself failed; in that case @p /// running is emptied, since the remaining children can no /// longer be tracked. /// @return How that child ended. static ExitStatus wait_any(std::vector& running, size_t* index) { ExitStatus status; *index = kNoIndex; #if defined(_WIN32) std::vector handles; for (const Child& child : running) handles.push_back(child.process); DWORD which = WaitForMultipleObjects(static_cast(handles.size()), handles.data(), FALSE, INFINITE); // On success the result is WAIT_OBJECT_0 (== 0) plus the index of the handle // that became signaled; anything else is an error. if (which >= handles.size()) { running.clear(); status.code = -1; return status; } DWORD code = 1; GetExitCodeProcess(handles[which], &code); CloseHandle(handles[which]); *index = running[which].index; running.erase(running.begin() + which); status.code = static_cast(code); return status; #else int raw = 0; pid_t done; do { done = waitpid(-1, &raw, 0); // -1 means "any child" } while (done < 0 && errno == EINTR); // retry if a signal interrupted us if (done < 0) { running.clear(); status.code = -1; return status; } auto it = std::find_if(running.begin(), running.end(), [done](const Child& c) { return c.process == done; }); if (it != running.end()) { *index = it->index; running.erase(it); } if (WIFSIGNALED(raw)) { status.signal = WTERMSIG(raw); } else if (WIFEXITED(raw)) { status.code = WEXITSTATUS(raw); } else { status.code = -1; } return status; #endif } /// @brief Runs a batch of commands with bounded parallelism. /// /// No threads are needed: the parallelism comes from the child processes, and /// this is just a scheduling loop. Each iteration does one of two things: /// - commands remain and we are below the limit: start one more; /// - otherwise: wait for one to finish. /// /// After the first failure no new commands are started, but the ones already /// running are still waited for so that no orphan processes are left behind. /// /// @param cmds Commands to run, started in order. /// @param max_jobs Maximum number of commands running at the same time. /// Capped at 60, because Windows can wait on at most 64 /// handles at once. /// @param failed If not null, receives the indices of the commands that /// failed. /// @return `true` only if every command succeeded. static bool run_all(const std::vector& cmds, unsigned max_jobs, std::vector* failed = nullptr) { max_jobs = std::min(max_jobs, 60u); size_t next = 0; // index of the next command to start std::vector running; // children currently running bool ok = true; while ((ok && next < cmds.size()) || !running.empty()) { if (ok && next < cmds.size() && running.size() < max_jobs) { running.push_back({spawn(cmds[next]), next}); ++next; } else { size_t index = kNoIndex; if (!wait_any(running, &index).ok()) { ok = false; if (failed != nullptr && index != kNoIndex) failed->push_back(index); } } } return ok; } /// @brief Runs a single command and waits for it. /// /// @param cmd Command to run. /// @return How it ended. static ExitStatus run_status(const Cmd& cmd) { std::vector running = {{spawn(cmd), 0}}; size_t ignored = kNoIndex; return wait_any(running, &ignored); } /// @brief Runs a single command and waits for it. /// /// @param cmd Command to run. /// @return `true` if the command succeeded. static bool run(const Cmd& cmd) { return run_status(cmd).ok(); } /// @brief Runs a command and captures its stdout and stderr (empty on failure). static std::string capture(const Cmd& cmd) { if (cmd.empty()) return {}; std::fflush(stdout); #if defined(_WIN32) SECURITY_ATTRIBUTES sa = {sizeof(sa), nullptr, TRUE}; HANDLE read_pipe = nullptr; HANDLE write_pipe = nullptr; if (!CreatePipe(&read_pipe, &write_pipe, &sa, 0)) return {}; SetHandleInformation(read_pipe, HANDLE_FLAG_INHERIT, 0); std::string line; for (size_t i = 0; i < cmd.size(); ++i) { if (i > 0) line += ' '; line += quote_arg(cmd[i]); } STARTUPINFOA startup = {}; startup.cb = sizeof(startup); startup.dwFlags = STARTF_USESTDHANDLES; startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); startup.hStdOutput = write_pipe; startup.hStdError = write_pipe; PROCESS_INFORMATION info = {}; if (!CreateProcessA(nullptr, line.data(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &startup, &info)) { CloseHandle(read_pipe); CloseHandle(write_pipe); return {}; } CloseHandle(write_pipe); CloseHandle(info.hThread); std::string out; char buf[512]; DWORD n = 0; while (ReadFile(read_pipe, buf, sizeof(buf), &n, nullptr) && n > 0) { out.append(buf, n); } CloseHandle(read_pipe); WaitForSingleObject(info.hProcess, INFINITE); DWORD code = 1; GetExitCodeProcess(info.hProcess, &code); CloseHandle(info.hProcess); return code == 0 ? out : std::string{}; #else int fds[2]; if (pipe(fds) != 0) return {}; posix_spawn_file_actions_t actions; posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_addclose(&actions, fds[0]); posix_spawn_file_actions_adddup2(&actions, fds[1], STDOUT_FILENO); posix_spawn_file_actions_adddup2(&actions, fds[1], STDERR_FILENO); posix_spawn_file_actions_addclose(&actions, fds[1]); std::vector argv; for (const std::string& arg : cmd) { argv.push_back(const_cast(arg.c_str())); } argv.push_back(nullptr); pid_t pid = 0; int err = posix_spawnp(&pid, argv[0], &actions, nullptr, argv.data(), environ); posix_spawn_file_actions_destroy(&actions); close(fds[1]); if (err != 0) { close(fds[0]); return {}; } std::string out; char buf[512]; for (;;) { ssize_t n = read(fds[0], buf, sizeof(buf)); if (n > 0) { out.append(buf, static_cast(n)); } else if (n == 0) { break; } else if (errno != EINTR) { break; } } close(fds[0]); int raw = 0; while (waitpid(pid, &raw, 0) < 0 && errno == EINTR) { } if (!WIFEXITED(raw) || WEXITSTATUS(raw) != 0) return {}; return out; #endif } /// @brief Says in words how a child ended, to follow the name of the program: /// `exited with status 3` or `was killed by signal 11 (Segmentation /// fault)`. static std::string describe(const ExitStatus& status) { if (status.signal != 0) { #if defined(_WIN32) return "was stopped by signal " + std::to_string(status.signal); #else const char* name = strsignal(status.signal); return "was killed by signal " + std::to_string(status.signal) + (name != nullptr ? " (" + std::string(name) + ")" : ""); #endif } if (status.code == -1) return "could not be waited for"; #if defined(_WIN32) // Windows reports a crash as an exit status such as 0xC0000005. if (static_cast(status.code) >= 0xC0000000u) { char buffer[32]; std::snprintf(buffer, sizeof(buffer), "crashed with code 0x%08X", static_cast(status.code)); return buffer; } #endif return "exited with status " + std::to_string(status.code); } /// @brief The exit status the builder itself should end with when it passes on /// the failure of a program it ran: its status, or 128 plus the signal, /// and never 0 for a failure. static int exit_code_of(const ExitStatus& status) { if (status.signal != 0) return 128 + status.signal; if (status.code <= 0 || status.code > 255) return status.ok() ? 0 : 1; return status.code; } /// @} /// @name Incremental compilation /// Deciding whether a source file must be recompiled. /// @{ /// @brief Reads a dependency file written by the compiler's `-MD` flag. /// /// The file uses Makefile syntax: `obj: dep dep dep`, where a backslash at the /// end of a line continues the list on the next line. Only these rules matter: /// - the dependency list starts after the first `": "`; /// - dependencies are separated by whitespace or a line continuation; /// - a space inside a path is escaped with a backslash; /// - any other backslash is part of the path, which is how Windows paths /// appear: a drive letter, then names separated by backslashes. /// /// @param path Path of the `.d` file. /// @return Every dependency listed in the file; empty if it cannot be parsed. static std::vector read_depfile(const fs::path& path) { // Read the whole file into one string. std::ifstream file(path); std::stringstream buffer; buffer << file.rdbuf(); std::string text = buffer.str(); std::vector deps; size_t i = text.find(": "); if (i == std::string::npos) return deps; std::string token; // the path currently being accumulated // The loop deliberately runs one step past the end (i == size) and treats // end-of-file as a newline, so the last path is flushed as well. for (i += 2; i <= text.size(); ++i) { char c = i < text.size() ? text[i] : '\n'; char next = i + 1 < text.size() ? text[i + 1] : '\0'; if (c == '\\' && next == ' ') { // An escaped space that belongs to the current path. token += ' '; ++i; } else if (c == '\\' && (next == '\n' || next == '\r')) { // A line continuation: the current path ends here. The newline itself // is a separator too and is handled by the next iteration. if (!token.empty()) deps.push_back(token); token.clear(); } else if (c == ' ' || c == '\n' || c == '\r') { // A separator: the current path ends here. if (!token.empty()) deps.push_back(token); token.clear(); } else { token += c; // includes a backslash that is part of a Windows path } } return deps; } /// @brief Tells whether an object file is out of date. /// /// Any one of these is enough: /// -# @p obj or @p dep is missing (never built, or cleaned); /// -# the builder or `kumo.toml` is newer than @p obj (the compile flags come /// from those two, so a change to either may mean different flags); /// -# some dependency (the source itself or a header it includes) is newer /// than @p obj, or has been deleted. /// /// @param obj Path of the object file. /// @param dep Path of the dependency file written alongside it. /// @param flags_time Modification time of whatever the flags come from: the /// newer of the builder binary and `kumo.toml`. /// @return `true` if the source must be recompiled. static bool needs_compile(const fs::path& obj, const fs::path& dep, fs::file_time_type flags_time) { if (!fs::exists(obj) || !fs::exists(dep)) return true; fs::file_time_type obj_time = fs::last_write_time(obj); if (flags_time > obj_time) return true; for (const fs::path& d : read_depfile(dep)) { if (!fs::exists(d) || fs::last_write_time(d) > obj_time) return true; } return false; } static void append_list(std::ostringstream& ss, const char* key, const Cmd& list) { ss << key << "=" << list.size() << "\n"; for (const std::string& item : list) { ss << " " << item << "\n"; } } /// @brief Computes a fingerprint of the active compiler and build flags. static std::string toolchain_fingerprint(const Config& cfg, const Cmd& dependency_commits) { const std::string version = capture({cfg.compiler, "--version"}); if (version.empty()) { print_error("cannot run compiler '" + cfg.compiler + "'"); std::exit(EXIT_FAILURE); } std::ostringstream ss; ss << "compiler=" << cfg.compiler << "\n" << "version:\n" << version << "\n"; append_list(ss, "flags", cfg.flags); append_list(ss, "objcxx_flags", cfg.objcxx_flags); append_list(ss, "link", cfg.link_flags); if (!dependency_commits.empty()) { append_list(ss, "dependencies", dependency_commits); } return ss.str(); } /// @brief Clears stale build outputs if the compiler or flags changed. static void check_toolchain_cache(const Config& cfg, const Cmd& dependency_commits) { const fs::path stamp = cfg.out_dir / ".toolchain"; const std::string current = toolchain_fingerprint(cfg, dependency_commits); if (fs::exists(stamp)) { std::ifstream in(stamp, std::ios::binary); std::ostringstream old; old << in.rdbuf(); if (old.str() == current) return; in.close(); // Windows cannot remove the stamp while this stream is open. log_step(Style::Cyan, "rebuild", "toolchain or flags changed, clearing " + cfg.out_dir.generic_string() + "/"); fs::remove_all(cfg.out_dir); } else if (fs::exists(cfg.out_dir)) { // Existing build directory without a stamp: clear once so objects from // an unknown compiler cannot linger. log_step( Style::Cyan, "rebuild", "no toolchain stamp, clearing " + cfg.out_dir.generic_string() + "/"); fs::remove_all(cfg.out_dir); } fs::create_directories(cfg.out_dir); std::ofstream out(stamp, std::ios::binary); out << current; } /// @} /// @name Header-only dependencies /// @{ static bool dependency_error(const Dependency& dep, const std::string& message) { print_error("dependency '" + dep.name + "' (" + dep.rev + "): " + message); return false; } static bool is_commit_id(std::string_view rev) { return (rev.size() == 40 || rev.size() == 64) && rev.find_first_not_of("0123456789abcdefABCDEF") == std::string_view::npos; } /// @brief A portable cache name derived from a dependency's URL and revision. /// /// The receipt also records the original values to detect a hash collision. static std::string dependency_cache_key(const Dependency& dep) { std::uint64_t hash = 14695981039346656037ull; for (unsigned char byte : dep.git + "\n" + dep.rev) { hash ^= byte; hash *= 1099511628211ull; } return std::to_string(hash); } static bool dependency_path_within(const fs::path& inner, const fs::path& outer) { auto component = inner.begin(); for (const fs::path& part : outer) { if (component == inner.end()) return false; #if defined(_WIN32) if (CompareStringOrdinal(component->c_str(), -1, part.c_str(), -1, TRUE) != CSTR_EQUAL) { return false; } #else if (*component != part) return false; #endif ++component; } return true; } static bool valid_dependency_cache(const Config& cfg) { const fs::path project = fs::canonical(fs::current_path()); const fs::path cache = fs::weakly_canonical(fs::absolute(DEPENDENCY_CACHE)); if (!dependency_path_within(cache, project) || dependency_path_within(project, cache)) { print_error("dependency cache must be inside the project"); return false; } for (const fs::path* dir : {&cfg.src_dir, &cfg.tests_dir, &cfg.clean_dir}) { const fs::path resolved = fs::weakly_canonical(fs::absolute(*dir)); if (dependency_path_within(cache, resolved) || dependency_path_within(resolved, cache)) { print_error("dependency cache overlaps " + dir->generic_string()); return false; } } return true; } static bool dependency_include_flags(const Dependency& dep, const fs::path& entry, Cmd& flags) { const fs::path source = entry / "source"; if (!fs::is_directory(source)) { return dependency_error(dep, "missing dependency checkout"); } const fs::path root = fs::canonical(source); if (!dependency_path_within(root, fs::canonical(entry))) { return dependency_error(dep, "checkout points outside its cache entry"); } for (const std::string& dir : dep.include_dirs) { const fs::path path = (source / dir).lexically_normal(); if (!fs::is_directory(path) || !dependency_path_within(fs::canonical(path), root)) { return dependency_error(dep, "missing or invalid include directory '" + dir + "'"); } flags.push_back("-I" + path.generic_string()); } return true; } /// @brief Fetches and validates a dependency before it enters the build cache. static bool populate_dependency(const Dependency& dep, const fs::path& staging) { std::string ref = dep.rev; const bool is_tag = !is_commit_id(ref); if (is_tag) { if (!ref.starts_with("refs/tags/")) ref = "refs/tags/" + ref; if (!run({"git", "check-ref-format", ref})) { return dependency_error(dep, "invalid Git tag"); } } log_step(Style::Cyan, "fetch", dep.name + " " + dep.rev); const std::string source = (staging / "source").generic_string(); if (!run({"git", "clone", "--no-checkout", "--no-hardlinks", "--no-recurse-submodules", "--", dep.git, source})) { return dependency_error(dep, "git clone failed"); } std::string commit = capture({"git", "-C", source, "rev-parse", "--verify", "--end-of-options", ref + "^{commit}"}); while (!commit.empty() && (commit.back() == '\n' || commit.back() == '\r')) { commit.pop_back(); } const bool matches_commit = is_tag || (commit.size() == ref.size() && std::equal(commit.begin(), commit.end(), ref.begin(), [](unsigned char a, unsigned char b) { return std::tolower(a) == std::tolower(b); })); if (!is_commit_id(commit) || !matches_commit) { return dependency_error(dep, is_tag ? "Git tag not found" : "Git commit not found"); } if (!run({"git", "-C", source, "checkout", "--quiet", "--detach", "--no-recurse-submodules", commit})) { return dependency_error(dep, "git checkout failed"); } Cmd flags; if (!dependency_include_flags(dep, staging, flags)) return false; std::ofstream receipt(staging / "revision", std::ios::binary); receipt << dep.git << '\n' << dep.rev << '\n' << commit << '\n'; receipt.close(); if (!receipt) return dependency_error(dep, "cannot write cache receipt"); return true; } static bool prepare_dependency(const Dependency& dep, Cmd& flags, Cmd& commits) { const fs::path parent = DEPENDENCY_CACHE / ("dep-" + dep.name); const fs::path root = fs::weakly_canonical(fs::absolute(DEPENDENCY_CACHE)); const std::string key = dependency_cache_key(dep); const fs::path entry = parent / key; if (!dependency_path_within(fs::weakly_canonical(fs::absolute(entry)), root)) { return dependency_error(dep, "cache entry points outside the dependency cache"); } if (!fs::exists(entry)) { fs::create_directories(parent); std::error_code error; auto nonce = std::chrono::steady_clock::now().time_since_epoch().count(); fs::path staging; do { staging = parent / (".tmp-" + key + "-" + std::to_string(nonce++)); error.clear(); } while (!fs::create_directory(staging, error) && !error); if (error) return dependency_error(dep, error.message()); const bool ready = populate_dependency(dep, staging); if (ready) fs::rename(staging, entry, error); if (!ready || error) { std::error_code ignored; const fs::path resolved = fs::canonical(staging, ignored); if (!ignored && !dependency_path_within(root, resolved) && dependency_path_within(resolved, root)) { fs::remove_all(fs::absolute(staging), ignored); } } if (!ready) return false; // Another invocation may have published the same dependency first. if (error && !fs::exists(entry)) return dependency_error(dep, error.message()); } std::ifstream receipt(entry / "revision", std::ios::binary); std::string git, rev, commit; if (!std::getline(receipt, git) || !std::getline(receipt, rev) || !std::getline(receipt, commit) || git != dep.git || rev != dep.rev || !is_commit_id(commit)) { return dependency_error(dep, "invalid cache receipt in " + entry.generic_string()); } if (!dependency_include_flags(dep, entry, flags)) return false; commits.push_back(commit); return true; } static bool prepare_dependencies(Config& cfg, Cmd& commits) { for (const Dependency& dep : cfg.dependencies) { try { if (!prepare_dependency(dep, cfg.flags, commits)) return false; } catch (const fs::filesystem_error& error) { return dependency_error(dep, error.what()); } } return true; } /// @} /// @name compile_commands.json /// Tells clangd how each file is compiled. /// @{ /// @brief Escapes a string for use inside a JSON string literal. /// /// Only double quotes and backslashes are handled; paths and flags never /// contain control characters. /// /// @param s Raw string. /// @return The escaped string, without surrounding quotes. static std::string json_escape(const std::string& s) { std::string out; for (char c : s) { if (c == '"' || c == '\\') out += '\\'; out += c; } return out; } /// @brief Writes `compile_commands.json` to the current directory. /// /// One object is written per file: /// @code{.json} /// {"directory": "", "file": "", "arguments": ["", ...]} /// @endcode /// /// @param sources Every source file. /// @param cmds Compile commands; `cmds[i]` compiles `sources[i]`. static void write_compile_commands(const std::vector& sources, const std::vector& cmds) { std::ofstream out("compile_commands.json"); std::string dir = json_escape(fs::current_path().string()); out << "[\n"; for (size_t i = 0; i < sources.size(); ++i) { out << " {\"directory\": \"" << dir << "\", \"file\": \"" << json_escape(sources[i].generic_string()) << "\", \"arguments\": ["; for (size_t j = 0; j < cmds[i].size(); j++) { out << (j ? ", " : "") << '"' << json_escape(cmds[i][j]) << '"'; } // JSON forbids a trailing comma, so the last entry gets none. out << "]}" << (i + 1 < sources.size() ? "," : "") << "\n"; } out << "]\n"; } /// @} /// @name Compiling and linking /// The steps shared by building the program and building the tests. /// @{ /// @brief One source file and how it is compiled. struct Unit { fs::path src; fs::path obj; ///< Where the compiled object goes. Cmd cmd; ///< The command that compiles #src into #obj. bool stale; ///< Whether #obj is out of date. }; /// @brief Plans the compilation of the sources found under a directory. /// /// Nothing is compiled here. The result is sorted by path, so that the order of /// the output and of the link line does not depend on the file system. /// /// @param cfg Project settings. /// @param dir Directory searched recursively for `.cpp` and `.mm`. /// @param tests_only Take only files whose name ends in `_test`. /// @param extra_flags Flags added after the project's compile flags. /// @param flags_time Modification time of whatever the flags come from. /// @return One unit per file that is built on this platform. static std::vector plan_units(const Config& cfg, const fs::path& dir, bool tests_only, const Cmd& extra_flags, fs::file_time_type flags_time) { std::vector units; for (const fs::directory_entry& entry : fs::recursive_directory_iterator(dir)) { fs::path src = entry.path(); if (src.extension() != ".cpp" && src.extension() != ".mm") continue; if (tests_only && !src.stem().string().ends_with("_test")) continue; if (!is_built_here(src)) continue; // src/foo/bar.cpp -> build/obj/src/foo/bar.cpp.o // The full file name is kept and a suffix appended, so bar.cpp and // bar.mm do not collide. fs::path obj = cfg.out_dir / "obj" / (src.string() + ".o"); fs::path dep = cfg.out_dir / "obj" / (src.string() + ".d"); fs::create_directories(obj.parent_path()); // -MD -MF : write the dependency list to dep while compiling. Cmd cmd = {cfg.compiler}; cmd.insert(cmd.end(), cfg.flags.begin(), cfg.flags.end()); cmd.insert(cmd.end(), extra_flags.begin(), extra_flags.end()); if (src.extension() == ".mm") { cmd.insert(cmd.end(), cfg.objcxx_flags.begin(), cfg.objcxx_flags.end()); } cmd.insert(cmd.end(), {"-MD", "-MF", dep.string(), "-c", src.string(), "-o", obj.string()}); units.push_back({src, obj, cmd, needs_compile(obj, dep, flags_time)}); } std::sort(units.begin(), units.end(), [](const Unit& a, const Unit& b) { return a.src < b.src; }); return units; } /// @brief Compiles those of the given units that are stale, in parallel. /// /// Each file is announced with a counter, and a failure ends with a line naming /// the files that did not compile, after the diagnostics of the compiler. /// /// @param units The units to consider; the up to date ones are skipped. /// @param compiled If not null, receives the number of files compiled. /// @return `true` if every compilation succeeded. static bool compile_stale(const std::vector& units, size_t* compiled = nullptr) { std::vector stale; for (const Unit* unit : units) { if (unit->stale) stale.push_back(unit); } if (compiled != nullptr) *compiled = stale.size(); std::vector cmds; for (size_t i = 0; i < stale.size(); ++i) { log_step( Style::Cyan, "compile", stale[i]->src.generic_string(), "[" + std::to_string(i + 1) + "/" + std::to_string(stale.size()) + "]"); if (verbose) print_command(stale[i]->cmd); cmds.push_back(stale[i]->cmd); } // hardware_concurrency may return 0, meaning "unknown". unsigned jobs = std::thread::hardware_concurrency(); std::vector failed; if (run_all(cmds, jobs ? jobs : 4, &failed)) return true; std::string names; for (size_t index : failed) { names += (names.empty() ? "" : ", ") + stale[index]->src.generic_string(); } print_error("failed to compile " + (names.empty() ? "the sources" : names)); return false; } /// @brief Links object files into an executable, unless it is up to date. /// /// "Did we compile anything this time?" is not a valid test for being up to /// date: if the last run compiled successfully but failed to link, nothing is /// stale now and yet the link is still needed. So the executable is compared /// with the objects themselves. /// /// @param cfg Project settings. /// @param objects The objects to link. /// @param exe The executable to produce. /// @param linked If not null, tells whether a link was done. /// @return `true` if the executable is up to date afterwards. static bool link_if_needed(const Config& cfg, const std::vector& objects, const fs::path& exe, bool* linked = nullptr) { if (linked != nullptr) *linked = false; bool needed = !fs::exists(exe); for (const fs::path& obj : objects) { if (!needed && fs::last_write_time(obj) > fs::last_write_time(exe)) { needed = true; } } if (!needed) return true; log_step(Style::Cyan, "link", exe.generic_string()); fs::create_directories(exe.parent_path()); Cmd link = {cfg.compiler}; for (const fs::path& obj : objects) link.push_back(obj.string()); link.insert(link.end(), cfg.link_flags.begin(), cfg.link_flags.end()); link.insert(link.end(), {"-o", exe.string()}); if (verbose) print_command(link); if (linked != nullptr) *linked = true; if (run(link)) return true; print_error("failed to link " + exe.generic_string()); return false; } /// @} /// @name Tests /// Every `*_test.cpp` under the tests directory is a program of its own. It is /// linked with all the sources of the project except the entry point, and it /// passes if it exits with status 0. /// @{ /// @brief The name a test is listed and selected by: its path inside the tests /// directory, without the extension (`render/raster_test`). static std::string test_name(const Config& cfg, const fs::path& src) { fs::path name = src.lexically_relative(cfg.tests_dir); name.replace_extension(""); return name.generic_string(); } /// @brief Where the executable of a test is put. static fs::path test_exe(const Config& cfg, const fs::path& src) { return cfg.out_dir / "tests" / (test_name(cfg, src) + EXE_SUFFIX); } /// @} /// @name Command line /// @{ /// @brief Prints the usage of the builder. static void print_usage(std::FILE* out) { std::fputs(R"usage(kumoko, the build tool of Kumo Usage: kumoko [options] [command] [name] Commands: build Compile and link the program (the default) run Build, then run the program test [name] Build and run the tests; with a name, only those whose path contains it, e.g. `test raster` or `test e2e/` clean Delete all build output help Show this text Options: --debug Build with debug symbols and no optimization (default) --release Build with optimizations enabled --asan Build with Address and UndefinedBehavior sanitizers -v, --verbose Print full commands -q, --quiet With test: one line per test program, not one per test case -h, --help Show this text Run it from the project root; its settings are in kumo.toml. Output is colored on a terminal; set NO_COLOR to turn that off. )usage", out); } /// @brief What the command line asks for. struct Args { std::string command = "build"; std::string pattern; ///< For `test`: part of the name of the tests to run. std::string profile = "debug"; ///< Build profile: debug, release, or asan. }; /// @brief Reads the command line. /// /// Prints the usage and exits for `help`, `-h` and `--help`; prints an error /// and exits with status 2 for anything it does not understand, instead of /// guessing what was meant. static Args parse_args(int argc, char** argv) { const auto mistake = [](const std::string& message) { print_error(message); std::fprintf(stderr, "Run `kumoko help` for the usage.\n"); std::exit(2); }; Args args; std::vector words; for (int i = 1; i < argc; ++i) { const std::string arg = argv[i]; if (arg == "-h" || arg == "--help") { print_usage(stdout); std::exit(0); } else if (arg == "--debug") { args.profile = "debug"; } else if (arg == "--release") { args.profile = "release"; } else if (arg == "--asan") { args.profile = "asan"; } else if (arg == "-v" || arg == "--verbose") { verbose = true; } else if (arg == "-q" || arg == "--quiet") { quiet = true; } else if (arg.size() > 1 && arg[0] == '-') { mistake("unknown option '" + arg + "'"); } else { words.push_back(arg); } } if (!words.empty()) args.command = words[0]; if (args.command == "help") { print_usage(stdout); std::exit(0); } if (args.command != "build" && args.command != "run" && args.command != "test" && args.command != "clean") { mistake("unknown command '" + args.command + "'"); } if (words.size() > (args.command == "test" ? 2u : 1u)) { mistake("too many arguments for '" + args.command + "'"); } if (words.size() == 2) args.pattern = words[1]; return args; } /// @} /// @name Entry point /// @{ /// @brief Recompiles and restarts the builder if its source has changed. /// /// If #SELF_SRC is newer than the builder's executable, it is recompiled /// and the new binary takes over with the same arguments. The new binary is /// always newer than the source, so this cannot loop forever. /// /// On macOS and Linux `execv` replaces the current process. Windows has no /// equivalent, so the running executable is renamed out of the way, the new /// one is built under the original name, and it is then run as a child /// whose exit status becomes ours. /// /// @param argc Argument count of main(). /// @param argv Argument vector of main(), forwarded to the new binary. static void rebuild_self([[maybe_unused]] int argc, char** argv) { #if defined(_WIN32) // Left over from the previous self-rebuild; it could not be deleted then // because it was still running. Failure to delete it is harmless. std::error_code ignored; fs::remove(SELF_OLD_EXE, ignored); #endif if (fs::last_write_time(SELF_SRC) <= fs::last_write_time(SELF_EXE)) return; log_step(Style::Cyan, "self", SELF_SRC.generic_string() + " changed, rebuilding the builder"); const Cmd compile = {SELF_CXX, "-std=c++20", SELF_SRC.string(), "-o", SELF_EXE.string()}; #if defined(_WIN32) std::error_code ec; fs::rename(SELF_EXE, SELF_OLD_EXE, ec); if (ec) { print_error("cannot move " + SELF_EXE.string() + " aside: " + ec.message()); std::exit(1); } if (!run(compile)) { // Put the old builder back so the next run can try again. fs::rename(SELF_OLD_EXE, SELF_EXE, ec); print_error("failed to rebuild " + SELF_SRC.generic_string()); std::exit(1); } Cmd relaunch(argv, argv + argc); relaunch[0] = SELF_EXE.string(); std::exit(run(relaunch) ? 0 : 1); #else if (!run(compile)) { print_error("failed to rebuild " + SELF_SRC.generic_string()); std::exit(1); } execv(SELF_EXE.c_str(), argv); // execv does not return on success; reaching this line means it failed. print_error(std::string("cannot restart the builder: ") + std::strerror(errno)); std::exit(1); #endif } /// @brief Builds the project, runs it, or builds and runs its tests. /// /// @param argc Argument count. /// @param argv The command line, see print_usage(). /// @return 0 on success, 1 if building failed or a test failed, 2 for a /// mistake on the command line; for `run`, the status of the program if /// it failed. int main(int argc, char** argv) { using Clock = std::chrono::steady_clock; init_terminal(); rebuild_self(argc, argv); const Args args = parse_args(argc, argv); Config cfg = load_config(args.profile); const Clock::time_point began = Clock::now(); if (!cfg.dependencies.empty() && !valid_dependency_cache(cfg)) return 1; if (args.command == "clean") { const std::uintmax_t removed = fs::remove_all(cfg.clean_dir); if (removed > 0) { log_step(Style::Cyan, "clean", "removed " + cfg.clean_dir.generic_string() + "/"); } else { log_step(Style::Cyan, "clean", "nothing to remove, " + cfg.clean_dir.generic_string() + "/ does not exist"); } return 0; } const bool testing = args.command == "test"; const std::string& filter = args.pattern; if (!fs::is_directory(cfg.src_dir)) { config_error(0, "the source directory '" + cfg.src_dir.string() + "' (key 'src') does not exist"); } const bool has_tests = fs::is_directory(cfg.tests_dir); if (testing && !has_tests) { config_error(0, "the tests directory '" + cfg.tests_dir.string() + "' (key 'tests') does not exist"); } Cmd dependency_commits; if (!prepare_dependencies(cfg, dependency_commits)) return 1; check_toolchain_cache(cfg, dependency_commits); // The compile flags come from the builder and from kumo.toml, so an object // file older than either is stale. fs::file_time_type flags_time = std::max(fs::last_write_time(SELF_EXE), fs::last_write_time(CONFIG_FILE)); // Step 1: plan the compilation of the sources and of the tests, and tell // clangd about all of them whatever the mode. std::vector units = plan_units(cfg, cfg.src_dir, false, {}, flags_time); std::vector tests; if (has_tests) { tests = plan_units(cfg, cfg.tests_dir, true, {"-I" + cfg.tests_dir.generic_string()}, flags_time); } std::vector sources; std::vector all_cmds; for (const std::vector* group : {&units, &tests}) { for (const Unit& unit : *group) { sources.push_back(unit.src); all_cmds.push_back(unit.cmd); } } write_compile_commands(sources, all_cmds); // Step 2: decide what to compile. In test mode the entry point is left out // of the program's objects, because every test has a `main` of its own. std::vector to_compile; std::vector objects; // what a final link gets, tests excluded bool found_entry = false; for (const Unit& unit : units) { if (testing && unit.src.lexically_normal() == cfg.entry.lexically_normal()) { found_entry = true; continue; } objects.push_back(unit.obj); to_compile.push_back(&unit); } if (testing && !found_entry) { config_error(0, "the entry file '" + cfg.entry.string() + "' (key 'entry') is not among the sources"); } std::vector selected; // the tests to build and run if (testing) { for (const Unit& test : tests) { if (test_name(cfg, test.src).find(filter) == std::string::npos) continue; selected.push_back(&test); to_compile.push_back(&test); } if (selected.empty()) { print_error(filter.empty() ? "there are no tests in " + cfg.tests_dir.generic_string() + "/" : "no test matches '" + filter + "'"); return 1; } } // Step 3: compile whatever is stale, in parallel. size_t compiled = 0; if (!compile_stale(to_compile, &compiled)) return 1; // Step 4: link, and run or report. if (!testing) { bool linked = false; if (!link_if_needed(cfg, objects, cfg.exe, &linked)) return 1; if (args.command == "run") { log_step(Style::Cyan, "run", cfg.exe.generic_string()); // Windows wants backslashes in the path of a program to start. fs::path program = cfg.exe; program.make_preferred(); const ExitStatus status = run_status({program.string()}); if (status.ok()) return 0; print_error(cfg.exe.generic_string() + " " + describe(status)); return exit_code_of(status); } const std::string took = format_duration(Clock::now() - began); if (compiled == 0 && !linked) { log_step(Style::Green, "built", cfg.exe.generic_string() + " is up to date"); } else { log_step(Style::Green, "built", cfg.exe.generic_string(), plural(compiled, "file") + " compiled in " + took); } return 0; } size_t name_width = 0; for (const Unit* test : selected) { name_width = std::max(name_width, test_name(cfg, test->src).size()); } // First every test program is linked, so that the lines about building stay // together and none of them falls between the blocks of two programs; a // program that does not link stops the run before any test has started. bool built_something = compiled > 0; for (const Unit* test : selected) { std::vector test_objects = {test->obj}; test_objects.insert(test_objects.end(), objects.begin(), objects.end()); bool linked = false; if (!link_if_needed(cfg, test_objects, test_exe(cfg, test->src), &linked)) { return 1; } built_something = built_something || linked; } if (built_something && !quiet) std::printf("\n"); std::vector failed; for (const Unit* test : selected) { const fs::path exe = test_exe(cfg, test->src); // The test program lists its cases as it runs them. It is told whether it // may color its output and rewrite its current line, which a terminal // allows and a pipe or a file does not, and whether to list only failures. const std::string name = test_name(cfg, test->src); fs::path program = exe; program.make_preferred(); Cmd command = {program.string()}; if (color_enabled) { command.push_back("--color"); command.push_back("--live"); } if (quiet) { command.push_back("--quiet"); } else { std::printf("%s\n", rule('-', name).c_str()); } const Clock::time_point test_began = Clock::now(); const ExitStatus status = run_status(command); const std::string took = format_duration(Clock::now() - test_began); // A test program that fails its checks exits with status 1; anything else // that is not success (a signal, another status) is a crash. const bool crashed = !status.ok() && !(status.signal == 0 && status.code == 1); // A crash leaves the line of the test case that was running unfinished. if (crashed && !quiet) std::printf("\n"); // The verdict is in the same column as the labels of the other lines, the // name is padded to the longest one and the time is right aligned, so that // the lines of all the programs line up. const std::string verdict = status.ok() ? "PASS" : crashed ? "CRASH" : "FAIL"; if (!status.ok()) failed.push_back(name); std::printf( "%s %s %s%s\n", paint(status.ok() ? Style::Green : Style::Red, pad(verdict, 8)).c_str(), pad(name, name_width).c_str(), paint(Style::Dim, pad_left(took, 7)).c_str(), crashed ? (" " + paint(Style::Red, describe(status))).c_str() : ""); if (!quiet) std::printf("\n"); } // A heavier rule sets the summary off from the programs above it. const std::string total = " in " + format_duration(Clock::now() - began); if (quiet) { std::printf("\n"); } else { std::printf("%s\n", rule('=').c_str()); } if (failed.empty()) { std::printf( "%s%s\n", paint(Style::Green, plural(selected.size(), "test program") + " passed") .c_str(), paint(Style::Dim, total).c_str()); return 0; } std::printf( "%s%s\n", paint(Style::Red, std::to_string(failed.size()) + " of " + plural(selected.size(), "test program") + " failed") .c_str(), paint(Style::Dim, total).c_str()); return 1; } /// @}