diff --git a/project.cpp b/project.cpp index d0cb676..30cedf0 100644 --- a/project.cpp +++ b/project.cpp @@ -352,6 +352,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("SourceScan").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("BuildAll").Dependencies({ CrafterBuildLib.get() }); cfg.AddTest("Lint").Dependencies({ CrafterBuildLib.get() }); + cfg.AddTest("LintCompilerHeaders").Dependencies({ CrafterBuildLib.get() }); } // Dogfood: the lite house rules, imported from their own repo through diff --git a/tests/LintCompilerHeaders/main.cpp b/tests/LintCompilerHeaders/main.cpp new file mode 100644 index 0000000..ce1deb3 --- /dev/null +++ b/tests/LintCompilerHeaders/main.cpp @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +import std; +import Crafter.Build; +namespace fs = std::filesystem; +using namespace Crafter; + +extern "C" int setenv(const char* name, const char* value, int overwrite); +extern "C" int unsetenv(const char* name); + +namespace { + std::int32_t Failures = 0; + + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + void Write(const fs::path& path, std::string_view content) { + std::ofstream file(path, std::ios::binary | std::ios::trunc); + file.write(content.data(), static_cast(content.size())); + } + + // The file the toolchain's clang++ runs as when no other toolchain is + // staged: CRAFTER_BUILD_LLVM_DIR's, else the one on PATH, found in the + // directory the compiler itself names, so that a wrapper on PATH that + // runs the compiler is not taken for it. Empty when there is none. + fs::path RealCompiler() { + const char* llvm = std::getenv("CRAFTER_BUILD_LLVM_DIR"); + const std::string compiler = llvm != nullptr && *llvm != '\0' ? (fs::path(llvm) / "bin" / "clang++").string() : std::string("clang++"); + const auto version = RunCommandWithTimeout(std::format("{} --version", ShellQuote(compiler)), std::chrono::seconds(30)); + constexpr std::string_view InstalledDirLine = "\nInstalledDir: "; + const std::size_t at = version.output.find(InstalledDirLine); + if (version.exitCode != 0 || at == std::string::npos) return {}; + const std::size_t begin = at + InstalledDirLine.size(); + std::string dir = version.output.substr(begin, version.output.find('\n', begin) - begin); + while (!dir.empty() && (dir.back() == '\r' || dir.back() == ' ')) dir.pop_back(); + std::error_code ec; + const fs::path real = fs::canonical(fs::path(dir) / "clang++", ec); + return ec ? fs::path() : real; + } + + // A link in `to` to every entry of `from` but the ones `except` names. + void LinkEntries(const fs::path& from, const fs::path& to, std::initializer_list except) { + for (const fs::directory_entry& entry : fs::directory_iterator(from)) { + const std::string name = entry.path().filename().string(); + if (!std::ranges::contains(except, name)) fs::create_symlink(entry.path(), to / name); + } + } +} + +// lint parses a file with the headers of the compiler that builds it, +// wherever that compiler is installed. libclang was given the compile +// command without its compiler and named the driver it runs plain "clang", +// and in a build for the host whose compile command names no libc++ +// directory, such as this test's, that driver, in no directory, looked for +// libc++ only in ../include from the working directory, in +// /usr/local/include and in /usr/include. Where none of them had one, as in +// the Flatpak, whose compiler keeps its libc++ in /app, a file of such a +// build that includes built, and every rule that reads its AST +// then failed on "'algorithm' file not found" (issue #46). +// +// Staged so that it fails without the fix on any host it can be staged on: +// an installation of the test's own, the toolchain's compiler copied into +// install/bin beside links to the rest of the real installation, with one +// header more in its c++/v1, crafter_issue46.h; and the toolchain the build +// is pointed at, whose bin/clang++ is a link to that copy and which has no +// include directory. The compiler runs from install/bin, so its compile finds +// both headers. A parse that looks for libc++ under /usr finds no +// crafter_issue46.h, and one that takes the compile command's own argv[0], +// llvm/bin/clang++, finds none either. The build's scan of the file, which +// clang-scan-deps makes with a driver of its own, is in the same place: given +// llvm/bin/clang++, it failed the build on crafter_issue46.h. A host whose +// compiler the copy cannot stand in for skips. +// +// A compile command whose last prefix flag is -no-canonical-prefixes has the +// compiler take itself to be where clangxx is as written, in llvm/bin, and +// read the clang++.cfg there, which adds a directory only it names. The second +// configuration's file includes a header from that directory, and the scan and +// the parse have to look from llvm/bin as the compile does: given +// install/bin/clang++, both failed on that header. Where the compile itself +// does not read that file, as where a user or system configuration directory +// hides it, the second configuration is left out, and the test skips unless +// the first failed. +int main() { + const fs::path root = fs::temp_directory_path() / "crafter-build-lint-compiler-headers"; + std::error_code ec; + fs::remove_all(root, ec); + + const fs::path compiler = RealCompiler(); + if (compiler.empty()) { + std::println(std::cerr, "SKIP: no clang++ found to stage an installation from"); + return 77; + } + const fs::path real = compiler.parent_path().parent_path(); + if (!fs::is_directory(real / "include" / "c++" / "v1")) { + std::println(std::cerr, "SKIP: {} has no libc++ headers of its own in {}", compiler.string(), (real / "include" / "c++" / "v1").string()); + return 77; + } + for (const std::string_view tool : { "llvm-ar", "clang-scan-deps" }) { + if (!fs::exists(compiler.parent_path() / tool)) { + std::println(std::cerr, "SKIP: no {} beside {} for the staged toolchain", tool, compiler.string()); + return 77; + } + } + const fs::path install = root / "install"; + const fs::path llvm = root / "llvm"; + fs::create_directories(install / "bin"); + fs::create_directories(install / "include" / "c++" / "v1"); + fs::create_directories(llvm / "bin"); + fs::create_directories(root / "project"); + fs::create_directories(root / "cache"); + + // A copy, not a link: clang finds its installation from the file it runs + // as, and a link would lead it back to the real one. The rest is the real + // installation's, linked: the programs and configuration files beside the + // compiler, its shared libraries and its own headers wherever its build + // put them, lib/ or lib64/, and every header, with one more in c++/v1. + fs::copy_file(compiler, install / "bin" / "clang++"); + fs::permissions(install / "bin" / "clang++", fs::perms::owner_all, fs::perm_options::add); + LinkEntries(compiler.parent_path(), install / "bin", {"clang++"}); + LinkEntries(real, install, {"bin", "include"}); + LinkEntries(real / "include", install / "include", {"c++"}); + LinkEntries(real / "include" / "c++", install / "include" / "c++", {"v1"}); + LinkEntries(real / "include" / "c++" / "v1", install / "include" / "c++" / "v1", {}); + Write(install / "include" / "c++" / "v1" / "crafter_issue46.h", "#pragma once\ninline constexpr int CrafterIssue46 = 46;\n"); + // The resource directory the copy works out from where it runs holds + // clang's own headers, stddef.h among them. A clang built to look for it + // somewhere those links do not reach, or a copy that does not start here, + // cannot stand in for the compiler. + const auto resource = RunCommandWithTimeout(std::format("{} -print-resource-dir", ShellQuote((install / "bin" / "clang++").string())), std::chrono::seconds(30)); + std::string resourceDir = resource.output; + while (!resourceDir.empty() && (resourceDir.back() == '\n' || resourceDir.back() == '\r')) resourceDir.pop_back(); + if (resource.exitCode != 0 || !fs::is_directory(fs::path(resourceDir) / "include")) { + std::println(std::cerr, "SKIP: the copy of {} in {} has no resource directory it can use: {}", compiler.string(), (install / "bin").string(), resourceDir); + return 77; + } + + fs::create_symlink(install / "bin" / "clang++", llvm / "bin" / "clang++"); + fs::create_symlink(compiler.parent_path() / "llvm-ar", llvm / "bin" / "llvm-ar"); + fs::create_symlink(compiler.parent_path() / "clang-scan-deps", llvm / "bin" / "clang-scan-deps"); + LinkEntries(real, llvm, {"bin", "include"}); + // The toolchain is resolved once per process, so before anything asks + // for it; and the std module it builds goes to a cache of this run's own. + // A CRAFTER_BUILD_LIBCXX_DIR the suite runs with would have every compile + // take that libc++ in place of the staged one, and a + // CLANG_NO_DEFAULT_CONFIG would have clang read no configuration file, + // the one the second configuration rests on among them. + setenv("CRAFTER_BUILD_LLVM_DIR", llvm.c_str(), 1); + unsetenv("CRAFTER_BUILD_LIBCXX_DIR"); + unsetenv("CLANG_NO_DEFAULT_CONFIG"); + setenv("XDG_CACHE_HOME", (root / "cache").c_str(), 1); + + Write(root / "project" / "unit.cpp", "#include \n#include \n\nint Largest(int a, int b) {\n return std::max(a, b) + CrafterIssue46;\n}\n"); + Configuration cfg; + cfg.path = root / "project"; + cfg.name = "compiler-headers"; + cfg.outputName = "compiler-headers"; + cfg.target = HostTarget(); + cfg.type = ConfigurationType::LibraryStatic; + std::array interfaces = {}; + std::array implementations = { "unit" }; + cfg.GetInterfacesAndImplementations(interfaces, implementations); + + { + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult result = Build(cfg, depResults, depMutex); + Check(result.result.empty(), std::format("the staged toolchain builds the file: {}", result.result)); + } + + std::vector declared; + cfg.AddAstLintRule("reads-ast", [&declared](LintContext& ctx) { + for (const LintDecl& decl : ctx.Decls()) declared.push_back(decl.name); + }); + const LintSummary summary = RunLint(cfg, {}); + Check(summary.errors == 0, "lint parses the file the build compiled (why not is on stderr)"); + Check(std::ranges::contains(declared, std::string("Largest")), "the rule that reads the AST sees the file's function"); + + // The same toolchain, with -no-canonical-prefixes in the command. The + // configuration file beside the link is written only now, once the first + // configuration is done with. The file includes no header of the C++ + // standard library, as llvm/ has no include directory, only the one that + // configuration file's directory holds. + fs::create_directories(root / "cfg-include"); + Write(root / "cfg-include" / "crafter_issue46_cfg.h", "#pragma once\ninline constexpr int CrafterIssue46Cfg = 46;\n"); + Write(llvm / "bin" / "clang++.cfg", std::format("-isystem {}\n", (root / "cfg-include").string())); + Write(root / "project" / "written.cpp", "#include \n\nint Written() {\n return CrafterIssue46Cfg;\n}\n"); + // clang reads the first clang++.cfg it finds, looking in its user and + // system configuration directories before its own, and none where it + // finds a -clang++.cfg first, so the file beside the link can be + // hidden. The compile the case rests on, tried first, says whether it is. + const auto reads = RunCommandWithTimeout(std::format("{} -no-canonical-prefixes -fsyntax-only -x c++ {}", ShellQuote((llvm / "bin" / "clang++").string()), ShellQuote((root / "project" / "written.cpp").string())), std::chrono::seconds(30)); + if (reads.exitCode != 0) { + std::println(std::cerr, "SKIP: the staged clang++ started with -no-canonical-prefixes does not read {}, which a user or system configuration directory can hide: {}", (llvm / "bin" / "clang++.cfg").string(), reads.output.substr(0, reads.output.find('\n'))); + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 77; + } + Configuration written; + written.path = root / "project"; + written.name = "compiler-headers-as-written"; + written.outputName = "compiler-headers-as-written"; + written.target = HostTarget(); + written.type = ConfigurationType::LibraryStatic; + written.compileFlags.push_back("-no-canonical-prefixes"); + std::array writtenImplementations = { "written" }; + written.GetInterfacesAndImplementations(interfaces, writtenImplementations); + + { + std::unordered_map> depResults; + std::mutex depMutex; + const BuildResult result = Build(written, depResults, depMutex); + Check(result.result.empty(), std::format("with -no-canonical-prefixes, the staged toolchain builds the file: {}", result.result)); + } + + std::vector writtenDeclared; + written.AddAstLintRule("reads-ast", [&writtenDeclared](LintContext& ctx) { + for (const LintDecl& decl : ctx.Decls()) writtenDeclared.push_back(decl.name); + }); + const LintSummary writtenSummary = RunLint(written, {}); + Check(writtenSummary.errors == 0, "with -no-canonical-prefixes, lint parses the file the build compiled (why not is on stderr)"); + Check(std::ranges::contains(writtenDeclared, std::string("Written")), "with -no-canonical-prefixes, the rule that reads the AST sees the file's function"); + + if (Failures > 0) { + std::println(std::cerr, "{} assertions failed", Failures); + return 1; + } + return 0; +}