Crafter.Build/interfaces/Crafter.Build-Clang.cppm

1020 lines
58 KiB
Text
Raw Normal View History

2026-07-23 01:24:42 +02:00
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
2026-04-23 01:57:25 +02:00
export module Crafter.Build:Clang;
import std;
import :Shader;
2026-04-27 07:04:42 +02:00
import :Interface;
import :Implementation;
import :External;
fix(incremental): key build outputs on the compiler A project built with one clang kept its outputs when crafter-build started using another. The output directory is named by VariantId(), which hashed every input that changes what is compiled except the compiler itself, and staleness is decided by mtimes, which a compiler update leaves alone. A PCM can only be read by the clang release that wrote it, so after the bundled LLVM moved from 22 to 23 the first build found nothing stale, and the first edit failed with "module file Greeter.pcm uses an older format that is no longer supported" until the project was cleaned by hand. A project with a `#pragma crafter dependency` did not get that far: its project file imports the dependency's PCM, so it failed to load, and for a git dependency that PCM lives in the cache, where `crafter-build clean` does not reach. The same happens natively when the distro updates clang. The toolchain's key now goes into the hash, as the host PCM cache was already keyed on it. An update starts an empty variant directory and rebuilds into it; the previous one stays until `clean`, as after any other change of variant, and two crafter-build versions can work in one checkout without disturbing each other. VariantId() gains an overload taking the toolchain so the dependence can be tested in-process, the way ResolveToolchain and SysrootStdModule take theirs. External cmake builds are not covered: their directory is fixed per clone and keyed on the compiler's path, not its release. Objects of two clang releases link together on the host, so nothing fails there, but they are not rebuilt either. Verified by replaying the update: three projects built with the 2.0.0 Flatpak, then built, edited and run with this one without cleaning, then built with 2.0.0 again. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 20:09:22 +02:00
import :Toolchain;
feat(agents): keep dependencies' AGENTS.consumer.md in AGENTS.md An agent working on a crafter-build project reads its AGENTS.md, and learns nothing there about the libraries the project builds against unless someone copied that in by hand. This repository shows the cost: the code style section of its AGENTS.md restates what Crafter.LintRules enforces, and goes stale whenever the rules change. A library now ships those notes itself, as AGENTS.consumer.md beside its project.cpp; nothing in its project.cpp changes. When a consumer has an AGENTS.md beside its own project.cpp, `crafter-build` and `crafter-build test` keep a section in it, between two marker comments, holding its dependencies' notes. The section is appended the first time and rewritten in place after that. The file is written only when the section changes, and an AGENTS.md is never created. lint, format, run and clean leave it alone. The update runs after loading, which has just fetched every dependency, and before compiling, so a build that fails still has the notes. cfg.dependencyNotes picks the dependencies. Transitive, the default, follows `dependencies` all the way down from the project's own configurations, its tests and its `#pragma crafter dependency` tooling; Direct stops at the first loaded project on each path; None removes the section. A dependency's own pragma tooling never counts: it is about how that dependency is built, not how it is used, and being no `dependencies` edge it is never reached. Nor are a dependency's tests: nothing builds them for the consumer, and their configurations can point at a local their project file has since moved out of. The walk has to know which Configurations belong to another project, and where that project lives, and cfg.path cannot say: only the Configuration GitProject and LocalProject return is rebased, so a dependency's internal configurations keep "./", which resolves to the consumer. The loader records it instead, LoadedProjectOf beside the project cache, and keeps what the root's pragmas resolved to past the frame LoadProject pops, PragmaDependencies. Neither is exported. The markers count only as whole lines outside fenced code blocks, so documentation can quote them. Unbalanced markers and a document ending inside a code block leave the file alone with a warning: guessing which part of someone's file is generated would overwrite their text, and missing the section would add another one on every build. A note that would break the section when it is read back, through a marker line of its own or a code block it never closes, is left out with a warning. The file is replaced through a temporary renamed onto the symlink's target, so a linked AGENTS.md stays a link and a write cut short leaves the old file rather than part of the new one. The code is a new partition, Crafter.Build:Agents, listed in build.sh, CrafterBuildModules, project.cpp and the umbrella. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:18:06 +01:00
import :Agents;
feat: lay an executable out as the files/ of a Flatpak A Linux executable built by the Flatpak crafter-build links the libc++, libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs inside crafter-build's sandbox and practically nowhere else: a host needs glibc 2.38 or newer and all three LLVM libraries, which not even Arch has. A program built here is meant to run in a Flatpak, so it can now be laid out as one: with cfg.packaging = Packaging::Flatpak, or --packaging=flatpak where the project.cpp crafter-build was pointed at calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in the app's sandbox, and -r runs the program there against the libraries the app carries. The program is linked into files/bin, where its shaders, files and assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path, and the new :Flatpak partition writes the rest of files/: files/lib with the LLVM runtime libraries, located one by one through clang, and whatever else the program needs, read with llvm-readelf, that the directories of the shared libraries it is built on hold, the ones an unpackaged link records as run paths, or the toolchain's own lib dir, /app/lib in crafter-build's Flatpak, which the link searches too; and the desktop entry, metainfo and icons under the app-id in files/share, the entry refused when its Icon= is not the app-id or desktop-file-validate, where there is one, rejects it, and an icon that is not an .svg or a square .png. The metadata and export/ of a build directory are flatpak build-finish's to write, and crafter-build keeps no copy of its rules: what a permission means and what the host sees of an app change with flatpak's releases, and a copy would have to follow every one. The writer copies a file only when its content differs, compared a block at a time so that a large file costs no more memory than a small one, and writes one only when what it would write differs, never deciding by an mtime, which ostree sets to 0 for every file of /app, and works the program's libraries out on every write, which reads only their dynamic sections, since a library replaced in place, as by a toolchain update, can need others, which FlatpakLibraryChange checks; it prunes from files/bin each top-level entry an earlier build put there and this one does not, reporting those the program wrote there itself. What cannot be a Flatpak is refused before anything is built, saying why: a Windows or wasm executable, a build against a sysroot or for musl, another architecture than the runtime's, a build against CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and a build by a native crafter-build, which links the host's glibc: a native process knows no Flatpak runtime, from /.flatpak-info, unless CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one. Default stays the executable as linked for now, RunTests runs every test as linked, whatever its Configuration asks for, and RunLint works out its compile command so, and a forwarded --packaging= leaves a dependency's executables alone, since consumers run them by path. A dependency that packages its own executable gets its desktop file, metainfo and icons rebased by the loader as its cfg.files are, so they are its own whatever directory the consumer builds from. Only a Flatpak is keyed into VariantId, so every other configuration keeps its directory, but for one given --packaging=, which was a project arg, hashed into VariantId, and is a standard arg now, a dependency's included. The app-id and what a Flatpak is installed as are not keyed: they change files/share, never what is compiled. The asset name map, kept three times, twice in Build() and once for the browser runtime's files.json, is one function now, CompressedAssetName; CompressAsset, in Crafter.Build-Asset.cpp, keeps the list of the extensions it loads, which has to agree with it. Each copy a Flatpak build makes into the program's directory, of its shaders, assets, cfg.files and what its dependencies forward, records the top-level name it places there, the names of what a directory holds for one copied into it itself ("data/", "data/."), and those are what the writer keeps in files/bin; a build that fails after copying adds them to the writer's record all the same, so the next write removes what no build places any more. SharedLibraryRuns now also packages its program as a Flatpak, whose files/lib has to carry libgreet.so for it to start.
2026-11-01 19:20:55 +01:00
import :Flatpak;
2026-04-23 01:57:25 +02:00
namespace fs = std::filesystem;
feat(wasm): compile C++ with WebAssembly exception handling wasm builds were compiled with -fno-exceptions. A throw did not compile, libc++'s own throws (vector::at, std::format, filesystem) aborted the program, and code that relies on exceptions could not be built for the browser at all. Every wasm unit and the std module now get -fwasm-exceptions, and the link adds -lunwind, which code built that way calls into and the driver does not add. The flag also selects the libc++ under the sysroot's lib/<triple>/eh, which wasi-sdk 33 and later ship next to the noeh one. Those libraries use the standardized encoding (try_table, exnref) while LLVM 23 still emits the legacy one by default, which wasmtime refuses to load and which would put both in one binary, so the flags ask for the standard form with -wasm-use-legacy-eh=false. That makes the setjmp lowering loadable under wasmtime too. The flags live in one constant, WasmBaselineFlags, which the compile command and the std module both take through WasmCompileFlags: a BMI is refused by a unit whose exception setting differs from its own. VariantId and StdPcmDir hash it, so the first build after the update starts fresh instead of importing PCMs built without exceptions, and two releases sharing the Flatpak's cache don't take turns rebuilding one std PCM. A sysroot without the exception-enabled libraries stops the build with a line saying so, rather than at the link with "unable to find library -lunwind". The result needs an engine with exnref: Chrome 137, Firefox 131, Safari 18.4, the bundled wasmtime. The runtime's exception-handling probe tested the legacy encoding; it now tests try_table, every variants.json entry carries it, and a browser without it is told which feature it lacks instead of failing with a CompileError. There is no switch back to -fno-exceptions: engines without exnref are old enough not to keep a second build for them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:54:39 +01:00
namespace Crafter {
fix(wasm): what the review found -flto in a wasm configuration's compileFlags or linkFlags reached the link, where LTO code generation runs without the backend options that keep exception handling: every landing pad was dropped, and the build succeeded with throws that escaped their catch blocks. -fno-exceptions there made every `import std;` fail on the std module built with exceptions, and a wasm shared library failed to link against the eh/ libc++, which is static archives built without -fPIC. Build() refuses all three now, each with a line that says why, before it makes a directory or starts a thread. The sysroot check sat in BuildStdPcm, which the linter calls as well. There the error only dropped the compile command, so lint ran no AST rule on a wasm configuration and reported it clean. It also refused static libraries, which never link, fired after the shader and external threads had started, and called a missing sysroot, or one without the target, "no C++ exception support". It is part of the same early check now, which first says when the sysroot or the target's directory is missing, and asks for libunwind only where something links. C sources got only the signal.h define. setjmp.h refused to compile in C, and a C object given -wasm-enable-sjlj through compileFlags used the legacy exception encoding next to C++ objects in the standard one, a mix engines refuse to load. They get WasmCompileFlags now, like the C++ units, a variant pass's flags included. The baseline probes include simd: V8 and SpiderMonkey switch SIMD off on x86 CPUs without SSE4.1, which virtual machines often present, and such an engine passed the exception-handling probe only to fail compiling the module; the manifest tests expect it on every entry. The Flatpak pins WASI_SDK_EXCEPTIONS=DUAL, which wasi-sdk 34 defaults to only with clang 23 or newer, and checks that the eh/ libunwind got installed: the wasm tests skip without it, so CI would otherwise pass a Flatpak whose every wasm build fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 06:10:41 +01:00
// What every wasm32 translation unit is compiled with, C or C++, and the
// std module the C++ ones import. A BMI cannot be loaded by a unit whose
// options differ from the ones that wrote it, so GetCompileCommand and
// BuildStdPcm both take the set from here (through WasmCompileFlags), and
// VariantId and StdPcmDir hash it so that a crafter-build which changes
// it never reuses what the old set compiled.
feat(wasm): compile C++ with WebAssembly exception handling wasm builds were compiled with -fno-exceptions. A throw did not compile, libc++'s own throws (vector::at, std::format, filesystem) aborted the program, and code that relies on exceptions could not be built for the browser at all. Every wasm unit and the std module now get -fwasm-exceptions, and the link adds -lunwind, which code built that way calls into and the driver does not add. The flag also selects the libc++ under the sysroot's lib/<triple>/eh, which wasi-sdk 33 and later ship next to the noeh one. Those libraries use the standardized encoding (try_table, exnref) while LLVM 23 still emits the legacy one by default, which wasmtime refuses to load and which would put both in one binary, so the flags ask for the standard form with -wasm-use-legacy-eh=false. That makes the setjmp lowering loadable under wasmtime too. The flags live in one constant, WasmBaselineFlags, which the compile command and the std module both take through WasmCompileFlags: a BMI is refused by a unit whose exception setting differs from its own. VariantId and StdPcmDir hash it, so the first build after the update starts fresh instead of importing PCMs built without exceptions, and two releases sharing the Flatpak's cache don't take turns rebuilding one std PCM. A sysroot without the exception-enabled libraries stops the build with a line saying so, rather than at the link with "unable to find library -lunwind". The result needs an engine with exnref: Chrome 137, Firefox 131, Safari 18.4, the bundled wasmtime. The runtime's exception-handling probe tested the legacy encoding; it now tests try_table, every variants.json entry carries it, and a browser without it is told which feature it lacks instead of failing with a CompileError. There is no switch back to -fno-exceptions: engines without exnref are old enough not to keep a second build for them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:54:39 +01:00
//
// -fwasm-exceptions compiles C++ exceptions to WebAssembly exception
// handling. It also selects the sysroot's include/<triple>/eh and
// lib/<triple>/eh, the libc++ built with exceptions that wasi-sdk 33 and
// later ship next to the noeh/ one, so it has to reach the link too; the
// link reuses this command line, so it does. Those libraries use the
// standardized form of the proposal (try_table, exnref), while LLVM 23
// still defaults to the legacy one: wasmtime refuses to load that, and it
// would mix two encodings in one binary. -wasm-use-legacy-eh=false asks
// for the standard form, for setjmp as well. wasi-libc's setjmp.h does
// not compile without -wasm-enable-sjlj, which lowers setjmp to the same
// exception handling, and signal.h needs the emulation define.
inline constexpr std::string_view WasmBaselineFlags = "-fwasm-exceptions -mllvm -wasm-use-legacy-eh=false -msimd128 -fno-c++-static-destructors -mllvm -wasm-enable-sjlj -D_WASI_EMULATED_SIGNAL";
// The wasi-runtime/runtime.js probes an engine has to pass to run anything
// built with WasmBaselineFlags; EnableWasiBrowserRuntime puts them on every
// entry of variants.json. Exception handling with exnref is the newest
fix(wasm): what the review found -flto in a wasm configuration's compileFlags or linkFlags reached the link, where LTO code generation runs without the backend options that keep exception handling: every landing pad was dropped, and the build succeeded with throws that escaped their catch blocks. -fno-exceptions there made every `import std;` fail on the std module built with exceptions, and a wasm shared library failed to link against the eh/ libc++, which is static archives built without -fPIC. Build() refuses all three now, each with a line that says why, before it makes a directory or starts a thread. The sysroot check sat in BuildStdPcm, which the linter calls as well. There the error only dropped the compile command, so lint ran no AST rule on a wasm configuration and reported it clean. It also refused static libraries, which never link, fired after the shader and external threads had started, and called a missing sysroot, or one without the target, "no C++ exception support". It is part of the same early check now, which first says when the sysroot or the target's directory is missing, and asks for libunwind only where something links. C sources got only the signal.h define. setjmp.h refused to compile in C, and a C object given -wasm-enable-sjlj through compileFlags used the legacy exception encoding next to C++ objects in the standard one, a mix engines refuse to load. They get WasmCompileFlags now, like the C++ units, a variant pass's flags included. The baseline probes include simd: V8 and SpiderMonkey switch SIMD off on x86 CPUs without SSE4.1, which virtual machines often present, and such an engine passed the exception-handling probe only to fail compiling the module; the manifest tests expect it on every entry. The Flatpak pins WASI_SDK_EXCEPTIONS=DUAL, which wasi-sdk 34 defaults to only with clang 23 or newer, and checks that the eh/ libunwind got installed: the wasm tests skip without it, so CI would otherwise pass a Flatpak whose every wasm build fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 06:10:41 +01:00
// feature those flags need (Chrome 137, Firefox 131, Safari 18.4). SIMD128
// is older, but V8 and SpiderMonkey switch it off on x86 CPUs without
// SSE4.1, which virtual machines often present.
inline constexpr auto WasmBaselineProbes = std::to_array<std::string_view>({"simd", "exception-handling"});
feat(wasm): compile C++ with WebAssembly exception handling wasm builds were compiled with -fno-exceptions. A throw did not compile, libc++'s own throws (vector::at, std::format, filesystem) aborted the program, and code that relies on exceptions could not be built for the browser at all. Every wasm unit and the std module now get -fwasm-exceptions, and the link adds -lunwind, which code built that way calls into and the driver does not add. The flag also selects the libc++ under the sysroot's lib/<triple>/eh, which wasi-sdk 33 and later ship next to the noeh one. Those libraries use the standardized encoding (try_table, exnref) while LLVM 23 still emits the legacy one by default, which wasmtime refuses to load and which would put both in one binary, so the flags ask for the standard form with -wasm-use-legacy-eh=false. That makes the setjmp lowering loadable under wasmtime too. The flags live in one constant, WasmBaselineFlags, which the compile command and the std module both take through WasmCompileFlags: a BMI is refused by a unit whose exception setting differs from its own. VariantId and StdPcmDir hash it, so the first build after the update starts fresh instead of importing PCMs built without exceptions, and two releases sharing the Flatpak's cache don't take turns rebuilding one std PCM. A sysroot without the exception-enabled libraries stops the build with a line saying so, rather than at the link with "unable to find library -lunwind". The result needs an engine with exnref: Chrome 137, Firefox 131, Safari 18.4, the bundled wasmtime. The runtime's exception-handling probe tested the legacy encoding; it now tests try_table, every variants.json entry carries it, and a browser without it is told which feature it lacks instead of failing with a CompileError. There is no switch back to -fno-exceptions: engines without exnref are old enough not to keep a second build for them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:54:39 +01:00
}
2026-04-23 01:57:25 +02:00
export namespace Crafter {
struct BuildResult {
std::string result;
bool repack;
fix: rebuild and relink on what changed, submodules at their revisions, and mingw found where it is - Shaders record the files glslang opened (a depfile) and their settings (source path, stage, entry point, defines, include directories) in the build directory, and rebuild when an included file or a setting changes, not only the shader's own source. - An executable relinks when its link command changed, not only when an object is newer: a link flag in project.cpp, or a dependency's library that moved (an ExternalDependency built into a new cache directory). The command is recorded beside the objects; its flags come from ordered sets, so the order the dependency threads finish in can't change it. - An external's newest artifact counts its libDirs and versioned .so names. - Submodules are checked out at the revisions the fetched commit records, from the URLs its .gitmodules gives, after every clone, switch, checkout and pull, so a pinned commit builds against its own submodules, and one moved by hand is put back; with no .gitmodules, git isn't asked. - Each external clone's fetch and build hold a file lock: parallel builds pulled into one clone at once ("cannot lock ref"). - mingw: - -stdlib=libstdc++ always; - the std module's source is found through libstdc++.modules.json in the mingw toolchain's own library directories (the generic lib/ holds the host's Linux one), asking the compiler once a run; - a toolchain that isn't there is a build error saying where it looked, not std::terminate; - CRAFTER_MINGW_DIR names the prefix, the directory holding x86_64-w64-mingw32/ and lib/gcc/; - inside the Flatpak the host's /usr mingw is used. - RunScript's exit-status check reads as the one range it is. - Tests: ConcurrentExternalFetch, ExternalArtifactTime, GitSubmodules, LinkFlagsChange, MingwMissing, ShaderIncludeChange; ShaderCompile and ToolchainResolve extended. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:08:13 +02:00
// Sets in order: the commands they go into are compared with the ones
// recorded last time, so they come out the same however the
// dependency threads that fill them happen to finish.
std::set<std::string> libs;
feat(cuda): link the CUDA runtime of the toolkit that compiles the .cu A program with CUDA sources needs the CUDA runtime, which cfg.linkFlags had to name: -L/opt/cuda/lib64 -lcudart for Arch's toolkit, a path into it. In the Flatpak that holds for /opt/cuda but not for the host's /usr/local/cuda, which is under /run/host there, at a path crafter-build resolves for nvcc and a project.cpp does not know. Jorijn chose to have crafter-build link it. A configuration with CUDA sources links the static runtime of the toolkit whose nvcc compiles them, by its path, with the -lrt -lpthread -ldl that nvcc's own link line puts after it. ResolveToolchain finds it with nvcc, as Toolchain::cudaRuntime: libcudart_static.a in the lib64 beside nvcc's bin, looked for without starting a process, so a test can stage a toolkit for it as for nvcc, and crafter-build --version prints it. The static one, so no run path into the toolkit ends up in the program; libcuda.so.1, which the runtime loads, comes with the driver. By its path, not through a -L of the lib64, which would put the toolkit's libraries, such as Arch's libcheckpoint.so, in the way of a project's own of the same name. It goes into BuildResult::runtimeLibs, which a configuration hands its consumers as it does libs and every link puts after them, so whatever is built on a library with CUDA sources links the runtime too, and a -lcudart a project names itself comes first. Where that lib64 holds none, as where a distribution keeps the toolkit's libraries in its own directories, cudaRuntime is empty and nothing is linked, as before: a -lcudart_static the linker could not find would fail the link even of a project that names its own -lcudart. The archive is looked for without throwing, so a lib64 that cannot be looked into, through a link loop or for want of permission, counts as one without it.
2026-11-11 19:34:52 +01:00
// The CUDA runtime that a configuration with CUDA sources, or one it
// is built on, links: Toolchain::cudaRuntime by its path and the -lrt
// -lpthread -ldl it needs, or nothing where the toolkit has none. By
// its path, so no directory of the toolkit's is searched for a
// project's own libraries; after libs on every link, so a -lcudart a
// project names itself is the one the linker takes.
std::set<std::string> runtimeLibs;
2026-05-01 19:02:14 +02:00
// Compile flags (typically -I include paths) the dep wants its
// consumers to see — sourced from its external dependencies' include
// dirs so headers a dep exposes in its public modules are reachable
// when a consumer #includes them directly. Propagates transitively.
fix: rebuild and relink on what changed, submodules at their revisions, and mingw found where it is - Shaders record the files glslang opened (a depfile) and their settings (source path, stage, entry point, defines, include directories) in the build directory, and rebuild when an included file or a setting changes, not only the shader's own source. - An executable relinks when its link command changed, not only when an object is newer: a link flag in project.cpp, or a dependency's library that moved (an ExternalDependency built into a new cache directory). The command is recorded beside the objects; its flags come from ordered sets, so the order the dependency threads finish in can't change it. - An external's newest artifact counts its libDirs and versioned .so names. - Submodules are checked out at the revisions the fetched commit records, from the URLs its .gitmodules gives, after every clone, switch, checkout and pull, so a pinned commit builds against its own submodules, and one moved by hand is put back; with no .gitmodules, git isn't asked. - Each external clone's fetch and build hold a file lock: parallel builds pulled into one clone at once ("cannot lock ref"). - mingw: - -stdlib=libstdc++ always; - the std module's source is found through libstdc++.modules.json in the mingw toolchain's own library directories (the generic lib/ holds the host's Linux one), asking the compiler once a run; - a toolchain that isn't there is a build error saying where it looked, not std::terminate; - CRAFTER_MINGW_DIR names the prefix, the directory holding x86_64-w64-mingw32/ and lib/gcc/; - inside the Flatpak the host's /usr mingw is used. - RunScript's exit-status check reads as the one range it is. - Tests: ConcurrentExternalFetch, ExternalArtifactTime, GitSubmodules, LinkFlagsChange, MingwMissing, ShaderIncludeChange; ShaderCompile and ToolchainResolve extended. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:08:13 +02:00
std::set<std::string> publicCompileFlags;
// Absolute directories the shared libraries this links against are
// loaded from at run time, its dependencies' included, and, once a
// shared library is linked, its own bin dir, for its consumers. An
// executable or shared library linked from them records each one as
feat: lay an executable out as the files/ of a Flatpak A Linux executable built by the Flatpak crafter-build links the libc++, libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs inside crafter-build's sandbox and practically nowhere else: a host needs glibc 2.38 or newer and all three LLVM libraries, which not even Arch has. A program built here is meant to run in a Flatpak, so it can now be laid out as one: with cfg.packaging = Packaging::Flatpak, or --packaging=flatpak where the project.cpp crafter-build was pointed at calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in the app's sandbox, and -r runs the program there against the libraries the app carries. The program is linked into files/bin, where its shaders, files and assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path, and the new :Flatpak partition writes the rest of files/: files/lib with the LLVM runtime libraries, located one by one through clang, and whatever else the program needs, read with llvm-readelf, that the directories of the shared libraries it is built on hold, the ones an unpackaged link records as run paths, or the toolchain's own lib dir, /app/lib in crafter-build's Flatpak, which the link searches too; and the desktop entry, metainfo and icons under the app-id in files/share, the entry refused when its Icon= is not the app-id or desktop-file-validate, where there is one, rejects it, and an icon that is not an .svg or a square .png. The metadata and export/ of a build directory are flatpak build-finish's to write, and crafter-build keeps no copy of its rules: what a permission means and what the host sees of an app change with flatpak's releases, and a copy would have to follow every one. The writer copies a file only when its content differs, compared a block at a time so that a large file costs no more memory than a small one, and writes one only when what it would write differs, never deciding by an mtime, which ostree sets to 0 for every file of /app, and works the program's libraries out on every write, which reads only their dynamic sections, since a library replaced in place, as by a toolchain update, can need others, which FlatpakLibraryChange checks; it prunes from files/bin each top-level entry an earlier build put there and this one does not, reporting those the program wrote there itself. What cannot be a Flatpak is refused before anything is built, saying why: a Windows or wasm executable, a build against a sysroot or for musl, another architecture than the runtime's, a build against CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and a build by a native crafter-build, which links the host's glibc: a native process knows no Flatpak runtime, from /.flatpak-info, unless CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one. Default stays the executable as linked for now, RunTests runs every test as linked, whatever its Configuration asks for, and RunLint works out its compile command so, and a forwarded --packaging= leaves a dependency's executables alone, since consumers run them by path. A dependency that packages its own executable gets its desktop file, metainfo and icons rebased by the loader as its cfg.files are, so they are its own whatever directory the consumer builds from. Only a Flatpak is keyed into VariantId, so every other configuration keeps its directory, but for one given --packaging=, which was a project arg, hashed into VariantId, and is a standard arg now, a dependency's included. The app-id and what a Flatpak is installed as are not keyed: they change files/share, never what is compiled. The asset name map, kept three times, twice in Build() and once for the browser runtime's files.json, is one function now, CompressedAssetName; CompressAsset, in Crafter.Build-Asset.cpp, keeps the list of the extensions it loads, which has to agree with it. Each copy a Flatpak build makes into the program's directory, of its shaders, assets, cfg.files and what its dependencies forward, records the top-level name it places there, the names of what a directory holds for one copied into it itself ("data/", "data/."), and those are what the writer keeps in files/bin; a build that fails after copying adds them to the writer's record all the same, so the next write removes what no build places any more. SharedLibraryRuns now also packages its program as a Flatpak, whose files/lib has to carry libgreet.so for it to start.
2026-11-01 19:20:55 +01:00
// a run path, except an executable packaged as a Flatpak: its one run
// path is $ORIGIN/../lib, and WriteFlatpak copies what it needs from
// these directories into files/lib.
std::set<std::string> runPaths;
2026-04-27 07:04:42 +02:00
};
2026-04-23 01:57:25 +02:00
2026-04-27 07:04:42 +02:00
struct Define {
2026-04-23 01:57:25 +02:00
std::string name;
std::string value;
};
feat: feature-detected browser-wasm variants (relaxed-SIMD) + variant-aware runtime The browser wasm pipeline hardcoded -msimd128 for every wasm32 target and baked a single wasm URL into index.html, so newer codegen features that aren't yet baseline across engines (relaxed SIMD today; threads, future SIMD revisions later) couldn't be adopted without dropping the browsers that lack them. Add a general, feature-parameterized mechanism owned entirely by Crafter.Build: - Configuration::wasmVariants declares N codegen variants (label, extra -m flags, runtime probes). Build() compiles the baseline plus one outputName.<label>.wasm per variant, recompiling the whole graph (incl. dep libs + std PCM) with the variant's flags — relaxed-SIMD is per-TU codegen, not a link switch. wasmVariantFlags folds into VariantId so each variant's objects/PCMs land in their own build+bin dir. - EnableWasiBrowserRuntime emits a variants.json manifest (label -> url + probes), preferred-first with the baseline as the universal fallback. - The shipped runtime.js runs inlined wasm-feature-detect probes (relaxed-simd, simd, tail-call, bulk-memory, exception-handling, threads), picks the first variant whose probes all pass, and falls back to the single baked CRAFTER_WASM_URL when no manifest is present (backward compatible). - EnableWasiRelaxedSimdVariant registers the relaxed-SIMD variant — the motivating case (Chrome 114+/Firefox 120+ enable it by default; Safari still flag-gates it as of mid-2026). Verified end to end: a wasm32-wasip1 build emits both wasi-hello.wasm and wasi-hello.relaxed-simd.wasm + variants.json; Firefox selects the relaxed-simd variant and runs it. Resolves #24 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 15:14:18 +00:00
// A browser-wasm codegen variant. The same wasm32 target is compiled more
// than once, each pass adding `flags` to every translation unit, so newer
// ISA features (relaxed SIMD today; threads, future SIMD revisions, … later)
// can be adopted without dropping engines that lack them. Each non-empty
// `label` emits an additional `outputName.<label>.wasm` alongside the
// baseline `outputName.wasm`; `probes` names the runtime feature-detect
// checks (see wasi-runtime/runtime.js's probe registry) that must all pass
feat(wasm): compile C++ with WebAssembly exception handling wasm builds were compiled with -fno-exceptions. A throw did not compile, libc++'s own throws (vector::at, std::format, filesystem) aborted the program, and code that relies on exceptions could not be built for the browser at all. Every wasm unit and the std module now get -fwasm-exceptions, and the link adds -lunwind, which code built that way calls into and the driver does not add. The flag also selects the libc++ under the sysroot's lib/<triple>/eh, which wasi-sdk 33 and later ship next to the noeh one. Those libraries use the standardized encoding (try_table, exnref) while LLVM 23 still emits the legacy one by default, which wasmtime refuses to load and which would put both in one binary, so the flags ask for the standard form with -wasm-use-legacy-eh=false. That makes the setjmp lowering loadable under wasmtime too. The flags live in one constant, WasmBaselineFlags, which the compile command and the std module both take through WasmCompileFlags: a BMI is refused by a unit whose exception setting differs from its own. VariantId and StdPcmDir hash it, so the first build after the update starts fresh instead of importing PCMs built without exceptions, and two releases sharing the Flatpak's cache don't take turns rebuilding one std PCM. A sysroot without the exception-enabled libraries stops the build with a line saying so, rather than at the link with "unable to find library -lunwind". The result needs an engine with exnref: Chrome 137, Firefox 131, Safari 18.4, the bundled wasmtime. The runtime's exception-handling probe tested the legacy encoding; it now tests try_table, every variants.json entry carries it, and a browser without it is told which feature it lacks instead of failing with a CompileError. There is no switch back to -fno-exceptions: engines without exnref are old enough not to keep a second build for them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:54:39 +01:00
// for a browser to be served this variant, on top of WasmBaselineProbes,
// which every build needs. The first variant whose probes pass wins; the
// baseline is the fallback, and an engine that fails even its probes gets
// an error naming them.
feat: feature-detected browser-wasm variants (relaxed-SIMD) + variant-aware runtime The browser wasm pipeline hardcoded -msimd128 for every wasm32 target and baked a single wasm URL into index.html, so newer codegen features that aren't yet baseline across engines (relaxed SIMD today; threads, future SIMD revisions later) couldn't be adopted without dropping the browsers that lack them. Add a general, feature-parameterized mechanism owned entirely by Crafter.Build: - Configuration::wasmVariants declares N codegen variants (label, extra -m flags, runtime probes). Build() compiles the baseline plus one outputName.<label>.wasm per variant, recompiling the whole graph (incl. dep libs + std PCM) with the variant's flags — relaxed-SIMD is per-TU codegen, not a link switch. wasmVariantFlags folds into VariantId so each variant's objects/PCMs land in their own build+bin dir. - EnableWasiBrowserRuntime emits a variants.json manifest (label -> url + probes), preferred-first with the baseline as the universal fallback. - The shipped runtime.js runs inlined wasm-feature-detect probes (relaxed-simd, simd, tail-call, bulk-memory, exception-handling, threads), picks the first variant whose probes all pass, and falls back to the single baked CRAFTER_WASM_URL when no manifest is present (backward compatible). - EnableWasiRelaxedSimdVariant registers the relaxed-SIMD variant — the motivating case (Chrome 114+/Firefox 120+ enable it by default; Safari still flag-gates it as of mid-2026). Verified end to end: a wasm32-wasip1 build emits both wasi-hello.wasm and wasi-hello.relaxed-simd.wasm + variants.json; Firefox selects the relaxed-simd variant and runs it. Resolves #24 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 15:14:18 +00:00
struct WasmVariant {
std::string label;
std::vector<std::string> flags;
std::vector<std::string> probes;
};
2026-04-23 01:57:25 +02:00
enum class ConfigurationType {
Executable,
LibraryStatic,
LibraryDynamic,
};
feat: lay an executable out as the files/ of a Flatpak A Linux executable built by the Flatpak crafter-build links the libc++, libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs inside crafter-build's sandbox and practically nowhere else: a host needs glibc 2.38 or newer and all three LLVM libraries, which not even Arch has. A program built here is meant to run in a Flatpak, so it can now be laid out as one: with cfg.packaging = Packaging::Flatpak, or --packaging=flatpak where the project.cpp crafter-build was pointed at calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in the app's sandbox, and -r runs the program there against the libraries the app carries. The program is linked into files/bin, where its shaders, files and assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path, and the new :Flatpak partition writes the rest of files/: files/lib with the LLVM runtime libraries, located one by one through clang, and whatever else the program needs, read with llvm-readelf, that the directories of the shared libraries it is built on hold, the ones an unpackaged link records as run paths, or the toolchain's own lib dir, /app/lib in crafter-build's Flatpak, which the link searches too; and the desktop entry, metainfo and icons under the app-id in files/share, the entry refused when its Icon= is not the app-id or desktop-file-validate, where there is one, rejects it, and an icon that is not an .svg or a square .png. The metadata and export/ of a build directory are flatpak build-finish's to write, and crafter-build keeps no copy of its rules: what a permission means and what the host sees of an app change with flatpak's releases, and a copy would have to follow every one. The writer copies a file only when its content differs, compared a block at a time so that a large file costs no more memory than a small one, and writes one only when what it would write differs, never deciding by an mtime, which ostree sets to 0 for every file of /app, and works the program's libraries out on every write, which reads only their dynamic sections, since a library replaced in place, as by a toolchain update, can need others, which FlatpakLibraryChange checks; it prunes from files/bin each top-level entry an earlier build put there and this one does not, reporting those the program wrote there itself. What cannot be a Flatpak is refused before anything is built, saying why: a Windows or wasm executable, a build against a sysroot or for musl, another architecture than the runtime's, a build against CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and a build by a native crafter-build, which links the host's glibc: a native process knows no Flatpak runtime, from /.flatpak-info, unless CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one. Default stays the executable as linked for now, RunTests runs every test as linked, whatever its Configuration asks for, and RunLint works out its compile command so, and a forwarded --packaging= leaves a dependency's executables alone, since consumers run them by path. A dependency that packages its own executable gets its desktop file, metainfo and icons rebased by the loader as its cfg.files are, so they are its own whatever directory the consumer builds from. Only a Flatpak is keyed into VariantId, so every other configuration keeps its directory, but for one given --packaging=, which was a project arg, hashed into VariantId, and is a standard arg now, a dependency's included. The app-id and what a Flatpak is installed as are not keyed: they change files/share, never what is compiled. The asset name map, kept three times, twice in Build() and once for the browser runtime's files.json, is one function now, CompressedAssetName; CompressAsset, in Crafter.Build-Asset.cpp, keeps the list of the extensions it loads, which has to agree with it. Each copy a Flatpak build makes into the program's directory, of its shaders, assets, cfg.files and what its dependencies forward, records the top-level name it places there, the names of what a directory holds for one copied into it itself ("data/", "data/."), and those are what the writer keeps in files/bin; a build that fails after copying adds them to the writer's record all the same, so the next write removes what no build places any more. SharedLibraryRuns now also packages its program as a Flatpak, whose files/lib has to carry libgreet.so for it to start.
2026-11-01 19:20:55 +01:00
// What an executable is delivered as. Read for executables only; a
// library is never packaged.
enum class Packaging {
// The executable as linked, for now; Flatpak is asked for by name.
Default,
// The files/ of a Flatpak in BinDir(), what becomes /app in the
// app's sandbox: the program and what it reads at run time in
// files/bin, the shared libraries it needs in files/lib, and its
// desktop entry, metainfo and icons in files/share. An x86_64 Linux
// (glibc) executable without a sysroot, built by the Flatpak
// crafter-build, since it links that runtime's glibc.
Flatpak,
// The executable as linked, with its files beside it in BinDir().
// Built by the Flatpak crafter-build, it needs the libc++,
// libc++abi and libunwind in /app/lib, so it runs inside that
// sandbox (-r, test, run scripts) and practically nowhere else.
None,
};
struct Test;
struct TestRunner {
// Command template the harness executes to run the test binary.
// Local runners leave this empty; prefix runners (Cmd, Wine) set it to
// a template like "wine {bin} {args}" or "qemu-aarch64 {bin} {args}".
std::string exec;
// Display name; also the cache key for the availability probe.
std::string name;
// Runs once per RunTests invocation (cached by `name`). Exit 0 = runner
// is available; non-zero = skip every Test using this runner with a
// "runner unavailable" message. Empty = always available (e.g., Local).
std::string probe;
bool IsLocal() const { return exec.empty(); }
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
static TestRunner Local();
// Prefix runner: wraps the local binary in `<command> {bin} {args}`.
// Used for qemu-user, wasmtime, and similar single-binary wrappers.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
static TestRunner Cmd(std::string command);
// Run a Windows .exe through Wine. Probes `wine` on PATH.
static TestRunner Wine();
// Parse a `<kind>[:<arg>]` spec used by CRAFTER_BUILD_RUNNER_<target>
// and --runner=. Supported: "local", "cmd:<binary>". Returns nullopt
// for an empty string; throws on a non-empty unrecognized spec.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
static std::optional<TestRunner> FromSpec(std::string_view spec);
// Honor CRAFTER_BUILD_RUNNER_<target> (power-user override). Triple
// dashes/dots become underscores so they're valid in env-var names.
// Returns `fallback` when the env var is unset.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
static TestRunner FromEnv(std::string_view target, TestRunner fallback = Local());
test: introduce test.toml + target-derived runners alongside existing machinery Vendors toml++ v3.4.0 as lib/toml.hpp and wires it into Crafter.Build-Test to parse a declarative test.toml manifest (target/march/mtune/sysroot/ requires/timeout/args/defines). Test discovery now treats project.cpp and test.toml as mutually exclusive: project.cpp stays the escape hatch for outer-driver tests, test.toml gives downstream test authors a no-boilerplate path. Adds: - TestRunner::Wine() and TestRunner::ForTarget(cfg) — runner is now derived from cfg.target (Local for host, Wine for Windows-on-Linux, wasmtime for WASI, qemu-<arch> with QEMU_LD_PREFIX for non-host Linux). The env-var override CRAFTER_BUILD_RUNNER_<target> still wins as a power-user escape hatch via FromEnv. - Declarative preconditions: tool:<name>, file:<path>, env:<VAR> are evaluated before the build; missing preconditions Skip without paying the compile cost. - Hard-fail-unless-declared: when a derived runner's tool is missing AND the test didn't declare 'tool:<that>' in requires, the missing runner is a Fail instead of a silent Skip. Surfaces broken cross-arch CI config that previously hid as "skipped". - Multi-target sweep: bare `crafter-build test` (no --target=) now iterates every distinct test.toml-declared target plus the host, so cross-arch tests run by default without the user needing to know which targets exist. `--target=X` bypasses the sweep. Test struct gains a `requires_` vector so project.cpp users can declare preconditions too (matching what test.toml writes there). Existing tests, factories (Ssh/SshWin/Wsl/Cmd), and CRAFTER_BUILD_RUNNER_* machinery remain intact — this commit only adds; migration and deletion follow in subsequent commits. Refs issue #8. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 17:47:39 +02:00
// Derive a runner from a Configuration's target triple + sysroot.
// Returns Local() when target equals the host, Wine() for Windows
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
// targets, `qemu-<arch>` (with QEMU_LD_PREFIX
test: introduce test.toml + target-derived runners alongside existing machinery Vendors toml++ v3.4.0 as lib/toml.hpp and wires it into Crafter.Build-Test to parse a declarative test.toml manifest (target/march/mtune/sysroot/ requires/timeout/args/defines). Test discovery now treats project.cpp and test.toml as mutually exclusive: project.cpp stays the escape hatch for outer-driver tests, test.toml gives downstream test authors a no-boilerplate path. Adds: - TestRunner::Wine() and TestRunner::ForTarget(cfg) — runner is now derived from cfg.target (Local for host, Wine for Windows-on-Linux, wasmtime for WASI, qemu-<arch> with QEMU_LD_PREFIX for non-host Linux). The env-var override CRAFTER_BUILD_RUNNER_<target> still wins as a power-user escape hatch via FromEnv. - Declarative preconditions: tool:<name>, file:<path>, env:<VAR> are evaluated before the build; missing preconditions Skip without paying the compile cost. - Hard-fail-unless-declared: when a derived runner's tool is missing AND the test didn't declare 'tool:<that>' in requires, the missing runner is a Fail instead of a silent Skip. Surfaces broken cross-arch CI config that previously hid as "skipped". - Multi-target sweep: bare `crafter-build test` (no --target=) now iterates every distinct test.toml-declared target plus the host, so cross-arch tests run by default without the user needing to know which targets exist. `--target=X` bypasses the sweep. Test struct gains a `requires_` vector so project.cpp users can declare preconditions too (matching what test.toml writes there). Existing tests, factories (Ssh/SshWin/Wsl/Cmd), and CRAFTER_BUILD_RUNNER_* machinery remain intact — this commit only adds; migration and deletion follow in subsequent commits. Refs issue #8. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 17:47:39 +02:00
// set when cfg.sysroot is non-empty) for non-host -linux- triples,
// `wasmtime` for wasm32-wasi/wasm64-wasi, and Local() as a last
// resort. CRAFTER_BUILD_RUNNER_<target> still wins as an override
// upstream of this — see FromEnv.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
static TestRunner ForTarget(const struct Configuration& cfg);
};
enum class TestOutcome { Pass, Fail, Crash, Timeout, Skipped };
struct TestResult {
std::string name;
TestOutcome outcome = TestOutcome::Pass;
2026-07-23 01:24:42 +02:00
std::int32_t exitCode = 0;
std::int32_t signal = 0;
std::chrono::milliseconds duration{0};
std::string output;
};
2026-07-23 01:24:42 +02:00
// One lint diagnostic. Produced by LintContext::Report — or derived by
// the driver when a transform rule's SetContent output differs from the
// file on disk ("would reformat") — collected and printed compiler-style
// by RunLint (Crafter.Build:Lint):
// <file>:<line>: warning: <message> [<rule>]
struct LintFinding {
fs::path file;
std::size_t line = 0; // 1-based; 0 = whole-file finding
std::string rule; // name of the rule that produced it
std::string message;
};
// Parsed `// lint-disable-*` suppression directives for one file (see
// LintContext::Suppressed). Line keys are 1-based and refer to the line a
// next-line directive TARGETS (the line after the comment).
struct LintSuppressions {
bool fileAll = false;
std::unordered_set<std::string> fileRules;
std::unordered_set<std::size_t> lineAll;
std::unordered_map<std::size_t, std::unordered_set<std::string>> lineRules;
};
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
// Lexical class of a LintToken, mirroring clang's token kinds one-to-one.
enum class LintTokenKind {
Punctuation,
Keyword,
Identifier,
Literal, // string, raw string, character, integer, floating literal
Comment, // // ... or /* ... */
};
// One token from LintContext::Tokens(). `offset`/`length` are byte offsets
// into LintContext::content and stay valid until the next SetContent.
//
// A raw string literal or a block comment is ONE token and may span lines,
// which is exactly what the hand-rolled scanners could not represent. The
// stream also covers text inside preprocessor branches that are inactive
// for the host — clang_tokenize lexes, it does not evaluate #if — so token
// rules see every platform's code, not just the one being built.
struct LintToken {
LintTokenKind kind = LintTokenKind::Punctuation;
std::size_t offset = 0;
std::size_t length = 0;
std::size_t line = 0; // 1-based, of the token's first byte
std::size_t column = 0; // 1-based, of the token's first byte
};
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
// What a LintDecl declares.
enum class LintDeclKind {
Namespace,
Class,
Struct,
Union,
Enum,
EnumConstant,
TypeAlias,
Function,
Method,
Constructor,
Destructor,
Field,
Variable, // local or namespace-scope variable
Parameter,
Other,
};
inline constexpr std::size_t LintNoParent = static_cast<std::size_t>(-1);
// One declaration from LintContext::Decls(), for declarations written in
// the file under lint (never ones pulled in from a header or module).
//
// The vector is flattened depth-first with parents before children, and
// `parent` indexes back into it — that is how a rule asks "is this at
// namespace scope, or inside a function?" without re-deriving a brace
// stack from the text.
struct LintDecl {
LintDeclKind kind = LintDeclKind::Other;
std::string name; // unqualified spelling; empty when anonymous
std::string type; // clang's resolved spelling: "char *", "std::int32_t"
std::size_t line = 0;
std::size_t column = 0;
std::size_t nameOffset = 0; // byte offset of the declared name
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
std::size_t begin = 0; // byte offsets of the whole declaration, for
std::size_t end = 0; // marking a region a transform must not touch
// For the FIRST declarator of a statement, `begin` is the start of the
// shared type and so precedes `nameOffset`. For a continuation
// declarator — the `b` of `int* a, b;` — the extent starts at the name,
// so begin == nameOffset. That is how a multi-declarator statement is
// recognised without re-parsing the text, and each declarator's `type`
// is its OWN resolved type: `int *` for a, plain `int` for b.
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
std::size_t parent = LintNoParent;
bool isDefinition = false;
bool isStatic = false;
bool isConstexpr = false;
bool isScopedEnum = false; // `enum class` rather than plain `enum`
// ---- foreign-API boundary ----
// Set when this declaration's spelling is dictated by somebody else's
// header, so the type-modernising rules must leave its bytes alone.
// Replaces the hand-maintained substring denylists, which could only
// ever grow: a new external library needs no new entry here.
feat(lint): const-local and constexpr-constant rules Two rules the AST makes possible, plus the mutation analysis behind them. const-local reports a local that is never written. It is restricted to SCALARS — integers, bools, enums, floating types — and that restriction is what makes the answer exact rather than a guess: a scalar has no member functions, so the only ways to write one are assignment, ++/--, having its address taken, or binding to a non-const reference. All four are now tracked in the walk: - assignment and compound assignment visit their LEFT operand in a write context, the right one normally; - ++/-- and & write their operand; - a call argument is checked against the callee's parameter type, so passing to `const int&` or by value is a read while `int&` is a write; - initialising a non-const reference writes what it binds to. For a class type a non-const method call could mutate it, and deciding that is the whole-program analysis clang-tidy does, so those are simply out of scope rather than guessed at. constexpr-constant promotes a const constant whose initialiser is made only of literals and operators, so `const int A = 1 << 4;` qualifies and `const int B = Compute();` does not. On this repository const-local found 103 candidates, which was too many to be useful, and the reason was informative: most were range-for bindings and pointer locals. `for (T* const x : …)` and `T* const p` are not spellings anybody writes, and the useful constness for a pointer is on the pointee, which this rule cannot advise on. Excluding both leaves 36, all plain bool or enum locals worth fixing — isWasm, isPe, exists, writes, isC and so on. Those 36 are fixed in this commit; the compiler verified every one. Both rules are report-only. The analysis is exact, but adding const is a judgement about intent as much as mechanics, and a wrong suggestion should cost a glance rather than a build. const-local also deliberately does not become a transform: inserting `const` before a shared type would apply it to every declarator in a multi-declarator statement, including any that IS written. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 00:50:48 +02:00
// ---- constness ----
// The declared type is const-qualified.
bool isConst = false;
// A scalar: integer, floating, bool, enum or pointer. For these,
// "is it ever written" is decidable from assignments, ++/--, address-of
// and reference bindings alone — there are no member calls that could
// mutate it — so isMutated is exact rather than a guess.
bool isScalar = false;
// Written to somewhere in this file: assigned, incremented, had its
// address taken, or bound to a non-const reference. Only meaningful
// for a declaration whose uses are all in this file, so a local rather
// than something with external linkage.
bool isMutated = false;
// The initialiser is a constant expression, as decided by clang's own
// constant evaluator rather than by inspecting its tokens. Only set for
// Variable and Field.
bool isConstantInitialised = false;
feat(lint): const-local and constexpr-constant rules Two rules the AST makes possible, plus the mutation analysis behind them. const-local reports a local that is never written. It is restricted to SCALARS — integers, bools, enums, floating types — and that restriction is what makes the answer exact rather than a guess: a scalar has no member functions, so the only ways to write one are assignment, ++/--, having its address taken, or binding to a non-const reference. All four are now tracked in the walk: - assignment and compound assignment visit their LEFT operand in a write context, the right one normally; - ++/-- and & write their operand; - a call argument is checked against the callee's parameter type, so passing to `const int&` or by value is a read while `int&` is a write; - initialising a non-const reference writes what it binds to. For a class type a non-const method call could mutate it, and deciding that is the whole-program analysis clang-tidy does, so those are simply out of scope rather than guessed at. constexpr-constant promotes a const constant whose initialiser is made only of literals and operators, so `const int A = 1 << 4;` qualifies and `const int B = Compute();` does not. On this repository const-local found 103 candidates, which was too many to be useful, and the reason was informative: most were range-for bindings and pointer locals. `for (T* const x : …)` and `T* const p` are not spellings anybody writes, and the useful constness for a pointer is on the pointee, which this rule cannot advise on. Excluding both leaves 36, all plain bool or enum locals worth fixing — isWasm, isPe, exists, writes, isC and so on. Those 36 are fixed in this commit; the compiler verified every one. Both rules are report-only. The analysis is exact, but adding const is a judgement about intent as much as mechanics, and a wrong suggestion should cost a glance rather than a build. const-local also deliberately does not become a transform: inserting `const` before a shared type would apply it to every declarator in a multi-declarator statement, including any that IS written. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 00:50:48 +02:00
// Method declared const. Only set for Method.
bool isConstMethod = false;
// Method declared static. Only set for Method.
bool isStaticMethod = false;
// The binding of a range-for: `for (T x : range)`. A loop binding is
// not a variable a reader thinks of as assignable, so constness advice
// about it is noise.
bool isLoopVariable = false;
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
bool isExternC = false; // declared with C language linkage
bool isForeignApi = false; // its type or its body binds to an entity
// declared outside the project root
};
2026-07-23 01:24:42 +02:00
// Per-file view handed to each LintRule's check callback. Every member
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
// function is out-of-line (defined in Crafter.Build:Lint's implementation
// unit) because rule lambdas execute from the user's project.so and
// resolve against the running executable: clang does not emit
// module-attached in-class inline bodies into consumers (see ArgQuery
// below).
2026-07-23 01:24:42 +02:00
struct LintContext {
fs::path file; // absolute path of the file under lint
std::string content; // whole file as read from disk
std::vector<std::string_view> lines; // views into `content`, one per line, no '\n'
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::string Extension() const; // ".cppm", ".cpp", ".h", ...
std::string_view Line(std::size_t n) const; // 1-based; empty if out of range
2026-07-27 02:59:11 +02:00
// `content` with comments and string/char literal bodies blanked to
// spaces, newlines preserved — offsets and line numbers stay valid.
// Built from Tokens() on first call, cached per file, so raw strings,
// escapes, encoding prefixes and literals like '"' all come out right.
// A raw string is reduced to R"…" with the body and the delimiter
// scaffolding blanked, leaving exactly two quote characters.
//
// Convenient for a quick scan, but Tokens() is the better tool for
// anything structural: this view cannot tell an identifier from a
// keyword, and it has already thrown away where the literals were.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
const std::string& CommentStripped();
2026-07-23 01:24:42 +02:00
// Record a finding at `line` (1-based; pass 0 for a whole-file finding).
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void Report(std::size_t line, std::string message);
2026-07-23 01:24:42 +02:00
// Replace the file's content. Makes this rule a *transform*:
// `crafter-build format` writes the result back to disk; `lint`
// derives would-reformat findings from it (dry — never writes).
// `lines` is re-split and CommentStripped() re-derives on next call;
// string_views taken before this call are invalidated. Recommended
// pattern: build the new string, call SetContent once at the end. Do
// not assign `content` directly — that bypasses the re-split. May be
// combined with Report() in the same rule.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void SetContent(std::string newContent);
2026-07-23 01:24:42 +02:00
// True when `rule` is suppressed at `line` (1-based; 0 = whole-file,
// which only file-level directives cover) by a suppression comment:
// // lint-disable-next-line [rules...] applies to the following line
// // lint-disable-file [rules...] applies to the whole file
// Rule names are space- or comma-separated; none = all rules. The
// driver already filters Report()
// findings and reverts line-preserving transform edits on suppressed
// lines; a transform that MERGES or SPLITS lines must consult this
// itself for every line its edit touches (the driver cannot map lines
// across a count-changing rewrite). Parsed lazily from the raw lines;
// re-parsed after SetContent.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
bool Suppressed(std::string_view rule, std::size_t line);
2026-07-23 01:24:42 +02:00
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
// The file lexed by clang, in source order. Built on first call, cached
// per file, re-lexed after SetContent. Empty for extensions that are
// not C or C++ (shaders): lexing GLSL as C++ would produce nonsense.
//
// Prefer this to scanning characters. It is the only view that gets
// raw strings, line splices, digraphs and nested quoting right, and
// offsets index straight into `content`, so a transform can find in
// the token stream and edit in place.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::span<const LintToken> Tokens();
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
// The token's own bytes: content.substr(tok.offset, tok.length).
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::string_view TokenText(const LintToken& token) const;
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
// Tokens whose FIRST byte is on `line` (1-based). A token that starts
// earlier and spans into `line` — a raw string, a block comment — is
// not included; ask Tokens() directly when that matters.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::span<const LintToken> TokensOnLine(std::size_t line);
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
// True when a comment token starts on `line`. Replaces `Line(n).contains("//")`,
// which false-positives on a `//` inside a string literal.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
bool LineHasComment(std::size_t line);
fix(lint): make the reflow guards token-accurate instead of textual The transforms guard themselves against comments and raw strings before joining or rewriting a line, because pulling text up past a `//` buries it and reflowing a multi-line literal changes the string. Those guards were substring probes over the raw line, so they answered the wrong question: Line(n).contains("//") fires on // inside a string literal Line(n).contains("R\"") fires on the characters R" inside a literal, and MISSES a raw string opened on an earlier line Both misfire on this repo's own sources. "MARKER" ends in R", and any string mentioning a lint-disable directive contains //. Two wrapped call sites in tests/Lint were being left unjoined for exactly these reasons; they join now, and the results are in this commit. Replaced by LineHasComment() (added with the token layer) and a new LineHasMultiLineToken(), which reports whether any token actually covering that line spans a line boundary — a raw string or a block comment. Backed by a per-line bitmap derived from the token cache and invalidated with it. The guards themselves stay: joining across a real comment or a real multi-line literal is still unsafe, and there are tests for both. What changes is that they now fire on comments and literals rather than on the characters that spell them. format-concat gets narrower as a result. It used to refuse any line containing R" and ask for a manual fix; now only a literal that genuinely spans lines does that, because a single-line raw string reduces to R"…" in the stripped view, fails the plain-literal test, and travels through as an argument with its spelling intact. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 03:08:06 +02:00
// True when `line` (1-based) is touched by a token that spans more
// than one line — a raw string or a block comment. A transform that
// joins, splits or rewrites such a line changes what is inside that
// token, so this is the guard to consult before reflowing anything.
// Replaces `Line(n).contains("R\"")`, which both misses raw strings
// opened on an earlier line and fires on the characters R" appearing
// inside an ordinary literal.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
bool LineHasMultiLineToken(std::size_t line);
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
// Declarations written in this file, flattened depth-first with
// parents before children (see LintDecl). Empty when the AST is not
// available — check AstAvailable() first, and do not read an empty
// result as "this file declares nothing".
//
// Requires the module PCMs, unlike Tokens(): a module unit's
// `import std;` cannot resolve without them, and clang treats that as
// fatal rather than recovering. RunLint builds them on demand for
// rules registered through AddAstLintRule and fails the run if it
// cannot, so a semantic rule never silently reports clean.
//
// One further asymmetry worth knowing: an AST is ONE configuration's
// slice. Declarations inside a preprocessor branch that is inactive
// for the host are absent here, though Tokens() still sees them. Rules
// that must cover every platform belong on tokens.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::span<const LintDecl> Decls();
bool AstAvailable();
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
// Why AstAvailable() is false — a missing PCM, a parse error, a file
// that is not a translation unit. Empty when the AST is available.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::string_view AstUnavailableReason();
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
2026-07-23 01:24:42 +02:00
// Driver wiring — set by RunLint before each check call. Not for rules.
std::string activeRule;
std::vector<LintFinding>* sink = nullptr;
std::optional<std::string> commentStrippedCache;
std::optional<LintSuppressions> suppressionsCache;
feat(lint): libclang-backed token layer Adds LintContext::Tokens() and friends, backed by clang_tokenize, as the substrate the rules will move onto. Nothing consumes it yet. libclang is dlopen'd rather than linked: -lclang would break the mingw and MSVC cross-builds at link time and would put a libclang.so.NN runtime dependency into the otherwise self-contained release tarballs. The clang-c header is used for its declarations only, and the function-pointer table is typed with decltype so the signatures cannot drift from the real API. Three properties this buys that the hand-rolled scanners could not have: - a raw string literal or block comment is ONE token, so the documented "raw string literals are not recognized" limitation goes away; - `//` inside a literal is not a comment, so LineHasComment() replaces the Line(n).contains("//") probes that false-positive on it; - tokens cover preprocessor branches that are inactive for the host, since clang_tokenize lexes rather than evaluates #if. Token rules therefore keep seeing every platform's code, which an AST could not offer. The parse backing the tokenizer is expected to fail on module units — no PCMs, no build flags — and that is fine, because lexing has no semantic prerequisites. Verified in the new tests. LintSummary::Clean() now counts `errors`. It previously ignored them, so an infrastructure failure that produced no findings reported clean and exited 0; a missing libclang would have been exactly that. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 02:54:38 +02:00
std::optional<std::vector<LintToken>> tokenCache;
fix(lint): make the reflow guards token-accurate instead of textual The transforms guard themselves against comments and raw strings before joining or rewriting a line, because pulling text up past a `//` buries it and reflowing a multi-line literal changes the string. Those guards were substring probes over the raw line, so they answered the wrong question: Line(n).contains("//") fires on // inside a string literal Line(n).contains("R\"") fires on the characters R" inside a literal, and MISSES a raw string opened on an earlier line Both misfire on this repo's own sources. "MARKER" ends in R", and any string mentioning a lint-disable directive contains //. Two wrapped call sites in tests/Lint were being left unjoined for exactly these reasons; they join now, and the results are in this commit. Replaced by LineHasComment() (added with the token layer) and a new LineHasMultiLineToken(), which reports whether any token actually covering that line spans a line boundary — a raw string or a block comment. Backed by a per-line bitmap derived from the token cache and invalidated with it. The guards themselves stay: joining across a real comment or a real multi-line literal is still unsafe, and there are tests for both. What changes is that they now fire on comments and literals rather than on the characters that spell them. format-concat gets narrower as a result. It used to refuse any line containing R" and ask for a manual fix; now only a literal that genuinely spans lines does that, because a single-line raw string reduces to R"…" in the stripped view, fails the plain-literal test, and travels through as an argument with its spelling intact. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 03:08:06 +02:00
// Per-line flag, 0-based, for LineHasMultiLineToken. Derived from
// tokenCache and invalidated with it.
std::optional<std::vector<bool>> spannedLineCache;
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
// Flags this file parses with, from GetCompileCommand of the
// Configuration that owns it. Empty disables Decls().
std::string compileCommand;
// Declarations resolving outside this are foreign API (LintDecl).
fs::path projectRoot;
std::optional<std::vector<LintDecl>> declCache;
std::string astReason;
2026-07-23 01:24:42 +02:00
};
// A named lint rule: `check` runs once per (rule, file) over the project's
// own sources. Rules self-filter by ctx.Extension() / ctx.file. A rule
// that calls ctx.SetContent is a transform — defined once, it both gates
// `crafter-build lint` and fixes under `crafter-build format`.
struct LintRule {
std::string name;
std::function<void(LintContext&)> check;
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
// Registered via AddAstLintRule: this rule reads Decls(), so the run
// has to produce the module PCMs first, and must fail rather than let
// the rule quietly find nothing.
bool needsAst = false;
2026-07-23 01:24:42 +02:00
};
feat(script): scripts in project.cpp, run with `crafter-build run` A project.cpp could describe how a project is built, tested and linted, but not the chores around it: packaging, installing, publishing. Those stayed shell lines in a README or in someone's history. Configuration gains `scripts`, a plain list like `defines`. A Script is a name and a C++ callback, as a lint rule is; there is no script language and no config file. The callback gets a ScriptContext (the project, the project file's directory, the arguments) and returns the exit status. ctx.Run runs a shell command with the terminal attached and returns its status. It is only stored when project.cpp loads, which happens for every verb and for every project that depends on this one. `crafter-build run <name> [args...]` runs one, a bare `run` lists them. Only the scripts of the project crafter-build was pointed at are runnable, never a dependency's. Everything after the script's name is handed to the script untouched. The two branches that do this sit ahead of every other branch of the parse loop, --version and --help included. Below the verbs, `run package clean` would delete build/, and any other word would land in the project's args and so in the variant hash, moving the build to another directory. Options before the name keep their meaning, so project args go there. The driver is its own partition, :Script. It refuses a project with no scripts, a name that is empty or starts with '-' (it could never be typed), a name declared twice (running either would be a guess) and an unknown name, each with exit 1 and without running anything. A script that throws exits 1. A return value outside 0..255 becomes 1: an exit status is eight bits, and a raw wait status such as 256 would otherwise wrap to success. Two helpers in :Platform: - RunCommandAttached runs a command with inherited stdio. Every helper so far captured through popen, which is right for a compile step and useless for a command that runs for half an hour or asks a question. It reads the wait status through DecodeWaitStatus, which RunCommandChecked and RunCommandWithTimeout now share. - ShellQuote is exported. It existed twice, as ShellQuote in :External and ShellQuoteSh in :Test, with the same behaviour; both are gone. A script that puts a path into a command needs it too. Not included: a string shorthand for one-command scripts (a one-line lambda covers it) and a ctx.Build() helper (Build() is already exported). A new partition and new exported symbols: run ./build.sh. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-06 18:16:00 +02:00
struct Configuration;
// The name StdPcmDir gives the directory of this configuration's std
// module under `toolchain`: target, march and the toolchain's key, which
// say what it is, then a hash of everything else it is compiled with,
// each flag BuildStdPcm passes (StdPcmFlags) and for the mingw target the
// prefix behind its --sysroot. Two configurations that would compile the
// std module differently never share a directory, so neither rebuilds it
// under the PCMs the other compiled against it. Declared ahead of
// Configuration, whose VariantId keys on it.
std::string StdPcmKey(const Configuration& config, const Toolchain& toolchain);
feat(script): scripts in project.cpp, run with `crafter-build run` A project.cpp could describe how a project is built, tested and linted, but not the chores around it: packaging, installing, publishing. Those stayed shell lines in a README or in someone's history. Configuration gains `scripts`, a plain list like `defines`. A Script is a name and a C++ callback, as a lint rule is; there is no script language and no config file. The callback gets a ScriptContext (the project, the project file's directory, the arguments) and returns the exit status. ctx.Run runs a shell command with the terminal attached and returns its status. It is only stored when project.cpp loads, which happens for every verb and for every project that depends on this one. `crafter-build run <name> [args...]` runs one, a bare `run` lists them. Only the scripts of the project crafter-build was pointed at are runnable, never a dependency's. Everything after the script's name is handed to the script untouched. The two branches that do this sit ahead of every other branch of the parse loop, --version and --help included. Below the verbs, `run package clean` would delete build/, and any other word would land in the project's args and so in the variant hash, moving the build to another directory. Options before the name keep their meaning, so project args go there. The driver is its own partition, :Script. It refuses a project with no scripts, a name that is empty or starts with '-' (it could never be typed), a name declared twice (running either would be a guess) and an unknown name, each with exit 1 and without running anything. A script that throws exits 1. A return value outside 0..255 becomes 1: an exit status is eight bits, and a raw wait status such as 256 would otherwise wrap to success. Two helpers in :Platform: - RunCommandAttached runs a command with inherited stdio. Every helper so far captured through popen, which is right for a compile step and useless for a command that runs for half an hour or asks a question. It reads the wait status through DecodeWaitStatus, which RunCommandChecked and RunCommandWithTimeout now share. - ShellQuote is exported. It existed twice, as ShellQuote in :External and ShellQuoteSh in :Test, with the same behaviour; both are gone. A script that puts a path into a command needs it too. Not included: a string shorthand for one-command scripts (a one-line lambda covers it) and a ctx.Build() helper (Build() is already exported). A new partition and new exported symbols: run ./build.sh. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-06 18:16:00 +02:00
// What a Script's callback is handed when `crafter-build run <name>`
// starts it.
struct ScriptContext {
feat: let a project file return several configurations A project.cpp described one configuration: CrafterBuildProject returns a Configuration by value, and anything else the project wanted built had to be among that one's dependencies. There it was built as part of that configuration's graph: under the check that a graph builds each module once, with its libraries handed up to whatever links that configuration, and with its tests and scripts out of reach of `test` and `run`. Jorijn asked for a project.cpp that can return several unrelated configurations which all get built, and suggested a separate entry point, so that no existing project file breaks. A project file now defines one of two functions. CrafterBuildProject is as it was. CrafterBuildConfigurations returns std::vector<Configuration*>: pointers to configurations the file keeps alive itself, or that GitProject and LocalProject gave it. The two have different names because the loader finds the entry point by its C symbol, which carries no return type, so one name with two return types would be called as whichever the loader guessed. They are pointers because a project file takes pointers between its configurations, for `dependencies` and for a test's, before it returns them, and a vector of values would move them. LoadConfigurations loads a project file with either entry point and returns the list. A CrafterBuildProject's Configuration comes back as a list of one, constructed by the call where the loader keeps it for the rest of the process; LoadProjectFromRoot, which did that for a sibling's, leaves it to LoadConfigurations, and the project cache holds the lists without owning a Configuration. The Configuration of the project crafter-build is pointed at is kept that long as well, where it was a local of Run(). LoadConfigurations throws for a file that defines both functions or neither, and for a CrafterBuildConfigurations that returns nothing, a null pointer or one configuration twice. It also throws for one that returns a configuration a project loaded through GitProject or LocalProject keeps to itself, which the loader now takes down when it loads that project's file: what the configurations the file returned led to through `dependencies` or through their tests, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. Returned from here, such a configuration would count as this file's own to `test` and `run`, and only the configurations a project file returns are rebased onto its directory. LoadProject stays, for a caller that wants a CrafterBuildProject's Configuration by value, and throws for a file with the other entry point. GitProject and LocalProject keep, per spec and args, the list a sibling's file returned, and return the first one unless the spec's new `configuration` names another by Configuration::name. Every configuration of the list is rebased onto the sibling's directory, except one that another project's file had returned before, which was rebased onto that project's. Specs that differ only in the name they pick share one load. A name the sibling does not have throws, listing the names it has, and a name two of its configurations share throws too. A `#pragma crafter dependency` gets the first. BuildAll builds the returned configurations in one pass. Each is built by Build(), as a project's one configuration is, the first on the calling thread and each other one on a thread of its own, and its result then goes into the record of the pass under its PcmDir, where Build() looks for a dependency. One that another of them is built on is built before that other starts, which then finds it in the record: started beside it, the other would not find it there yet and would build it a second time. A configuration is not put into the record before it is built, because a dependency of its own that is built into the same directory would be handed its unfinished build and wait for it, while it waits for the dependency. All of them are built to the end, and the errors come back in the order given, each message once; an exception a build throws comes back as an error that names the configuration, where Run() printed the exception's own text for a project's one configuration. Refused before anything is built: two that would be built into one directory, which would be two builds writing the same files at once; several that are each built on something of another's directory, so that none could be built first; and one that is built on something of its own directory when another is built on that directory as well, since the record holds one result for a directory and the other could be given either. One shortcut is in it. A wasm executable that declares wasmVariants builds what it is built on once more per variant, and says which variant by rewriting those configurations in place, at the end of its Build(). A library that two returned configurations share would change under the one still building its baseline, so with such an executable anywhere in the graph BuildAll builds the configurations one after the other, on the calling thread. Keeping them side by side takes a variant driver that does not rewrite configurations other builds read, which this commit does not attempt. Run() works on the list. A build builds all of it. `test` runs the tests, and `run` offers the scripts, of the ones in it that the project file made itself. One that another project's file returned to GitProject or LocalProject, and that this file returns in turn, is built with the rest, but its tests and scripts stay that project's, so `run` still reaches only the scripts of the project crafter-build was pointed at. What the list itself rules out Run() refuses once the project file has loaded, before any of the list is built and before AGENTS.md is written: for a build, `-r`, `install` and `bundle` whatever BuildAll refuses a list for, and for `test`, which builds its tests with Build() and never comes to BuildAll, two returned configurations of one directory. BuildAll makes its refusals again for whoever calls it. A script is handed the configuration it is declared on. `lint` and `format` walk from every returned configuration and keep, as before, the configurations in the project's directory: the returned ones first, in the order the file returned them, then what they depend on, so that of two returned ones that register a rule under one name the earlier one's runs. `-r` runs the executable when exactly one of them is one, and `install` and `bundle` export the one that is packaged as a Flatpak; with more than one candidate each refuses and names them, `-r` once everything is built and `install` and `bundle` before anything is. AGENTS.md takes the notes that the dependencyNotes of each returned configuration the file made itself selects among what that one is built against, and the file's pragma tooling and a returned configuration of another project go by the widest of those settings. There, a configuration is another project's when GitProject or LocalProject loaded it from another project file than the one whose AGENTS.md is written, two files being one when they resolve to one path, so UpdateAgentsMd still reads the setting of a Configuration one of the two returned when it is given that Configuration's own project file. For that, RunTests, RunLint, RunScript and UpdateAgentsMd each gained an overload that takes the list, and the one that takes a single Configuration calls it with a list of one. SetParentProject gained one too, and ParentLib searches the graph of every configuration it was given. BuildAll, RunTests and RunScript count a configuration the list names twice once. The tests of several configurations share what one configuration's had to itself: AddTest names a test's sources, tests/<name>, and its build directory after the test and its compile state, not after the configuration that declares it. Two configurations that each declare a test of one name, compiled alike, would have RunTests build both in that one directory, each with the dependencies of its own declaration. RunTests fails both without building either, and each failure names the configurations. It compares tests of different configurations only, so a project of one configuration is treated as it was. The --help text names the second entry point, says what -r, install and bundle do with several configurations, and speaks of the project file's entry point as what gets the project args, where it named CrafterBuildProject. AGENTS.template.md says that a project.cpp returns one configuration or several, that Run() works on the list and what a new verb has to decide about it, which configurations have their path rebased, and that the scripts of a returned configuration of another project cannot be run. Two of its notes named LoadProject as what loads a project.cpp for crafter-build, which Run(), GitProject and LocalProject no longer call, and speak of the load now. Its rule for the link flags of a test that loads a project file names the ways a test loads one, where it named LoadProject, and its entry for `:Script` speaks of the `scripts` of the configurations the driver is given, where it named `cfg.scripts`. Its entry for `:Platform` names LoadConfigurations beside LoadProject. That entry also said that `:Platform` holds all OS-specific code, which it did not before this range either, :Agents, :Progress, :Lint and :Clang including POSIX headers of their own, and no longer says so. The bug-prover lens's section names BuildAll's threads and LoadConfigurations. Not in this commit: a way to say which executable -r runs or which app install and bundle export when there are several, and a keyword that lets a `#pragma crafter dependency` name a configuration.
2026-11-15 02:16:06 +01:00
// The Configuration the script is declared on: the one project.cpp
// returned, or of several the one whose `scripts` holds it. Read the
// project through this rather than capturing a local of the entry
// point by reference: the local need not be the object that the
// entry point returned.
feat(script): scripts in project.cpp, run with `crafter-build run` A project.cpp could describe how a project is built, tested and linted, but not the chores around it: packaging, installing, publishing. Those stayed shell lines in a README or in someone's history. Configuration gains `scripts`, a plain list like `defines`. A Script is a name and a C++ callback, as a lint rule is; there is no script language and no config file. The callback gets a ScriptContext (the project, the project file's directory, the arguments) and returns the exit status. ctx.Run runs a shell command with the terminal attached and returns its status. It is only stored when project.cpp loads, which happens for every verb and for every project that depends on this one. `crafter-build run <name> [args...]` runs one, a bare `run` lists them. Only the scripts of the project crafter-build was pointed at are runnable, never a dependency's. Everything after the script's name is handed to the script untouched. The two branches that do this sit ahead of every other branch of the parse loop, --version and --help included. Below the verbs, `run package clean` would delete build/, and any other word would land in the project's args and so in the variant hash, moving the build to another directory. Options before the name keep their meaning, so project args go there. The driver is its own partition, :Script. It refuses a project with no scripts, a name that is empty or starts with '-' (it could never be typed), a name declared twice (running either would be a guess) and an unknown name, each with exit 1 and without running anything. A script that throws exits 1. A return value outside 0..255 becomes 1: an exit status is eight bits, and a raw wait status such as 256 would otherwise wrap to success. Two helpers in :Platform: - RunCommandAttached runs a command with inherited stdio. Every helper so far captured through popen, which is right for a compile step and useless for a command that runs for half an hour or asks a question. It reads the wait status through DecodeWaitStatus, which RunCommandChecked and RunCommandWithTimeout now share. - ShellQuote is exported. It existed twice, as ShellQuote in :External and ShellQuoteSh in :Test, with the same behaviour; both are gone. A script that puts a path into a command needs it too. Not included: a string shorthand for one-command scripts (a one-line lambda covers it) and a ctx.Build() helper (Build() is already exported). A new partition and new exported symbols: run ./build.sh. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-06 18:16:00 +02:00
Configuration& project;
// Absolute directory of the project file. Commands run in the
// directory crafter-build was started from, like everything else it
// does, so a script names its files through this.
fs::path projectDir;
// Everything the user typed after the script's name, untouched:
// crafter-build interprets none of it.
std::span<const std::string> args;
// Run `command` through sh with the terminal attached — output
// appears as it is produced, the command can prompt, Ctrl-C reaches
// it — after echoing it as `$ command` (not under -q). Returns its
// exit code, 128+signal when it was killed; return that from the
// script to make it the exit code of crafter-build. Quote anything
// that is not a literal with ShellQuote. Out-of-line like
// LintContext's members: the callback runs from project.so.
std::int32_t Run(std::string_view command) const;
};
// A project script: a chore that belongs to the project but is not part
// of building it (packaging, installing, publishing, serving), run by
// name with `crafter-build run <name> [args...]`. `run` returns the
// process exit code. It is only stored when project.cpp is loaded, which
// happens for every verb and for every project that depends on this one,
// so whatever a script needs to probe it probes when it runs. Only the
// scripts of the project crafter-build was pointed at can be run, never
// a dependency's.
struct Script {
std::string name;
std::function<std::int32_t(ScriptContext&)> run;
};
feat(toolchain): resolve the compiler in one place Every clang++, clang and llvm-ar the tool spawned was a bare name on PATH, the std module source was /usr/share/libc++/v1/std.cppm, the WASI sysroot /usr/share/wasi-sysroot and the mingw headers /usr/x86_64-w64-mingw32, spelled out at eighteen call sites. A toolchain installed anywhere else, which is what the Flatpak ships under /app, had no way in. Crafter.Build:Toolchain resolves all of it once per process: CRAFTER_BUILD_LLVM_DIR, else a clang++ installed beside crafter-build (<prefix>/bin, found through the same walk GetCrafterBuildHome does), else PATH. What sits beside the compiler is used when present: its libclang.so, its clang-c headers, its std module source, its WASI sysroot. An explicit prefix without a clang++ is an error rather than a fallback, for the same reason CRAFTER_BUILD_LIBCLANG was already exclusive. CRAFTER_BUILD_LIBCXX_DIR points at a libc++ install other than the compiler's own, and CRAFTER_MINGW_DIR now does what its help line always claimed: it is passed as --sysroot for the mingw target. Binaries linked by a toolchain outside /usr get an rpath to its lib dir, since its libc++.so.1 is not on the loader's default path. HostTarget() is the resolved clang's -print-target-triple. A clang built without a vendor reports x86_64-unknown-linux-gnu where Arch's reports x86_64-pc-linux-gnu, so target equality that decides whether a test runs locally and which targets a bare `test` sweeps goes through SameTarget, which ignores the vendor field. The strings themselves are never rewritten: clang rejects a PCM whose triple differs from the importing unit's. The examples and README stop hardcoding the host triple; the default is already the host. `crafter-build --version` prints the version baked in at build time (CRAFTER_BUILD_VERSION, else `git describe`, else 0.0.0-dev), the compiler and the host triple, and is answered before any argument is forwarded to project.cpp. The version is a define on the library, so each version is its own library variant and relinks the executable and tests once per commit. build.sh gains a shebang and `set -eu`, honours CRAFTER_BUILD_LLVM_DIR and CRAFTER_BUILD_VERSION, skips the glslang clone when it is already there, and writes a fresh archive instead of appending to one that may hold members from an older layout. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 22:26:31 +02:00
// The host target triple: what the resolved toolchain's clang++ prints
// for -print-target-triple (see GetToolchain). Used as the default for
2026-04-29 18:59:01 +02:00
// Configuration::target so projects don't have to hardcode it for the
feat(toolchain): resolve the compiler in one place Every clang++, clang and llvm-ar the tool spawned was a bare name on PATH, the std module source was /usr/share/libc++/v1/std.cppm, the WASI sysroot /usr/share/wasi-sysroot and the mingw headers /usr/x86_64-w64-mingw32, spelled out at eighteen call sites. A toolchain installed anywhere else, which is what the Flatpak ships under /app, had no way in. Crafter.Build:Toolchain resolves all of it once per process: CRAFTER_BUILD_LLVM_DIR, else a clang++ installed beside crafter-build (<prefix>/bin, found through the same walk GetCrafterBuildHome does), else PATH. What sits beside the compiler is used when present: its libclang.so, its clang-c headers, its std module source, its WASI sysroot. An explicit prefix without a clang++ is an error rather than a fallback, for the same reason CRAFTER_BUILD_LIBCLANG was already exclusive. CRAFTER_BUILD_LIBCXX_DIR points at a libc++ install other than the compiler's own, and CRAFTER_MINGW_DIR now does what its help line always claimed: it is passed as --sysroot for the mingw target. Binaries linked by a toolchain outside /usr get an rpath to its lib dir, since its libc++.so.1 is not on the loader's default path. HostTarget() is the resolved clang's -print-target-triple. A clang built without a vendor reports x86_64-unknown-linux-gnu where Arch's reports x86_64-pc-linux-gnu, so target equality that decides whether a test runs locally and which targets a bare `test` sweeps goes through SameTarget, which ignores the vendor field. The strings themselves are never rewritten: clang rejects a PCM whose triple differs from the importing unit's. The examples and README stop hardcoding the host triple; the default is already the host. `crafter-build --version` prints the version baked in at build time (CRAFTER_BUILD_VERSION, else `git describe`, else 0.0.0-dev), the compiler and the host triple, and is answered before any argument is forwarded to project.cpp. The version is a define on the library, so each version is its own library variant and relinks the executable and tests once per commit. build.sh gains a shebang and `set -eu`, honours CRAFTER_BUILD_LLVM_DIR and CRAFTER_BUILD_VERSION, skips the glslang clone when it is already there, and writes a fresh archive instead of appending to one that may hold members from an older layout. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 22:26:31 +02:00
// no-cross-compile case. Returns "" when no compiler could be resolved;
// those projects still need an explicit cfg.target, and the first build
// step reports the missing compiler.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::string HostTarget();
feat(toolchain): resolve the compiler in one place Every clang++, clang and llvm-ar the tool spawned was a bare name on PATH, the std module source was /usr/share/libc++/v1/std.cppm, the WASI sysroot /usr/share/wasi-sysroot and the mingw headers /usr/x86_64-w64-mingw32, spelled out at eighteen call sites. A toolchain installed anywhere else, which is what the Flatpak ships under /app, had no way in. Crafter.Build:Toolchain resolves all of it once per process: CRAFTER_BUILD_LLVM_DIR, else a clang++ installed beside crafter-build (<prefix>/bin, found through the same walk GetCrafterBuildHome does), else PATH. What sits beside the compiler is used when present: its libclang.so, its clang-c headers, its std module source, its WASI sysroot. An explicit prefix without a clang++ is an error rather than a fallback, for the same reason CRAFTER_BUILD_LIBCLANG was already exclusive. CRAFTER_BUILD_LIBCXX_DIR points at a libc++ install other than the compiler's own, and CRAFTER_MINGW_DIR now does what its help line always claimed: it is passed as --sysroot for the mingw target. Binaries linked by a toolchain outside /usr get an rpath to its lib dir, since its libc++.so.1 is not on the loader's default path. HostTarget() is the resolved clang's -print-target-triple. A clang built without a vendor reports x86_64-unknown-linux-gnu where Arch's reports x86_64-pc-linux-gnu, so target equality that decides whether a test runs locally and which targets a bare `test` sweeps goes through SameTarget, which ignores the vendor field. The strings themselves are never rewritten: clang rejects a PCM whose triple differs from the importing unit's. The examples and README stop hardcoding the host triple; the default is already the host. `crafter-build --version` prints the version baked in at build time (CRAFTER_BUILD_VERSION, else `git describe`, else 0.0.0-dev), the compiler and the host triple, and is answered before any argument is forwarded to project.cpp. The version is a define on the library, so each version is its own library variant and relinks the executable and tests once per commit. build.sh gains a shebang and `set -eu`, honours CRAFTER_BUILD_LLVM_DIR and CRAFTER_BUILD_VERSION, skips the glslang clone when it is already there, and writes a fresh archive instead of appending to one that may hold members from an older layout. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 22:26:31 +02:00
// Target equality that ignores the vendor field: x86_64-pc-linux-gnu,
// x86_64-unknown-linux-gnu and x86_64-linux-gnu are one target as far as
// "does this test run on this host" goes, and which spelling a clang
// reports depends on how it was built. The strings themselves are never
// rewritten: clang rejects a PCM whose triple string differs from the
// importing unit's, so what the user wrote is what the compiler sees.
std::string NormalizeTarget(std::string_view triple);
bool SameTarget(std::string_view a, std::string_view b);
2026-04-29 18:59:01 +02:00
2026-04-23 01:57:25 +02:00
struct Configuration {
2026-04-27 07:04:42 +02:00
fs::path path;
std::string outputName;
std::string name;
2026-04-23 01:57:25 +02:00
std::string march = "native";
std::string mtune = "native";
2026-04-29 18:59:01 +02:00
std::string target = HostTarget();
std::string sysroot;
2026-04-23 01:57:25 +02:00
bool debug = false;
ConfigurationType type = ConfigurationType::Executable;
feat: lay an executable out as the files/ of a Flatpak A Linux executable built by the Flatpak crafter-build links the libc++, libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs inside crafter-build's sandbox and practically nowhere else: a host needs glibc 2.38 or newer and all three LLVM libraries, which not even Arch has. A program built here is meant to run in a Flatpak, so it can now be laid out as one: with cfg.packaging = Packaging::Flatpak, or --packaging=flatpak where the project.cpp crafter-build was pointed at calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in the app's sandbox, and -r runs the program there against the libraries the app carries. The program is linked into files/bin, where its shaders, files and assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path, and the new :Flatpak partition writes the rest of files/: files/lib with the LLVM runtime libraries, located one by one through clang, and whatever else the program needs, read with llvm-readelf, that the directories of the shared libraries it is built on hold, the ones an unpackaged link records as run paths, or the toolchain's own lib dir, /app/lib in crafter-build's Flatpak, which the link searches too; and the desktop entry, metainfo and icons under the app-id in files/share, the entry refused when its Icon= is not the app-id or desktop-file-validate, where there is one, rejects it, and an icon that is not an .svg or a square .png. The metadata and export/ of a build directory are flatpak build-finish's to write, and crafter-build keeps no copy of its rules: what a permission means and what the host sees of an app change with flatpak's releases, and a copy would have to follow every one. The writer copies a file only when its content differs, compared a block at a time so that a large file costs no more memory than a small one, and writes one only when what it would write differs, never deciding by an mtime, which ostree sets to 0 for every file of /app, and works the program's libraries out on every write, which reads only their dynamic sections, since a library replaced in place, as by a toolchain update, can need others, which FlatpakLibraryChange checks; it prunes from files/bin each top-level entry an earlier build put there and this one does not, reporting those the program wrote there itself. What cannot be a Flatpak is refused before anything is built, saying why: a Windows or wasm executable, a build against a sysroot or for musl, another architecture than the runtime's, a build against CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and a build by a native crafter-build, which links the host's glibc: a native process knows no Flatpak runtime, from /.flatpak-info, unless CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one. Default stays the executable as linked for now, RunTests runs every test as linked, whatever its Configuration asks for, and RunLint works out its compile command so, and a forwarded --packaging= leaves a dependency's executables alone, since consumers run them by path. A dependency that packages its own executable gets its desktop file, metainfo and icons rebased by the loader as its cfg.files are, so they are its own whatever directory the consumer builds from. Only a Flatpak is keyed into VariantId, so every other configuration keeps its directory, but for one given --packaging=, which was a project arg, hashed into VariantId, and is a standard arg now, a dependency's included. The app-id and what a Flatpak is installed as are not keyed: they change files/share, never what is compiled. The asset name map, kept three times, twice in Build() and once for the browser runtime's files.json, is one function now, CompressedAssetName; CompressAsset, in Crafter.Build-Asset.cpp, keeps the list of the extensions it loads, which has to agree with it. Each copy a Flatpak build makes into the program's directory, of its shaders, assets, cfg.files and what its dependencies forward, records the top-level name it places there, the names of what a directory holds for one copied into it itself ("data/", "data/."), and those are what the writer keeps in files/bin; a build that fails after copying adds them to the writer's record all the same, so the next write removes what no build places any more. SharedLibraryRuns now also packages its program as a Flatpak, whose files/lib has to carry libgreet.so for it to start.
2026-11-01 19:20:55 +01:00
// What the executable is delivered as (see Packaging).
// ApplyStandardArgs sets it from --packaging=none|flatpak.
Packaging packaging = Packaging::Default;
feat: install and bundle a Flatpak through the host's flatpak An executable packaged as a Flatpak came out as the files/ of one, which only flatpak build-finish makes an app of, and getting it installed or onto another machine took flatpak commands on the host, typed by hand. Two verbs do it where the host's flatpak can be reached: `crafter-build install` builds the project and installs its app for this user, and `crafter-build bundle` builds it into bin/<variant>.flatpak, a single file for `flatpak install --user` that names Flathub's repository for the runtime. Inside crafter-build's Flatpak they need the org.freedesktop.Flatpak permission, which its manifest does not grant in this commit. Both put the app into the project's repo first, in build/flatpak-apps/<app-id>/ (FlatpakAppDir), one per app rather than per variant, since flatpak-builder's state there is its cache. Every variant exports into it, so the export and the install or bundle made from it hold a lock there, and another crafter-build exporting meanwhile waits rather than leave this one installing or bundling its program. The user remote an install re-points is every checkout's that builds the app-id, so re-pointing it and installing from it hold a second lock, which every crafter-build installing there takes, natively or in the Flatpak, whatever its XDG_CACHE_HOME: in ~/.cache/crafter.build/flatpak-remotes/, found by HOME, for the user's own installation, which flatpak hides from the sandbox behind a tmpfs of the sandbox's own, and in the directory of a private one, FLATPAK_USER_DIR, one lock for all of them where the sandbox shares that directory with the host. Without modules, the host's flatpak build-finish finishes build/flatpak-apps/<app-id>/build-dir, made afresh each time from a metadata naming the app, its runtime and the Sdk and a tree of hard links to the build's files/, copies where a link cannot be made, across filesystems or on one without links, vfat or exFAT: it writes the command, the sandbox's permissions and export/ by flatpak's own rules, those of whichever flatpak the host runs, and refuses a permission it does not know, and flatpak build-export puts the result into the repo. When cfg.flatpak.modules names flatpak-builder module files for what the app needs in /app besides the program, flatpak-builder does both, from a manifest that lists them and copies the built program in last, so nothing is compiled twice. That manifest keeps share/locale in the app ("separate-locales": false): flatpak-builder would split it into a .Locale extension by default, which a bundle, holding the app alone, leaves out. The loader rebases a dependency's module files as it does its cfg.files. install uses a user remote named after the app-id, re-pointed at the repo each time, and says how to remove both. The app's tree in build/flatpak-apps/<app-id>/build-dir, where flatpak-builder installs a module's files too, is left out of the include walk with every other build/, so the headers a module installed reach no compile. cfg.flatpak gets the runtime, the Platform or the Sdk at the branch crafter-build runs on, and the sandbox's permissions, finish-args as Flatpak spells them, which any configuration may declare: an executable gets its dependencies' first and its own last, so it can take one back. The build reads neither, and a change to either links nothing. install and bundle print the permissions, with where each came from, and hand them to build-finish, the one judge of what they mean, so a refusal can be traced to the configuration that declared it. FlatpakPermissions checks the order everywhere, and that a change to one neither moves the build to another directory nor links anything, and, where the host's flatpak runs, what build-finish makes of them and that it refuses a socket it does not have; FlatpakBundle that build-finish exports the desktop entry and the icon, and that the build's own files/ is left as it was; VariantId's test has the runtime, permissions and modules move no directory. The host's flatpak and flatpak-builder are reached only through HostCommand in :Platform, which builds the command lines of RunHostFlatpak, RunHostFlatpakBuilder and HostFlatpakUnavailable's probes: flatpak-spawn --host --watch-bus inside crafter-build's Flatpak, started in the host's / and passing FLATPAK_USER_DIR on, and the command itself natively. flatpak-spawn would otherwise start a command in crafter-build's own working directory, which the host need not have, and from /app, say, every host command would fail. HostFlatpakUnavailable says why the host cannot be reached: no org.freedesktop.Flatpak permission, no session bus (CI's build sandbox has neither), a host that does not see the project's bin/ and build/ where crafter-build does, as it does not in the sandbox's own /tmp, /var, /usr, /etc and /app or where a link leads into one, or no flatpak natively. That, and an executable that is not packaged as a Flatpak, install and bundle refuse as soon as the project is loaded, before anything is built; FlatpakVerbRefusal shows the second. The host is asked rather than the sandbox's paths modelled, which an override sharing a directory inside the sandbox's own would defeat: its flatpak is started in a directory just made in each of bin/ and build/ under a name no other has, which it enters only where it sees that very directory, and the directory is removed again. --help gets a section on both, and its Clean section says the repo an install points at goes with build/. FlatpakModules runs flatpak-builder only with a flatpak-builder program on the host, crafter-build falling back to the org.flatpak.Builder app, whose `flatpak run` would write ~/.var/app in the real home, and with the Platform and Sdk it builds the app with. The library's install function is InstallFlatpakApp because project.cpp files define an InstallFlatpak script of their own under `using namespace Crafter`, this repository's included, and a library InstallFlatpak would make the name an overload set, which the scripts table's std::function cannot be built from; BundleFlatpakApp is named to match. JsonQuote writes the manifest's strings, and variants.json's, which escaped quotes and backslashes only. FlatpakExport, FlatpakManifestText, ExportFlatpak and FlatpakPermission, which only :Clang uses, stay out of the API a project.cpp compiles against, as RecordFlatpakPlaced does, so their names cannot meet a project's own under `using namespace Crafter`; ExportFlatpak's comment names the app's lock, which its callers hold, beside HostFlatpakUnavailable.
2026-11-02 19:38:30 +01:00
// What it is installed as when it is packaged as a Flatpak, and the
// sandbox permissions any configuration may declare for the
// executables built on it.
feat: lay an executable out as the files/ of a Flatpak A Linux executable built by the Flatpak crafter-build links the libc++, libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs inside crafter-build's sandbox and practically nowhere else: a host needs glibc 2.38 or newer and all three LLVM libraries, which not even Arch has. A program built here is meant to run in a Flatpak, so it can now be laid out as one: with cfg.packaging = Packaging::Flatpak, or --packaging=flatpak where the project.cpp crafter-build was pointed at calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in the app's sandbox, and -r runs the program there against the libraries the app carries. The program is linked into files/bin, where its shaders, files and assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path, and the new :Flatpak partition writes the rest of files/: files/lib with the LLVM runtime libraries, located one by one through clang, and whatever else the program needs, read with llvm-readelf, that the directories of the shared libraries it is built on hold, the ones an unpackaged link records as run paths, or the toolchain's own lib dir, /app/lib in crafter-build's Flatpak, which the link searches too; and the desktop entry, metainfo and icons under the app-id in files/share, the entry refused when its Icon= is not the app-id or desktop-file-validate, where there is one, rejects it, and an icon that is not an .svg or a square .png. The metadata and export/ of a build directory are flatpak build-finish's to write, and crafter-build keeps no copy of its rules: what a permission means and what the host sees of an app change with flatpak's releases, and a copy would have to follow every one. The writer copies a file only when its content differs, compared a block at a time so that a large file costs no more memory than a small one, and writes one only when what it would write differs, never deciding by an mtime, which ostree sets to 0 for every file of /app, and works the program's libraries out on every write, which reads only their dynamic sections, since a library replaced in place, as by a toolchain update, can need others, which FlatpakLibraryChange checks; it prunes from files/bin each top-level entry an earlier build put there and this one does not, reporting those the program wrote there itself. What cannot be a Flatpak is refused before anything is built, saying why: a Windows or wasm executable, a build against a sysroot or for musl, another architecture than the runtime's, a build against CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and a build by a native crafter-build, which links the host's glibc: a native process knows no Flatpak runtime, from /.flatpak-info, unless CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one. Default stays the executable as linked for now, RunTests runs every test as linked, whatever its Configuration asks for, and RunLint works out its compile command so, and a forwarded --packaging= leaves a dependency's executables alone, since consumers run them by path. A dependency that packages its own executable gets its desktop file, metainfo and icons rebased by the loader as its cfg.files are, so they are its own whatever directory the consumer builds from. Only a Flatpak is keyed into VariantId, so every other configuration keeps its directory, but for one given --packaging=, which was a project arg, hashed into VariantId, and is a standard arg now, a dependency's included. The app-id and what a Flatpak is installed as are not keyed: they change files/share, never what is compiled. The asset name map, kept three times, twice in Build() and once for the browser runtime's files.json, is one function now, CompressedAssetName; CompressAsset, in Crafter.Build-Asset.cpp, keeps the list of the extensions it loads, which has to agree with it. Each copy a Flatpak build makes into the program's directory, of its shaders, assets, cfg.files and what its dependencies forward, records the top-level name it places there, the names of what a directory holds for one copied into it itself ("data/", "data/."), and those are what the writer keeps in files/bin; a build that fails after copying adds them to the writer's record all the same, so the next write removes what no build places any more. SharedLibraryRuns now also packages its program as a Flatpak, whose files/lib has to carry libgreet.so for it to start.
2026-11-01 19:20:55 +01:00
FlatpakApp flatpak;
2026-04-27 07:04:42 +02:00
std::vector<std::unique_ptr<Module>> interfaces;
std::vector<Implementation> implementations;
std::vector<fs::path> cFiles;
std::vector<fs::path> cuda;
feat(cuda): make the GPU architecture configurable, native by default nvcc ran with -arch=sm_89 for every build, which is code for that one architecture and its PTX, whatever GPU the program was for. Jorijn asked for the architecture to be configurable, and native when nothing sets it, as the CPU's is. cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc compiles for the GPUs it sees, and where it sees none it warns and uses its own default architecture. Like -march=native it is for a program that runs where it is built, since it carries no PTX, and `crafter-build bundle` warns of a bundle whose CUDA code, in the program or a library it is built on, is compiled for native, as it warns of -march=native. ApplyStandardArgs sets it from --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the parent's, as they give them its sysroot and debug flag; and ForceHostTooling gives host tooling the host's, as it gives it the host's march, since project.so runs it on the machine that loads it. A .cu is compiled again only when it is newer than its object, so the architecture keys VariantId, and so does the nvcc that compiles it, by what it is rather than where: Toolchain::nvccStamp, its canonical path, size and time, read without a process, changes when CUDA_PATH names another toolkit and when an update replaces the one at the same path, as a package does at /opt/cuda. native is keyed as well, by Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose and number them, each empty value apart from an unset one, read without a process. It is crafter-build's reading of the machine, not nvcc's. The word alone would keep an object compiled for a GPU the machine no longer has, after a GPU change or on another machine that shares the checkout, and that object carries no PTX for the GPU it has now, where sm_89's carried its PTX. Only a configuration with CUDA sources is keyed, so every other one keeps the directory it had, but for one built with --cuda-arch=, which was a project argument, hashed as one, and is crafter-build's own now.
2026-11-11 19:34:52 +01:00
// The GPU architecture nvcc compiles `cuda` for, as its -arch takes
// one. "native", the default, compiles for the GPUs of the machine
// that builds, as march's default does for its CPU; with none to be
// seen, nvcc warns and uses its own default. Like -march=native it is
// for a program that runs where it is built: it carries no PTX, which
// a newer GPU could compile when it loads the program. "sm_89" is one
// architecture with its PTX; "all-major" or "all" is for a program
// that runs elsewhere. ApplyStandardArgs sets it from
// CRAFTER_BUILD_CUDA_ARCH and --cuda-arch=.
std::string cudaArch = "native";
2026-04-27 07:04:42 +02:00
std::vector<Configuration*> dependencies;
std::vector<fs::path> files;
2026-05-02 21:08:51 +02:00
// Build-time-only source files this configuration exposes to its own
// and its consumers' shader compiles as glslang #include search
// paths. Each entry's parent directory (or the entry itself, if it's
// a directory) is added to the includer for every shader compiled in
// this configuration and in any configuration that transitively
// depends on it. Files are NOT copied — they're read in place from
// the dep's source tree, like C++ -I include dirs.
std::vector<fs::path> buildFiles;
2026-04-23 01:57:25 +02:00
std::vector<Define> defines;
std::vector<Shader> shaders;
2026-05-12 03:44:14 +02:00
// Source assets compressed via Crafter.Asset's SaveCompressed →
// .ctex/.cmesh in this configuration's bin dir.
//
// Each entry is either:
// - A single .png/.obj file. Output lands flat in the bin dir:
// bin/<filename>.ctex or bin/<filename>.cmesh.
// - A directory. The build recurses; .png/.obj are compressed
// with the relative tree mirrored under bin/<dirname>/, and
// every other file in the tree is copied through unchanged.
// Lets mod/map trees (mod.json + cannon/base.obj +
// cannon/color.png) keep their nested layout so JSON paths
// like "cannon/base.cmesh" resolve at runtime.
//
// Crafter.Asset must be reachable through cfg.dependencies (the
// build engine links its library API into crafter-build via a
// self-host pass). Forwarded to a consuming executable's bin dir
// alongside .spv shaders and cfg.files entries.
2026-05-12 01:16:40 +02:00
std::vector<fs::path> assets;
2026-04-27 07:04:42 +02:00
std::vector<ExternalDependency> externalDependencies;
std::vector<std::string> compileFlags;
std::vector<std::string> linkFlags;
feat: feature-detected browser-wasm variants (relaxed-SIMD) + variant-aware runtime The browser wasm pipeline hardcoded -msimd128 for every wasm32 target and baked a single wasm URL into index.html, so newer codegen features that aren't yet baseline across engines (relaxed SIMD today; threads, future SIMD revisions later) couldn't be adopted without dropping the browsers that lack them. Add a general, feature-parameterized mechanism owned entirely by Crafter.Build: - Configuration::wasmVariants declares N codegen variants (label, extra -m flags, runtime probes). Build() compiles the baseline plus one outputName.<label>.wasm per variant, recompiling the whole graph (incl. dep libs + std PCM) with the variant's flags — relaxed-SIMD is per-TU codegen, not a link switch. wasmVariantFlags folds into VariantId so each variant's objects/PCMs land in their own build+bin dir. - EnableWasiBrowserRuntime emits a variants.json manifest (label -> url + probes), preferred-first with the baseline as the universal fallback. - The shipped runtime.js runs inlined wasm-feature-detect probes (relaxed-simd, simd, tail-call, bulk-memory, exception-handling, threads), picks the first variant whose probes all pass, and falls back to the single baked CRAFTER_WASM_URL when no manifest is present (backward compatible). - EnableWasiRelaxedSimdVariant registers the relaxed-SIMD variant — the motivating case (Chrome 114+/Firefox 120+ enable it by default; Safari still flag-gates it as of mid-2026). Verified end to end: a wasm32-wasip1 build emits both wasi-hello.wasm and wasi-hello.relaxed-simd.wasm + variants.json; Firefox selects the relaxed-simd variant and runs it. Resolves #24 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 15:14:18 +00:00
// Browser-wasm feature-detected variants. Empty (the default) builds a
// single outputName.wasm with the baseline wasm flag set. Non-empty
// builds the baseline plus one outputName.<label>.wasm per entry, each
// recompiling the whole build graph with that entry's `flags`;
// EnableWasiBrowserRuntime emits a variants.json manifest the shipped
// runtime.js uses to pick the right variant per browser. Populate via
// EnableWasiRelaxedSimdVariant for the common case.
std::vector<WasmVariant> wasmVariants;
// Extra wasm codegen flags injected into this configuration's compile +
// link command for the active variant pass. Set across the whole build
// graph by the variant driver inside Build(); part of VariantId so each
// variant's objects/PCMs land in their own build+bin dir and never
// clobber the baseline's. Not for direct project use — declare
// wasmVariants instead.
std::vector<std::string> wasmVariantFlags;
fix: key the host PCM cache on source content, add clean, hash project args Three follow-ons to the stale-build report, all cases of an identity not capturing something that changes the output. The host PCM cache under <cache>/crafter.build/<target>-<march>/ is shared by every crafter-build on the machine, and freshness was a per-file mtime comparison. That cannot tell "this PCM is newer than my source" from "this PCM was built from different sources that happen to be newer", so a package install and a working checkout — or two checkouts of different versions — silently compiled their project.cpp against each other's declarations. Invalidation now keys on a stamp over the bytes of every module source, which also covers the case one file's mtime never could: the cached PCMs import each other, so a change to :Interface invalidates :Clang's PCM with Crafter.Build-Clang.cppm untouched. Project args ApplyStandardArgs does not itself interpret are now folded into VariantId. Such a flag typically decides what gets compiled or bundled — the report's example is --no-webgpu dropping entries from cfg.files — and without it both settings shared one bin dir and interleaved their outputs there, leaving a bundle matching neither. Sorted and deduplicated so flag order doesn't split the cache, and inherited by test Configurations. `crafter-build clean` removes the project's bin/ and build/ trees. It deliberately does not load project.cpp: cleaning is most often reached when something is already wrong, and a clean that first needs the project to compile is useless exactly then.
2026-07-30 17:43:09 +00:00
// The project args ApplyStandardArgs did not interpret — i.e. the
// project's own flags, whose effect on the build the framework cannot
// see. Hashed into VariantId because such a flag typically decides what
// gets compiled or bundled (`--no-webgpu` dropping entries from
// cfg.files, say), and without it both flag settings share one bin dir
// and interleave their outputs there. Populated by ApplyStandardArgs;
// the args it does recognise are excluded, since their effect already
// shows up in target/march/mtune/debug/sysroot/type. For the same
// reason this is not what to hand a sibling project: ProjectArgs() is
// every arg, the recognised ones included.
fix: key the host PCM cache on source content, add clean, hash project args Three follow-ons to the stale-build report, all cases of an identity not capturing something that changes the output. The host PCM cache under <cache>/crafter.build/<target>-<march>/ is shared by every crafter-build on the machine, and freshness was a per-file mtime comparison. That cannot tell "this PCM is newer than my source" from "this PCM was built from different sources that happen to be newer", so a package install and a working checkout — or two checkouts of different versions — silently compiled their project.cpp against each other's declarations. Invalidation now keys on a stamp over the bytes of every module source, which also covers the case one file's mtime never could: the cached PCMs import each other, so a change to :Interface invalidates :Clang's PCM with Crafter.Build-Clang.cppm untouched. Project args ApplyStandardArgs does not itself interpret are now folded into VariantId. Such a flag typically decides what gets compiled or bundled — the report's example is --no-webgpu dropping entries from cfg.files — and without it both settings shared one bin dir and interleaved their outputs there, leaving a bundle matching neither. Sorted and deduplicated so flag order doesn't split the cache, and inherited by test Configurations. `crafter-build clean` removes the project's bin/ and build/ trees. It deliberately does not load project.cpp: cleaning is most often reached when something is already wrong, and a clean that first needs the project to compile is useless exactly then.
2026-07-30 17:43:09 +00:00
std::vector<std::string> projectArgs;
std::vector<Test> tests;
2026-07-23 01:24:42 +02:00
// Lint rules for `crafter-build lint`. Populate via AddLintRule.
std::vector<LintRule> lintRules;
feat(script): scripts in project.cpp, run with `crafter-build run` A project.cpp could describe how a project is built, tested and linted, but not the chores around it: packaging, installing, publishing. Those stayed shell lines in a README or in someone's history. Configuration gains `scripts`, a plain list like `defines`. A Script is a name and a C++ callback, as a lint rule is; there is no script language and no config file. The callback gets a ScriptContext (the project, the project file's directory, the arguments) and returns the exit status. ctx.Run runs a shell command with the terminal attached and returns its status. It is only stored when project.cpp loads, which happens for every verb and for every project that depends on this one. `crafter-build run <name> [args...]` runs one, a bare `run` lists them. Only the scripts of the project crafter-build was pointed at are runnable, never a dependency's. Everything after the script's name is handed to the script untouched. The two branches that do this sit ahead of every other branch of the parse loop, --version and --help included. Below the verbs, `run package clean` would delete build/, and any other word would land in the project's args and so in the variant hash, moving the build to another directory. Options before the name keep their meaning, so project args go there. The driver is its own partition, :Script. It refuses a project with no scripts, a name that is empty or starts with '-' (it could never be typed), a name declared twice (running either would be a guess) and an unknown name, each with exit 1 and without running anything. A script that throws exits 1. A return value outside 0..255 becomes 1: an exit status is eight bits, and a raw wait status such as 256 would otherwise wrap to success. Two helpers in :Platform: - RunCommandAttached runs a command with inherited stdio. Every helper so far captured through popen, which is right for a compile step and useless for a command that runs for half an hour or asks a question. It reads the wait status through DecodeWaitStatus, which RunCommandChecked and RunCommandWithTimeout now share. - ShellQuote is exported. It existed twice, as ShellQuote in :External and ShellQuoteSh in :Test, with the same behaviour; both are gone. A script that puts a path into a command needs it too. Not included: a string shorthand for one-command scripts (a one-line lambda covers it) and a ctx.Build() helper (Build() is already exported). A new partition and new exported symbols: run ./build.sh. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-06 18:16:00 +02:00
// Scripts for `crafter-build run <name>`, a plain list like defines:
// cfg.scripts.push_back({"docs", [](ScriptContext& ctx) {
// return ctx.Run("python3 tools/gen-docs.py");
// }});
// Not part of VariantId: a script changes nothing that is compiled.
std::vector<Script> scripts;
feat(agents): keep dependencies' AGENTS.consumer.md in AGENTS.md An agent working on a crafter-build project reads its AGENTS.md, and learns nothing there about the libraries the project builds against unless someone copied that in by hand. This repository shows the cost: the code style section of its AGENTS.md restates what Crafter.LintRules enforces, and goes stale whenever the rules change. A library now ships those notes itself, as AGENTS.consumer.md beside its project.cpp; nothing in its project.cpp changes. When a consumer has an AGENTS.md beside its own project.cpp, `crafter-build` and `crafter-build test` keep a section in it, between two marker comments, holding its dependencies' notes. The section is appended the first time and rewritten in place after that. The file is written only when the section changes, and an AGENTS.md is never created. lint, format, run and clean leave it alone. The update runs after loading, which has just fetched every dependency, and before compiling, so a build that fails still has the notes. cfg.dependencyNotes picks the dependencies. Transitive, the default, follows `dependencies` all the way down from the project's own configurations, its tests and its `#pragma crafter dependency` tooling; Direct stops at the first loaded project on each path; None removes the section. A dependency's own pragma tooling never counts: it is about how that dependency is built, not how it is used, and being no `dependencies` edge it is never reached. Nor are a dependency's tests: nothing builds them for the consumer, and their configurations can point at a local their project file has since moved out of. The walk has to know which Configurations belong to another project, and where that project lives, and cfg.path cannot say: only the Configuration GitProject and LocalProject return is rebased, so a dependency's internal configurations keep "./", which resolves to the consumer. The loader records it instead, LoadedProjectOf beside the project cache, and keeps what the root's pragmas resolved to past the frame LoadProject pops, PragmaDependencies. Neither is exported. The markers count only as whole lines outside fenced code blocks, so documentation can quote them. Unbalanced markers and a document ending inside a code block leave the file alone with a warning: guessing which part of someone's file is generated would overwrite their text, and missing the section would add another one on every build. A note that would break the section when it is read back, through a marker line of its own or a code block it never closes, is left out with a warning. The file is replaced through a temporary renamed onto the symlink's target, so a linked AGENTS.md stays a link and a write cut short leaves the old file rather than part of the new one. The code is a new partition, Crafter.Build:Agents, listed in build.sh, CrafterBuildModules, project.cpp and the umbrella. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:18:06 +01:00
// Which dependencies' AGENTS.consumer.md `crafter-build` and
feat(agents): write AGENTS.md from a tracked AGENTS.template.md The dependency notes were kept in a section of the AGENTS.md beside project.cpp, the file a project commits, so a build could change a tracked file at any time: a dependency editing its AGENTS.consumer.md, an unpinned one moving on, a flag pulling a dependency in or out, each showed up in the consumer's diff as a change nobody made. Users reported it as the feature clobbering their diffs. A project now commits its instructions as AGENTS.template.md, and a build and a test run write AGENTS.md from it: a first line saying the file is generated and where to edit, the template's text as written, then the notes section, after it or where the template's marker lines put it. AGENTS.md is build output and goes into .gitignore. It is created when missing, since a fresh clone has none, and otherwise written as before: only when its text changes, in place and under a lock, so links, ownership and a read-only file are respected. The first line is also how a build tells its own AGENTS.md from one someone wrote. Beside a template the second is easily there, as a committed AGENTS.md nobody has removed yet; it is never replaced, and each build warns until it is deleted. An empty file counts as a build's, since that is what a write cut short leaves of a new one. An AGENTS.md linked to the template is refused: writing it would write the committed file again. A template the notes cannot be placed in leaves no empty AGENTS.md behind. The in-place mode is removed rather than kept as the fallback for a project without a template. It is the default that put generated text into tracked files unasked, the moment any dependency started shipping notes. Without a template a build no longer touches AGENTS.md. One that still holds a section from 3.0.0 would go stale silently, under a preamble promising that every build rewrites it, so it gets a warning naming the move instead. MergeDependencyNotes keeps its rules and now runs on the template. The test changes in this commit rather than its own, because it pinned the in-place behaviour this removes: it now covers the generated file's shape, edits and markers in the template, the ownership check, a CRLF template, a link to the template and the cases without one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:53:42 +01:00
// `crafter-build test` merge into the AGENTS.md they write from the
// AGENTS.template.md beside project.cpp, when there is one (see
// Crafter.Build:Agents):
feat(agents): keep dependencies' AGENTS.consumer.md in AGENTS.md An agent working on a crafter-build project reads its AGENTS.md, and learns nothing there about the libraries the project builds against unless someone copied that in by hand. This repository shows the cost: the code style section of its AGENTS.md restates what Crafter.LintRules enforces, and goes stale whenever the rules change. A library now ships those notes itself, as AGENTS.consumer.md beside its project.cpp; nothing in its project.cpp changes. When a consumer has an AGENTS.md beside its own project.cpp, `crafter-build` and `crafter-build test` keep a section in it, between two marker comments, holding its dependencies' notes. The section is appended the first time and rewritten in place after that. The file is written only when the section changes, and an AGENTS.md is never created. lint, format, run and clean leave it alone. The update runs after loading, which has just fetched every dependency, and before compiling, so a build that fails still has the notes. cfg.dependencyNotes picks the dependencies. Transitive, the default, follows `dependencies` all the way down from the project's own configurations, its tests and its `#pragma crafter dependency` tooling; Direct stops at the first loaded project on each path; None removes the section. A dependency's own pragma tooling never counts: it is about how that dependency is built, not how it is used, and being no `dependencies` edge it is never reached. Nor are a dependency's tests: nothing builds them for the consumer, and their configurations can point at a local their project file has since moved out of. The walk has to know which Configurations belong to another project, and where that project lives, and cfg.path cannot say: only the Configuration GitProject and LocalProject return is rebased, so a dependency's internal configurations keep "./", which resolves to the consumer. The loader records it instead, LoadedProjectOf beside the project cache, and keeps what the root's pragmas resolved to past the frame LoadProject pops, PragmaDependencies. Neither is exported. The markers count only as whole lines outside fenced code blocks, so documentation can quote them. Unbalanced markers and a document ending inside a code block leave the file alone with a warning: guessing which part of someone's file is generated would overwrite their text, and missing the section would add another one on every build. A note that would break the section when it is read back, through a marker line of its own or a code block it never closes, is left out with a warning. The file is replaced through a temporary renamed onto the symlink's target, so a linked AGENTS.md stays a link and a write cut short leaves the old file rather than part of the new one. The code is a new partition, Crafter.Build:Agents, listed in build.sh, CrafterBuildModules, project.cpp and the umbrella. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:18:06 +01:00
// cfg.dependencyNotes = DependencyNotes::Direct;
// Only read on the Configuration project.cpp returns; a dependency's
feat: let a project file return several configurations A project.cpp described one configuration: CrafterBuildProject returns a Configuration by value, and anything else the project wanted built had to be among that one's dependencies. There it was built as part of that configuration's graph: under the check that a graph builds each module once, with its libraries handed up to whatever links that configuration, and with its tests and scripts out of reach of `test` and `run`. Jorijn asked for a project.cpp that can return several unrelated configurations which all get built, and suggested a separate entry point, so that no existing project file breaks. A project file now defines one of two functions. CrafterBuildProject is as it was. CrafterBuildConfigurations returns std::vector<Configuration*>: pointers to configurations the file keeps alive itself, or that GitProject and LocalProject gave it. The two have different names because the loader finds the entry point by its C symbol, which carries no return type, so one name with two return types would be called as whichever the loader guessed. They are pointers because a project file takes pointers between its configurations, for `dependencies` and for a test's, before it returns them, and a vector of values would move them. LoadConfigurations loads a project file with either entry point and returns the list. A CrafterBuildProject's Configuration comes back as a list of one, constructed by the call where the loader keeps it for the rest of the process; LoadProjectFromRoot, which did that for a sibling's, leaves it to LoadConfigurations, and the project cache holds the lists without owning a Configuration. The Configuration of the project crafter-build is pointed at is kept that long as well, where it was a local of Run(). LoadConfigurations throws for a file that defines both functions or neither, and for a CrafterBuildConfigurations that returns nothing, a null pointer or one configuration twice. It also throws for one that returns a configuration a project loaded through GitProject or LocalProject keeps to itself, which the loader now takes down when it loads that project's file: what the configurations the file returned led to through `dependencies` or through their tests, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. Returned from here, such a configuration would count as this file's own to `test` and `run`, and only the configurations a project file returns are rebased onto its directory. LoadProject stays, for a caller that wants a CrafterBuildProject's Configuration by value, and throws for a file with the other entry point. GitProject and LocalProject keep, per spec and args, the list a sibling's file returned, and return the first one unless the spec's new `configuration` names another by Configuration::name. Every configuration of the list is rebased onto the sibling's directory, except one that another project's file had returned before, which was rebased onto that project's. Specs that differ only in the name they pick share one load. A name the sibling does not have throws, listing the names it has, and a name two of its configurations share throws too. A `#pragma crafter dependency` gets the first. BuildAll builds the returned configurations in one pass. Each is built by Build(), as a project's one configuration is, the first on the calling thread and each other one on a thread of its own, and its result then goes into the record of the pass under its PcmDir, where Build() looks for a dependency. One that another of them is built on is built before that other starts, which then finds it in the record: started beside it, the other would not find it there yet and would build it a second time. A configuration is not put into the record before it is built, because a dependency of its own that is built into the same directory would be handed its unfinished build and wait for it, while it waits for the dependency. All of them are built to the end, and the errors come back in the order given, each message once; an exception a build throws comes back as an error that names the configuration, where Run() printed the exception's own text for a project's one configuration. Refused before anything is built: two that would be built into one directory, which would be two builds writing the same files at once; several that are each built on something of another's directory, so that none could be built first; and one that is built on something of its own directory when another is built on that directory as well, since the record holds one result for a directory and the other could be given either. One shortcut is in it. A wasm executable that declares wasmVariants builds what it is built on once more per variant, and says which variant by rewriting those configurations in place, at the end of its Build(). A library that two returned configurations share would change under the one still building its baseline, so with such an executable anywhere in the graph BuildAll builds the configurations one after the other, on the calling thread. Keeping them side by side takes a variant driver that does not rewrite configurations other builds read, which this commit does not attempt. Run() works on the list. A build builds all of it. `test` runs the tests, and `run` offers the scripts, of the ones in it that the project file made itself. One that another project's file returned to GitProject or LocalProject, and that this file returns in turn, is built with the rest, but its tests and scripts stay that project's, so `run` still reaches only the scripts of the project crafter-build was pointed at. What the list itself rules out Run() refuses once the project file has loaded, before any of the list is built and before AGENTS.md is written: for a build, `-r`, `install` and `bundle` whatever BuildAll refuses a list for, and for `test`, which builds its tests with Build() and never comes to BuildAll, two returned configurations of one directory. BuildAll makes its refusals again for whoever calls it. A script is handed the configuration it is declared on. `lint` and `format` walk from every returned configuration and keep, as before, the configurations in the project's directory: the returned ones first, in the order the file returned them, then what they depend on, so that of two returned ones that register a rule under one name the earlier one's runs. `-r` runs the executable when exactly one of them is one, and `install` and `bundle` export the one that is packaged as a Flatpak; with more than one candidate each refuses and names them, `-r` once everything is built and `install` and `bundle` before anything is. AGENTS.md takes the notes that the dependencyNotes of each returned configuration the file made itself selects among what that one is built against, and the file's pragma tooling and a returned configuration of another project go by the widest of those settings. There, a configuration is another project's when GitProject or LocalProject loaded it from another project file than the one whose AGENTS.md is written, two files being one when they resolve to one path, so UpdateAgentsMd still reads the setting of a Configuration one of the two returned when it is given that Configuration's own project file. For that, RunTests, RunLint, RunScript and UpdateAgentsMd each gained an overload that takes the list, and the one that takes a single Configuration calls it with a list of one. SetParentProject gained one too, and ParentLib searches the graph of every configuration it was given. BuildAll, RunTests and RunScript count a configuration the list names twice once. The tests of several configurations share what one configuration's had to itself: AddTest names a test's sources, tests/<name>, and its build directory after the test and its compile state, not after the configuration that declares it. Two configurations that each declare a test of one name, compiled alike, would have RunTests build both in that one directory, each with the dependencies of its own declaration. RunTests fails both without building either, and each failure names the configurations. It compares tests of different configurations only, so a project of one configuration is treated as it was. The --help text names the second entry point, says what -r, install and bundle do with several configurations, and speaks of the project file's entry point as what gets the project args, where it named CrafterBuildProject. AGENTS.template.md says that a project.cpp returns one configuration or several, that Run() works on the list and what a new verb has to decide about it, which configurations have their path rebased, and that the scripts of a returned configuration of another project cannot be run. Two of its notes named LoadProject as what loads a project.cpp for crafter-build, which Run(), GitProject and LocalProject no longer call, and speak of the load now. Its rule for the link flags of a test that loads a project file names the ways a test loads one, where it named LoadProject, and its entry for `:Script` speaks of the `scripts` of the configurations the driver is given, where it named `cfg.scripts`. Its entry for `:Platform` names LoadConfigurations beside LoadProject. That entry also said that `:Platform` holds all OS-specific code, which it did not before this range either, :Agents, :Progress, :Lint and :Clang including POSIX headers of their own, and no longer says so. The bug-prover lens's section names BuildAll's threads and LoadConfigurations. Not in this commit: a way to say which executable -r runs or which app install and bundle export when there are several, and a keyword that lets a `#pragma crafter dependency` name a configuration.
2026-11-15 02:16:06 +01:00
// setting decides nothing for its consumers. Of several returned
// configurations, each one the project file made itself has its own
// read, for what that one is built against (see UpdateAgentsMd). Not
// part of VariantId: the notes change nothing that is compiled.
feat(agents): keep dependencies' AGENTS.consumer.md in AGENTS.md An agent working on a crafter-build project reads its AGENTS.md, and learns nothing there about the libraries the project builds against unless someone copied that in by hand. This repository shows the cost: the code style section of its AGENTS.md restates what Crafter.LintRules enforces, and goes stale whenever the rules change. A library now ships those notes itself, as AGENTS.consumer.md beside its project.cpp; nothing in its project.cpp changes. When a consumer has an AGENTS.md beside its own project.cpp, `crafter-build` and `crafter-build test` keep a section in it, between two marker comments, holding its dependencies' notes. The section is appended the first time and rewritten in place after that. The file is written only when the section changes, and an AGENTS.md is never created. lint, format, run and clean leave it alone. The update runs after loading, which has just fetched every dependency, and before compiling, so a build that fails still has the notes. cfg.dependencyNotes picks the dependencies. Transitive, the default, follows `dependencies` all the way down from the project's own configurations, its tests and its `#pragma crafter dependency` tooling; Direct stops at the first loaded project on each path; None removes the section. A dependency's own pragma tooling never counts: it is about how that dependency is built, not how it is used, and being no `dependencies` edge it is never reached. Nor are a dependency's tests: nothing builds them for the consumer, and their configurations can point at a local their project file has since moved out of. The walk has to know which Configurations belong to another project, and where that project lives, and cfg.path cannot say: only the Configuration GitProject and LocalProject return is rebased, so a dependency's internal configurations keep "./", which resolves to the consumer. The loader records it instead, LoadedProjectOf beside the project cache, and keeps what the root's pragmas resolved to past the frame LoadProject pops, PragmaDependencies. Neither is exported. The markers count only as whole lines outside fenced code blocks, so documentation can quote them. Unbalanced markers and a document ending inside a code block leave the file alone with a warning: guessing which part of someone's file is generated would overwrite their text, and missing the section would add another one on every build. A note that would break the section when it is read back, through a marker line of its own or a code block it never closes, is left out with a warning. The file is replaced through a temporary renamed onto the symlink's target, so a linked AGENTS.md stays a link and a write cut short leaves the old file rather than part of the new one. The code is a new partition, Crafter.Build:Agents, listed in build.sh, CrafterBuildModules, project.cpp and the umbrella. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:18:06 +01:00
DependencyNotes dependencyNotes = DependencyNotes::Transitive;
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void GetInterfacesAndImplementations(std::span<fs::path> interfaces, std::span<fs::path> implementations);
// Retry the `import X;` names GetInterfacesAndImplementations could not
// place, against the dependency DAG as it stands now. Sources are
// scanned when they're declared, but `dependencies` is often assigned
// afterwards (AddTest does exactly this), and an import that resolved to
// nothing leaves no staleness edge — so a dependency's interface could
// change and this Configuration's objects would be silently reused
// against the new layout. Build() calls this before checking mtimes;
// calling it again is harmless.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void ResolvePendingImports();
2026-05-27 19:45:05 +02:00
// Declare a test. Sources default to `tests/<name>/main.cpp` resolved
2026-07-22 18:25:39 +02:00
// against this Configuration's path; target/march/mtune/sysroot/debug
feat(cuda): make the GPU architecture configurable, native by default nvcc ran with -arch=sm_89 for every build, which is code for that one architecture and its PTX, whatever GPU the program was for. Jorijn asked for the architecture to be configurable, and native when nothing sets it, as the CPU's is. cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc compiles for the GPUs it sees, and where it sees none it warns and uses its own default architecture. Like -march=native it is for a program that runs where it is built, since it carries no PTX, and `crafter-build bundle` warns of a bundle whose CUDA code, in the program or a library it is built on, is compiled for native, as it warns of -march=native. ApplyStandardArgs sets it from --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the parent's, as they give them its sysroot and debug flag; and ForceHostTooling gives host tooling the host's, as it gives it the host's march, since project.so runs it on the machine that loads it. A .cu is compiled again only when it is newer than its object, so the architecture keys VariantId, and so does the nvcc that compiles it, by what it is rather than where: Toolchain::nvccStamp, its canonical path, size and time, read without a process, changes when CUDA_PATH names another toolkit and when an update replaces the one at the same path, as a package does at /opt/cuda. native is keyed as well, by Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose and number them, each empty value apart from an unset one, read without a process. It is crafter-build's reading of the machine, not nvcc's. The word alone would keep an object compiled for a GPU the machine no longer has, after a GPU change or on another machine that shares the checkout, and that object carries no PTX for the GPU it has now, where sm_89's carried its PTX. Only a configuration with CUDA sources is keyed, so every other one keeps the directory it had, but for one built with --cuda-arch=, which was a project argument, hashed as one, and is crafter-build's own now.
2026-11-11 19:34:52 +01:00
// and cudaArch are inherited from this Configuration so cross-arch
// projects don't have to re-specify. Returns a builder for chaining
// defines, deps, etc. Defined in Crafter.Build:Test.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
struct TestBuilder AddTest(std::string_view name);
2026-05-27 19:45:05 +02:00
// Same as AddTest, but compiles the parent's `interfaces` directly
// into this test's Configuration (rather than going through a dep).
// Use when the test must rebuild those interfaces with its own
// compile flags — typically per-march SIMD codegen.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
struct TestBuilder AddTest(std::string_view name, std::span<fs::path> interfaces);
2026-05-27 19:45:05 +02:00
// Math-style fan-out: one Test per MarchTier, all sharing the same
// `tests/<name>/main.cpp` source and the same interface set, each
// compiled with the tier's `-march`/`-mtune`. Test names are
// `<name>-<march>`.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void AddMarchVariants(std::string_view name, std::span<fs::path> interfaces, std::span<const struct MarchTier> tiers);
2026-07-23 01:24:42 +02:00
// Register a lint rule for `crafter-build lint` / `format`. Rules
// registered on any Configuration whose path lies inside the project
// root are collected (deduplicated by name, root-first) — attach them
// to the lib or the exe config, either works. Rules that call
// ctx.SetContent are transforms (see LintContext::SetContent).
// Defined in Crafter.Build:Lint.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void AddLintRule(std::string name, std::function<void(LintContext&)> check);
feat(lint): AST layer over libclang cursors Adds LintContext::Decls() — clang's view of the declarations written in the file — plus AddAstLintRule to register a rule that reads it. No rule uses it yet; the three that will are migrated separately. The declarations come back as a flat vector with parent indices rather than an opaque cursor handle: no lifetimes cross the project-DLL boundary, no callback hops back into project.so per node, and "is this at namespace scope or inside a function?" becomes an index lookup instead of a hand-rolled brace stack. Three things had to be solved for this to work at all on this codebase. libclang cannot see through `export`. A C++20 export declaration has no CXCursorKind, so `export namespace Crafter { … }` arrives as a childless CXCursor_UnexposedDecl and clang_visitChildren does not descend. Five of the eleven interfaces here are written that way — 677 lines, including Configuration and LintContext, yielding zero usable cursors. A plain `namespace` IS descended into, so the fix is to blank the keyword before parsing, byte-length preserving so every line and column still lands on the original file. `export module` is left alone or the unit stops being a module interface. Verified end-to-end against a fixture whose asserted line numbers match the unblanked file. PCMs are flag-locked, so each file has to parse with the flags that built it. CollectConfigSources now records which Configuration owns each source instead of flattening to a set, because three regimes coexist: the library, each test (carrying its own target, defines and -march), and project.cpp, which Build never touches and which therefore gets no command at all. libclang resolves its builtin headers relative to its own install path, which need not match the clang++ that wrote the PCMs. When it doesn't, every parse dies on "'stddef.h' file not found", so -resource-dir is passed explicitly from `clang++ -print-resource-dir`. Two flags on each declaration replace what would otherwise become more substring denylists: isExternC, and isForeignApi for a declaration that binds to an entity declared outside the project root — resolved through clang_getCursorReferenced and the same inside-the-root test the dependency walk already uses. Parameters and fields inherit it, so an exemption covers a whole signature rather than the one node that named the foreign entity. Failure is never silent. A fatal diagnostic leaves a fragment that is indistinguishable from a file declaring nothing, so it is reported as an error instead: the rule is skipped, a finding explains why, and summary.errors makes the run fail. --no-ast opts out deliberately and exits normally. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:30:41 +02:00
// Same, for a rule that reads LintContext::Decls(). Declared
// separately rather than as a flag on AddLintRule so existing
// registrations keep compiling. Such a rule makes the run build the
// module PCMs if they are missing, and a file whose AST could not be
// produced becomes an error instead of a silent pass. Prefer
// report-only: a transform running after the first one forces a
// re-parse of everything it changed.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void AddAstLintRule(std::string name, std::function<void(LintContext&)> check);
2026-04-30 02:20:19 +02:00
// Suffix that uniquely identifies this Configuration's compile state.
// target+march+mtune are spelled out for readability; the rest
// (type, debug, sysroot, defines, compileFlags, the std module, the
feat(cuda): make the GPU architecture configurable, native by default nvcc ran with -arch=sm_89 for every build, which is code for that one architecture and its PTX, whatever GPU the program was for. Jorijn asked for the architecture to be configurable, and native when nothing sets it, as the CPU's is. cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc compiles for the GPUs it sees, and where it sees none it warns and uses its own default architecture. Like -march=native it is for a program that runs where it is built, since it carries no PTX, and `crafter-build bundle` warns of a bundle whose CUDA code, in the program or a library it is built on, is compiled for native, as it warns of -march=native. ApplyStandardArgs sets it from --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the parent's, as they give them its sysroot and debug flag; and ForceHostTooling gives host tooling the host's, as it gives it the host's march, since project.so runs it on the machine that loads it. A .cu is compiled again only when it is newer than its object, so the architecture keys VariantId, and so does the nvcc that compiles it, by what it is rather than where: Toolchain::nvccStamp, its canonical path, size and time, read without a process, changes when CUDA_PATH names another toolkit and when an update replaces the one at the same path, as a package does at /opt/cuda. native is keyed as well, by Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose and number them, each empty value apart from an unset one, read without a process. It is crafter-build's reading of the machine, not nvcc's. The word alone would keep an object compiled for a GPU the machine no longer has, after a GPU change or on another machine that shares the checkout, and that object carries no PTX for the GPU it has now, where sm_89's carried its PTX. Only a configuration with CUDA sources is keyed, so every other one keeps the directory it had, but for one built with --cuda-arch=, which was a project argument, hashed as one, and is crafter-build's own now.
2026-11-11 19:34:52 +01:00
// toolchain, the GPU architecture and the nvcc of CUDA sources)
fix(incremental): key build outputs on the compiler A project built with one clang kept its outputs when crafter-build started using another. The output directory is named by VariantId(), which hashed every input that changes what is compiled except the compiler itself, and staleness is decided by mtimes, which a compiler update leaves alone. A PCM can only be read by the clang release that wrote it, so after the bundled LLVM moved from 22 to 23 the first build found nothing stale, and the first edit failed with "module file Greeter.pcm uses an older format that is no longer supported" until the project was cleaned by hand. A project with a `#pragma crafter dependency` did not get that far: its project file imports the dependency's PCM, so it failed to load, and for a git dependency that PCM lives in the cache, where `crafter-build clean` does not reach. The same happens natively when the distro updates clang. The toolchain's key now goes into the hash, as the host PCM cache was already keyed on it. An update starts an empty variant directory and rebuilds into it; the previous one stays until `clean`, as after any other change of variant, and two crafter-build versions can work in one checkout without disturbing each other. VariantId() gains an overload taking the toolchain so the dependence can be tested in-process, the way ResolveToolchain and SysrootStdModule take theirs. External cmake builds are not covered: their directory is fixed per clone and keyed on the compiler's path, not its release. Objects of two clang releases link together on the host, so nothing fails there, but they are not rebuilt either. Verified by replaying the update: three projects built with the 2.0.0 Flatpak, then built, edited and run with this one without cleaning, then built with 2.0.0 again. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 20:09:22 +02:00
// collapse into a short hash so two Configurations sharing a path but
// with different compile state can't clobber each other's outputs.
std::string VariantId() const { return VariantId(GetToolchain()); }
// The variant under an explicit toolchain; VariantId() is this for
// the running one. The compiler is compile state like any flag: a
// PCM can only be read by the clang release that wrote it, and
// staleness is decided by mtimes, which a compiler update does not
// touch. Before the toolchain was hashed, a project built with clang
// 22 kept its PCMs when crafter-build moved to clang 23, and the
// first edit afterwards failed with "module file ... uses an older
// format that is no longer supported" until the project was cleaned.
// Keyed here, an update starts an empty directory and rebuilds; the
// old one stays until `crafter-build clean`.
std::string VariantId(const Toolchain& toolchain) const {
2026-04-30 02:20:19 +02:00
std::string compileKey;
2026-07-23 01:24:42 +02:00
compileKey += std::to_string(static_cast<std::int32_t>(type));
2026-04-30 02:20:19 +02:00
compileKey += '|';
compileKey += debug ? '1' : '0';
compileKey += '|';
fix(wasm): resolve the WASI sysroot where it is read, not in Build() A wasm32 configuration that names no sysroot is built against the toolchain's WASI sysroot. ApplyStandardArgs stores that sysroot in cfg.sysroot, for a project file that calls it. For a configuration whose project file sets the target itself, Build() stored it on its way in. VariantId hashes the sysroot, so such a configuration had one BuildDir, BinDir and PcmDir until its build started and others from then on. A build pass records each dependency's build under its PcmDir, and a configuration asks for a dependency by the PcmDir it has at that moment. A wasm32 library that two configurations of one pass are built on was recorded under the first directory for the one that asked first. One that asked after the library's build had started asked under the second directory, found nothing there, and built the library again. Configuration::ResolvedSysroot now gives what cfg.sysroot comes to: the toolchain's WASI sysroot for a wasm32 configuration that names none, cfg.sysroot as it stands for every other, as ResolvedPackaging gives what `packaging` comes to. VariantId, the std module's flags, key and source, the compile and link commands and the check that refuses a wasm build without a usable sysroot read it, and Build() no longer stores the sysroot in the configuration. ApplyStandardArgs still does: what a project file reads in cfg.sysroot after the call stays what it was. The directories a build writes keep their names: a configuration that named no sysroot was built into the ones its VariantId named once Build() had stored it, which are the ones it names now. StdPcmFlags takes the toolchain, as StdPcmKey does, so that a VariantId asked for under a toolchain resolves the sysroot under that one.
2026-11-14 23:42:47 +01:00
compileKey += ResolvedSysroot(toolchain);
2026-04-30 02:20:19 +02:00
for (const Define& d : defines) {
compileKey += "|D:";
compileKey += d.name;
compileKey += '=';
compileKey += d.value;
}
for (const std::string& f : compileFlags) {
compileKey += "|F:";
compileKey += f;
}
feat: feature-detected browser-wasm variants (relaxed-SIMD) + variant-aware runtime The browser wasm pipeline hardcoded -msimd128 for every wasm32 target and baked a single wasm URL into index.html, so newer codegen features that aren't yet baseline across engines (relaxed SIMD today; threads, future SIMD revisions later) couldn't be adopted without dropping the browsers that lack them. Add a general, feature-parameterized mechanism owned entirely by Crafter.Build: - Configuration::wasmVariants declares N codegen variants (label, extra -m flags, runtime probes). Build() compiles the baseline plus one outputName.<label>.wasm per variant, recompiling the whole graph (incl. dep libs + std PCM) with the variant's flags — relaxed-SIMD is per-TU codegen, not a link switch. wasmVariantFlags folds into VariantId so each variant's objects/PCMs land in their own build+bin dir. - EnableWasiBrowserRuntime emits a variants.json manifest (label -> url + probes), preferred-first with the baseline as the universal fallback. - The shipped runtime.js runs inlined wasm-feature-detect probes (relaxed-simd, simd, tail-call, bulk-memory, exception-handling, threads), picks the first variant whose probes all pass, and falls back to the single baked CRAFTER_WASM_URL when no manifest is present (backward compatible). - EnableWasiRelaxedSimdVariant registers the relaxed-SIMD variant — the motivating case (Chrome 114+/Firefox 120+ enable it by default; Safari still flag-gates it as of mid-2026). Verified end to end: a wasm32-wasip1 build emits both wasi-hello.wasm and wasi-hello.relaxed-simd.wasm + variants.json; Firefox selects the relaxed-simd variant and runs it. Resolves #24 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 15:14:18 +00:00
// Wasm variant codegen flags perturb every object/PCM, so they must
// key into a distinct build+bin dir from the baseline (and from
// each other) to avoid clobbering.
for (const std::string& f : wasmVariantFlags) {
compileKey += "|W:";
compileKey += f;
}
feat(wasm): compile C++ with WebAssembly exception handling wasm builds were compiled with -fno-exceptions. A throw did not compile, libc++'s own throws (vector::at, std::format, filesystem) aborted the program, and code that relies on exceptions could not be built for the browser at all. Every wasm unit and the std module now get -fwasm-exceptions, and the link adds -lunwind, which code built that way calls into and the driver does not add. The flag also selects the libc++ under the sysroot's lib/<triple>/eh, which wasi-sdk 33 and later ship next to the noeh one. Those libraries use the standardized encoding (try_table, exnref) while LLVM 23 still emits the legacy one by default, which wasmtime refuses to load and which would put both in one binary, so the flags ask for the standard form with -wasm-use-legacy-eh=false. That makes the setjmp lowering loadable under wasmtime too. The flags live in one constant, WasmBaselineFlags, which the compile command and the std module both take through WasmCompileFlags: a BMI is refused by a unit whose exception setting differs from its own. VariantId and StdPcmDir hash it, so the first build after the update starts fresh instead of importing PCMs built without exceptions, and two releases sharing the Flatpak's cache don't take turns rebuilding one std PCM. A sysroot without the exception-enabled libraries stops the build with a line saying so, rather than at the link with "unable to find library -lunwind". The result needs an engine with exnref: Chrome 137, Firefox 131, Safari 18.4, the bundled wasmtime. The runtime's exception-handling probe tested the legacy encoding; it now tests try_table, every variants.json entry carries it, and a browser without it is told which feature it lacks instead of failing with a CompileError. There is no switch back to -fno-exceptions: engines without exnref are old enough not to keep a second build for them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:54:39 +01:00
// So does the set every wasm unit gets before those. Unkeyed, the
// release that turned exceptions on would have kept the objects
// and PCMs compiled without them: the first unit recompiled after
// the update would import BMIs built without exceptions, which
// clang rejects, and objects nothing recompiled would let
// exceptions pass through without running their destructors.
if (target.starts_with("wasm32")) {
compileKey += "|B:";
compileKey += WasmBaselineFlags;
}
// The std module the units import. Its PCMs and objects record
// it by path, and units do not notice it moving: when the mingw
// prefix stopped being clang's sysroot as is (issue #43), the
// std module was rebuilt and the objects compiled against the
// host's glibc headers were only relinked, failing as before. A
// std module that moves directories, because anything it is
// compiled with changed, moves the build with it.
compileKey += "|S:";
compileKey += StdPcmKey(*this, toolchain);
fix: key the host PCM cache on source content, add clean, hash project args Three follow-ons to the stale-build report, all cases of an identity not capturing something that changes the output. The host PCM cache under <cache>/crafter.build/<target>-<march>/ is shared by every crafter-build on the machine, and freshness was a per-file mtime comparison. That cannot tell "this PCM is newer than my source" from "this PCM was built from different sources that happen to be newer", so a package install and a working checkout — or two checkouts of different versions — silently compiled their project.cpp against each other's declarations. Invalidation now keys on a stamp over the bytes of every module source, which also covers the case one file's mtime never could: the cached PCMs import each other, so a change to :Interface invalidates :Clang's PCM with Crafter.Build-Clang.cppm untouched. Project args ApplyStandardArgs does not itself interpret are now folded into VariantId. Such a flag typically decides what gets compiled or bundled — the report's example is --no-webgpu dropping entries from cfg.files — and without it both settings shared one bin dir and interleaved their outputs there, leaving a bundle matching neither. Sorted and deduplicated so flag order doesn't split the cache, and inherited by test Configurations. `crafter-build clean` removes the project's bin/ and build/ trees. It deliberately does not load project.cpp: cleaning is most often reached when something is already wrong, and a clean that first needs the project to compile is useless exactly then.
2026-07-30 17:43:09 +00:00
// Sorted by ApplyStandardArgs, so flag order on the command line
// doesn't split the cache.
for (const std::string& a : projectArgs) {
compileKey += "|A:";
compileKey += a;
}
fix(incremental): key build outputs on the compiler A project built with one clang kept its outputs when crafter-build started using another. The output directory is named by VariantId(), which hashed every input that changes what is compiled except the compiler itself, and staleness is decided by mtimes, which a compiler update leaves alone. A PCM can only be read by the clang release that wrote it, so after the bundled LLVM moved from 22 to 23 the first build found nothing stale, and the first edit failed with "module file Greeter.pcm uses an older format that is no longer supported" until the project was cleaned by hand. A project with a `#pragma crafter dependency` did not get that far: its project file imports the dependency's PCM, so it failed to load, and for a git dependency that PCM lives in the cache, where `crafter-build clean` does not reach. The same happens natively when the distro updates clang. The toolchain's key now goes into the hash, as the host PCM cache was already keyed on it. An update starts an empty variant directory and rebuilds into it; the previous one stays until `clean`, as after any other change of variant, and two crafter-build versions can work in one checkout without disturbing each other. VariantId() gains an overload taking the toolchain so the dependence can be tested in-process, the way ResolveToolchain and SysrootStdModule take theirs. External cmake builds are not covered: their directory is fixed per clone and keyed on the compiler's path, not its release. Objects of two clang releases link together on the host, so nothing fails there, but they are not rebuilt either. Verified by replaying the update: three projects built with the 2.0.0 Flatpak, then built, edited and run with this one without cleaning, then built with 2.0.0 again. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-03 20:09:22 +02:00
compileKey += "|T:";
compileKey += toolchain.Key();
feat(cuda): make the GPU architecture configurable, native by default nvcc ran with -arch=sm_89 for every build, which is code for that one architecture and its PTX, whatever GPU the program was for. Jorijn asked for the architecture to be configurable, and native when nothing sets it, as the CPU's is. cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc compiles for the GPUs it sees, and where it sees none it warns and uses its own default architecture. Like -march=native it is for a program that runs where it is built, since it carries no PTX, and `crafter-build bundle` warns of a bundle whose CUDA code, in the program or a library it is built on, is compiled for native, as it warns of -march=native. ApplyStandardArgs sets it from --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the parent's, as they give them its sysroot and debug flag; and ForceHostTooling gives host tooling the host's, as it gives it the host's march, since project.so runs it on the machine that loads it. A .cu is compiled again only when it is newer than its object, so the architecture keys VariantId, and so does the nvcc that compiles it, by what it is rather than where: Toolchain::nvccStamp, its canonical path, size and time, read without a process, changes when CUDA_PATH names another toolkit and when an update replaces the one at the same path, as a package does at /opt/cuda. native is keyed as well, by Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose and number them, each empty value apart from an unset one, read without a process. It is crafter-build's reading of the machine, not nvcc's. The word alone would keep an object compiled for a GPU the machine no longer has, after a GPU change or on another machine that shares the checkout, and that object carries no PTX for the GPU it has now, where sm_89's carried its PTX. Only a configuration with CUDA sources is keyed, so every other one keeps the directory it had, but for one built with --cuda-arch=, which was a project argument, hashed as one, and is crafter-build's own now.
2026-11-11 19:34:52 +01:00
// The GPU architecture decides what a .cu compiles into, and so
// does the toolkit whose nvcc compiles it, which CUDA_PATH can
// switch and an update can replace at the same path, so the nvcc
// is keyed by what it is (Toolchain::nvccStamp), and native by the
// GPUs it resolves to (Toolchain::cudaNativeKey). None of them
// need touch the files whose times decide whether a .cu is
// compiled again, so each needs a directory of its own. Only keyed
// with CUDA sources, so every other configuration keeps the
// directory it had.
if (!cuda.empty()) {
compileKey += "|C:";
compileKey += cudaArch;
compileKey += '|';
compileKey += toolchain.nvccStamp;
if (cudaArch == "native") {
compileKey += '|';
compileKey += toolchain.cudaNativeKey;
}
}
feat: lay an executable out as the files/ of a Flatpak A Linux executable built by the Flatpak crafter-build links the libc++, libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs inside crafter-build's sandbox and practically nowhere else: a host needs glibc 2.38 or newer and all three LLVM libraries, which not even Arch has. A program built here is meant to run in a Flatpak, so it can now be laid out as one: with cfg.packaging = Packaging::Flatpak, or --packaging=flatpak where the project.cpp crafter-build was pointed at calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in the app's sandbox, and -r runs the program there against the libraries the app carries. The program is linked into files/bin, where its shaders, files and assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path, and the new :Flatpak partition writes the rest of files/: files/lib with the LLVM runtime libraries, located one by one through clang, and whatever else the program needs, read with llvm-readelf, that the directories of the shared libraries it is built on hold, the ones an unpackaged link records as run paths, or the toolchain's own lib dir, /app/lib in crafter-build's Flatpak, which the link searches too; and the desktop entry, metainfo and icons under the app-id in files/share, the entry refused when its Icon= is not the app-id or desktop-file-validate, where there is one, rejects it, and an icon that is not an .svg or a square .png. The metadata and export/ of a build directory are flatpak build-finish's to write, and crafter-build keeps no copy of its rules: what a permission means and what the host sees of an app change with flatpak's releases, and a copy would have to follow every one. The writer copies a file only when its content differs, compared a block at a time so that a large file costs no more memory than a small one, and writes one only when what it would write differs, never deciding by an mtime, which ostree sets to 0 for every file of /app, and works the program's libraries out on every write, which reads only their dynamic sections, since a library replaced in place, as by a toolchain update, can need others, which FlatpakLibraryChange checks; it prunes from files/bin each top-level entry an earlier build put there and this one does not, reporting those the program wrote there itself. What cannot be a Flatpak is refused before anything is built, saying why: a Windows or wasm executable, a build against a sysroot or for musl, another architecture than the runtime's, a build against CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and a build by a native crafter-build, which links the host's glibc: a native process knows no Flatpak runtime, from /.flatpak-info, unless CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one. Default stays the executable as linked for now, RunTests runs every test as linked, whatever its Configuration asks for, and RunLint works out its compile command so, and a forwarded --packaging= leaves a dependency's executables alone, since consumers run them by path. A dependency that packages its own executable gets its desktop file, metainfo and icons rebased by the loader as its cfg.files are, so they are its own whatever directory the consumer builds from. Only a Flatpak is keyed into VariantId, so every other configuration keeps its directory, but for one given --packaging=, which was a project arg, hashed into VariantId, and is a standard arg now, a dependency's included. The app-id and what a Flatpak is installed as are not keyed: they change files/share, never what is compiled. The asset name map, kept three times, twice in Build() and once for the browser runtime's files.json, is one function now, CompressedAssetName; CompressAsset, in Crafter.Build-Asset.cpp, keeps the list of the extensions it loads, which has to agree with it. Each copy a Flatpak build makes into the program's directory, of its shaders, assets, cfg.files and what its dependencies forward, records the top-level name it places there, the names of what a directory holds for one copied into it itself ("data/", "data/."), and those are what the writer keeps in files/bin; a build that fails after copying adds them to the writer's record all the same, so the next write removes what no build places any more. SharedLibraryRuns now also packages its program as a Flatpak, whose files/lib has to carry libgreet.so for it to start.
2026-11-01 19:20:55 +01:00
// A Flatpak lays its bin dir out unlike the executable as linked,
// so the two never share one. Only keyed for a Flatpak, so every
// other configuration keeps the directory it had.
if (ResolvedPackaging() == Packaging::Flatpak) compileKey += "|P:flatpak";
2026-04-30 02:20:19 +02:00
std::size_t configHash = std::hash<std::string>{}(compileKey);
return std::format("{}-{}-{}-{}-{:08x}", name, target, march, mtune, configHash);
}
fs::path BuildDir() const { return path / "build" / VariantId(); }
fs::path BinDir() const { return path / "bin" / VariantId(); }
// Where an executable and the files it reads at run time land, and
// the directory `-r` runs a host executable in and serves a browser
// build from: its shaders, cfg.files and assets, and those its
feat: lay an executable out as the files/ of a Flatpak A Linux executable built by the Flatpak crafter-build links the libc++, libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs inside crafter-build's sandbox and practically nowhere else: a host needs glibc 2.38 or newer and all three LLVM libraries, which not even Arch has. A program built here is meant to run in a Flatpak, so it can now be laid out as one: with cfg.packaging = Packaging::Flatpak, or --packaging=flatpak where the project.cpp crafter-build was pointed at calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in the app's sandbox, and -r runs the program there against the libraries the app carries. The program is linked into files/bin, where its shaders, files and assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path, and the new :Flatpak partition writes the rest of files/: files/lib with the LLVM runtime libraries, located one by one through clang, and whatever else the program needs, read with llvm-readelf, that the directories of the shared libraries it is built on hold, the ones an unpackaged link records as run paths, or the toolchain's own lib dir, /app/lib in crafter-build's Flatpak, which the link searches too; and the desktop entry, metainfo and icons under the app-id in files/share, the entry refused when its Icon= is not the app-id or desktop-file-validate, where there is one, rejects it, and an icon that is not an .svg or a square .png. The metadata and export/ of a build directory are flatpak build-finish's to write, and crafter-build keeps no copy of its rules: what a permission means and what the host sees of an app change with flatpak's releases, and a copy would have to follow every one. The writer copies a file only when its content differs, compared a block at a time so that a large file costs no more memory than a small one, and writes one only when what it would write differs, never deciding by an mtime, which ostree sets to 0 for every file of /app, and works the program's libraries out on every write, which reads only their dynamic sections, since a library replaced in place, as by a toolchain update, can need others, which FlatpakLibraryChange checks; it prunes from files/bin each top-level entry an earlier build put there and this one does not, reporting those the program wrote there itself. What cannot be a Flatpak is refused before anything is built, saying why: a Windows or wasm executable, a build against a sysroot or for musl, another architecture than the runtime's, a build against CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and a build by a native crafter-build, which links the host's glibc: a native process knows no Flatpak runtime, from /.flatpak-info, unless CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one. Default stays the executable as linked for now, RunTests runs every test as linked, whatever its Configuration asks for, and RunLint works out its compile command so, and a forwarded --packaging= leaves a dependency's executables alone, since consumers run them by path. A dependency that packages its own executable gets its desktop file, metainfo and icons rebased by the loader as its cfg.files are, so they are its own whatever directory the consumer builds from. Only a Flatpak is keyed into VariantId, so every other configuration keeps its directory, but for one given --packaging=, which was a project arg, hashed into VariantId, and is a standard arg now, a dependency's included. The app-id and what a Flatpak is installed as are not keyed: they change files/share, never what is compiled. The asset name map, kept three times, twice in Build() and once for the browser runtime's files.json, is one function now, CompressedAssetName; CompressAsset, in Crafter.Build-Asset.cpp, keeps the list of the extensions it loads, which has to agree with it. Each copy a Flatpak build makes into the program's directory, of its shaders, assets, cfg.files and what its dependencies forward, records the top-level name it places there, the names of what a directory holds for one copied into it itself ("data/", "data/."), and those are what the writer keeps in files/bin; a build that fails after copying adds them to the writer's record all the same, so the next write removes what no build places any more. SharedLibraryRuns now also packages its program as a Flatpak, whose files/lib has to carry libgreet.so for it to start.
2026-11-01 19:20:55 +01:00
// dependencies forward to it. A Flatpak keeps them in files/bin of
// its bin dir, which becomes /app/bin; every other configuration in
// its bin dir.
fs::path ProgramDir() const { return ResolvedPackaging() == Packaging::Flatpak ? BinDir() / "files" / "bin" : BinDir(); }
// What `packaging` comes to for this configuration: Flatpak for an
// executable that asks for one by name, None for every other
// configuration and for Default.
Packaging ResolvedPackaging() const {
return type == ConfigurationType::Executable && packaging == Packaging::Flatpak ? Packaging::Flatpak : Packaging::None;
}
fix(wasm): resolve the WASI sysroot where it is read, not in Build() A wasm32 configuration that names no sysroot is built against the toolchain's WASI sysroot. ApplyStandardArgs stores that sysroot in cfg.sysroot, for a project file that calls it. For a configuration whose project file sets the target itself, Build() stored it on its way in. VariantId hashes the sysroot, so such a configuration had one BuildDir, BinDir and PcmDir until its build started and others from then on. A build pass records each dependency's build under its PcmDir, and a configuration asks for a dependency by the PcmDir it has at that moment. A wasm32 library that two configurations of one pass are built on was recorded under the first directory for the one that asked first. One that asked after the library's build had started asked under the second directory, found nothing there, and built the library again. Configuration::ResolvedSysroot now gives what cfg.sysroot comes to: the toolchain's WASI sysroot for a wasm32 configuration that names none, cfg.sysroot as it stands for every other, as ResolvedPackaging gives what `packaging` comes to. VariantId, the std module's flags, key and source, the compile and link commands and the check that refuses a wasm build without a usable sysroot read it, and Build() no longer stores the sysroot in the configuration. ApplyStandardArgs still does: what a project file reads in cfg.sysroot after the call stays what it was. The directories a build writes keep their names: a configuration that named no sysroot was built into the ones its VariantId named once Build() had stored it, which are the ones it names now. StdPcmFlags takes the toolchain, as StdPcmKey does, so that a VariantId asked for under a toolchain resolves the sysroot under that one.
2026-11-14 23:42:47 +01:00
// What `sysroot` comes to for this configuration under `toolchain`:
// the toolchain's WASI sysroot for a wasm32 target that names none,
// `sysroot` as it stands for every other configuration. The
// commands that compile and link a wasm32 configuration and the
// names of its directories read the sysroot through here, so the
// configuration is the same thing before its build as during it and
// after. Build() used to store the WASI sysroot in `sysroot` on its
// way in instead, and VariantId hashes the sysroot: a wasm32
// configuration whose target was set without ApplyStandardArgs,
// which stores it when the project file is loaded, had one
// BuildDir, BinDir and PcmDir until its build started and others
// from then on. A build pass records a dependency's build under its
// PcmDir, so one that two configurations of the pass were built on
// was looked up under the first directory by the one that asked
// before its build had started and under the second by the one
// that asked after, and was built a second time.
std::string ResolvedSysroot(const Toolchain& toolchain) const {
return sysroot.empty() && target.starts_with("wasm32") ? toolchain.wasiSysroot.string() : sysroot;
}
2026-04-27 07:04:42 +02:00
fs::path PcmDir() const {
2026-04-30 02:20:19 +02:00
return type == ConfigurationType::Executable ? BuildDir() : BinDir();
2026-04-27 07:04:42 +02:00
}
};
struct Test {
Configuration config;
TestRunner runner;
std::chrono::seconds timeout{60};
std::vector<std::string> args;
test: introduce test.toml + target-derived runners alongside existing machinery Vendors toml++ v3.4.0 as lib/toml.hpp and wires it into Crafter.Build-Test to parse a declarative test.toml manifest (target/march/mtune/sysroot/ requires/timeout/args/defines). Test discovery now treats project.cpp and test.toml as mutually exclusive: project.cpp stays the escape hatch for outer-driver tests, test.toml gives downstream test authors a no-boilerplate path. Adds: - TestRunner::Wine() and TestRunner::ForTarget(cfg) — runner is now derived from cfg.target (Local for host, Wine for Windows-on-Linux, wasmtime for WASI, qemu-<arch> with QEMU_LD_PREFIX for non-host Linux). The env-var override CRAFTER_BUILD_RUNNER_<target> still wins as a power-user escape hatch via FromEnv. - Declarative preconditions: tool:<name>, file:<path>, env:<VAR> are evaluated before the build; missing preconditions Skip without paying the compile cost. - Hard-fail-unless-declared: when a derived runner's tool is missing AND the test didn't declare 'tool:<that>' in requires, the missing runner is a Fail instead of a silent Skip. Surfaces broken cross-arch CI config that previously hid as "skipped". - Multi-target sweep: bare `crafter-build test` (no --target=) now iterates every distinct test.toml-declared target plus the host, so cross-arch tests run by default without the user needing to know which targets exist. `--target=X` bypasses the sweep. Test struct gains a `requires_` vector so project.cpp users can declare preconditions too (matching what test.toml writes there). Existing tests, factories (Ssh/SshWin/Wsl/Cmd), and CRAFTER_BUILD_RUNNER_* machinery remain intact — this commit only adds; migration and deletion follow in subsequent commits. Refs issue #8. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 17:47:39 +02:00
// Declarative preconditions. Each entry is "tool:<name>",
// "file:<path>", or "env:<VAR>". Evaluated before the test runs; any
// unmet require turns the test into a Skip with a derived reason.
// Also doubles as the "I know this runner might not be here" opt-in:
// when the test's derived runner needs a tool (e.g. qemu-aarch64,
// wasmtime, wine) and the matching tool: entry isn't present, an
// unavailable runner becomes a Fail instead of a silent Skip — the
// dependency has to be declared to be allowed to be missing.
std::vector<std::string> requires_;
};
// Directory holding the std module PCM for this Configuration,
// GetCacheDir() / StdPcmKey(config, GetToolchain()): a BMI is only
// loadable by a unit compiled the way it was.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
fs::path StdPcmDir(const Configuration& config);
refactor: extract GetCompileCommand and StdPcmDir out of Build The clang invocation was assembled inline across four regions of Build, interleaved with the dependency-graph walk, so nothing else could ask "what flags does this Configuration compile with". The linter's AST layer needs exactly that, and it cannot approximate it: a precompiled module is rejected outright by a translation unit whose target features differ from the one that wrote it. Dropping just -march=native produces hundreds of "compiled with the target feature '+avx512bw' but the current translation unit is not" errors and no usable parse, so reconstructed flags fail hard rather than degrade. GetCompileCommand is the config-pure part: target, arch, standard, configuration defines, module search paths, includes, user compileFlags, optimisation and LTO. Build appends only what depends on work having happened — dependency public flags and external dependency flags. The sub-strings it also needs on their own (includes, defines, user flags, LTO) come back as struct members, so the .c compile path is unchanged. Verified by probing `command` at the equivalent point before and after and diffing: byte-identical across all 23 configurations exercised by a full build plus the test suite. Two incidental simplifications fell out. pcmDir was recomputing what Configuration::PcmDir() already returns, and cmakeBuildType is now a one-liner. GetCompileCommand is also most of what a compile_commands.json would need, which this repo lacks. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:15:20 +02:00
feat: project.cpp declares its own dependencies with #pragma crafter dependency A project.cpp could only import std and Crafter.Build, so anything shared between build descriptions had to be a header every consumer copies. Now #pragma crafter dependency "<source>" [branch "<b>" | commit "<sha>"] [project "<file>"] names a sibling crafter-build project that project.cpp itself imports a module from. LoadProject scans for the directive, resolves it through GitProject (a URL) or LocalProject (a path relative to the project file), forces the result into host-tooling mode (the host triple LoadProject's own cache is keyed on, native march, no debug, -fPIC so the archive links into a shared object), builds it, and puts its BMIs and archive on the project.so command line. The dependency's own project.cpp goes through the same loader, so its directives resolve recursively; a cycle between project files is an error instead of unbounded recursion. The dependency is built on every load, fresh or not: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the module depfile — which Module::Check already reads — is what notices the host PCM cache was regenerated. Its artifact mtime is an input to project.so's staleness check, so editing the dependency recompiles project.cpp without touching it. The Linux link gains -fuse-ld=lld because release archives hold ThinLTO bitcode. ProjectDependency(name) hands the same Configuration* back from inside CrafterBuildProject, by configuration name or exported module name, so a test that links the module needn't spell the source twice. It reads a thread_local frame stack that an RAII guard keeps for the whole of LoadProject, which also provides the cycle check. ExpectedOutput() is the link gate's artifact-path lambda hoisted into the :Clang partition, so the staleness check and the -r runner share the one rule. Windows branches are wired identically but unverified. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 20:03:22 +02:00
// Where Build leaves this Configuration's linked artifact: the executable
// (with the target's suffix), `lib<name>.a` / `<name>.lib`, or the shared
// library / DLL. The one rule every "is the consumer older than its
// dependency" check reads, so a staleness test and the link step can't
// disagree about the file name.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
fs::path ExpectedOutput(const Configuration& config);
feat: project.cpp declares its own dependencies with #pragma crafter dependency A project.cpp could only import std and Crafter.Build, so anything shared between build descriptions had to be a header every consumer copies. Now #pragma crafter dependency "<source>" [branch "<b>" | commit "<sha>"] [project "<file>"] names a sibling crafter-build project that project.cpp itself imports a module from. LoadProject scans for the directive, resolves it through GitProject (a URL) or LocalProject (a path relative to the project file), forces the result into host-tooling mode (the host triple LoadProject's own cache is keyed on, native march, no debug, -fPIC so the archive links into a shared object), builds it, and puts its BMIs and archive on the project.so command line. The dependency's own project.cpp goes through the same loader, so its directives resolve recursively; a cycle between project files is an error instead of unbounded recursion. The dependency is built on every load, fresh or not: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the module depfile — which Module::Check already reads — is what notices the host PCM cache was regenerated. Its artifact mtime is an input to project.so's staleness check, so editing the dependency recompiles project.cpp without touching it. The Linux link gains -fuse-ld=lld because release archives hold ThinLTO bitcode. ProjectDependency(name) hands the same Configuration* back from inside CrafterBuildProject, by configuration name or exported module name, so a test that links the module needn't spell the source twice. It reads a thread_local frame stack that an RAII guard keeps for the whole of LoadProject, which also provides the cycle check. ExpectedOutput() is the link gate's artifact-path lambda hoisted into the :Clang partition, so the staleness check and the -r runner share the one rule. Windows branches are wired identically but unverified. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 20:03:22 +02:00
fix(build): name a source's object from its path The object of an implementation unit was named from its file's name alone, <build dir>/<name>_impl.o, and that of a C or CUDA source likewise, <name>_source.o. Two sources of one configuration with the same file name in different directories were therefore compiled into one object, each over the other, with one dependency file between them, and the link was given that object twice (issue #50). A build of an a/Thing.cpp and a b/Thing.cpp that each define a function failed at the link, with duplicate symbols of one of the two and no word of the other. A debug build of two such files that define nothing another file names succeeded, and its program had one file's code twice and the other's not at all. A .c and a .cu of one name shared an object in one directory as well. An object, with its dependency file beside it, is now named from where its source lies: under <build dir>/objects by the source's path from the configuration's directory, objects/a/Thing_impl.o for a/Thing.cpp, or, for a source outside that directory, under <build dir>/objects-outside by its whole path. A .cu's object ends in _cuda.o; a .cpp's still ends in _impl.o and a .c's in _source.o. Two sources then have one object only when their paths are one once . and .. are taken out of them: any other two differ by path or by ending in one of the two directories, and the two directories share nothing, whatever a project calls its own directories. They are directories of their own, and not the build directory itself, because that one holds files named after other things: an interface unit's object, the record of the link and the list of its objects and, for an executable, the BMIs. ObjectPath gives that name, exported beside ExpectedOutput for what looks at an object from outside Build(). Build() names each object by the same rule, once, as it goes over the sources, and the list it keeps of them for the link is what the check whether an object is newer than the output reads as well. Before, each put the name together for itself: Implementation::Check, Implementation::Schedule, and Build() where it compiles C and CUDA sources, lists the link's objects and checks whether to link again. Implementation::Check and Schedule are given the object, where they put its name together from the build directory. The job that compiles a source makes the directory of its object first, since the compiler makes none. The C compile quotes its source, dependency file and object for the shell, as the CUDA compile does: the object of a source outside the configuration's directory holds that source's whole path, and so directories the command did not name before, the working directory's among them where the source is listed relative to it. The progress line of the compile of a .cpp, .c or .cu names the source by the path its object is named from, "Compiling a/Thing.cpp" where it was "Compiling Thing.cpp" for both, and so does the error for a .cu without an nvcc. What else changes: every implementation unit and every C and CUDA source has its object in a new place, so an existing build directory compiles them once more. The objects under the old names stay where they are, unused; a static library's archive does not keep them, being written anew. Interface units are as they were: a BMI is found by its module's name, so two interface files of one name would have to be one module. A source that a configuration lists twice is also as it was, compiled twice into its one object, which the link is given twice. In IncrementalHeaderChange, IncrementalInterfaceChange, StdPcmRebuild and TransitiveInterfaceChange, the lines that spelled out an object's old name take it from ObjectPath. Fixes #50
2026-11-19 11:02:39 +01:00
// Where Build leaves the object of `source`, one of this Configuration's
// implementation units (.cpp), C sources (.c) or CUDA sources (.cu),
// given with its extension; a relative `source` is taken against the
// working directory, as Build takes cFiles and cuda. The dependency file
// the compiler writes lies beside it, as <object>.d.
//
// The object is named from where the source lies: under
// BuildDir()/objects by the source's path from the Configuration's
// `path`, objects/a/Thing_impl.o for a/Thing.cpp, or, for a source
// outside that directory, under BuildDir()/objects-outside by its whole
// path. The name ends in _impl.o for a .cpp, _source.o for a .c and
// _cuda.o for a .cu. So two sources have one object only when their
// paths are one once `.` and `..` are taken out of them as they are
// written: any other two differ by path or by ending in one of the two
// directories, and the two directories share nothing.
//
// Objects were named from the file name alone, in BuildDir() itself:
// a/Thing.cpp and b/Thing.cpp were both compiled into Thing_impl.o,
// each over the other, and the link was given that object twice. The
// link then failed, or, in a debug build of two sources that define
// nothing another file names, gave a program with one source's code
// twice and the other's not at all (issue #50).
//
// An interface unit's object is not named here. It lies in BuildDir()
// itself, named by the unit's file name alone, as its BMI is: clang
// looks a BMI up by its module's name, so two interface files of one
// name would have to be one module. Throws std::invalid_argument for a
// `source` with any other extension.
fs::path ObjectPath(const Configuration& config, const fs::path& source);
feat: install and bundle a Flatpak through the host's flatpak An executable packaged as a Flatpak came out as the files/ of one, which only flatpak build-finish makes an app of, and getting it installed or onto another machine took flatpak commands on the host, typed by hand. Two verbs do it where the host's flatpak can be reached: `crafter-build install` builds the project and installs its app for this user, and `crafter-build bundle` builds it into bin/<variant>.flatpak, a single file for `flatpak install --user` that names Flathub's repository for the runtime. Inside crafter-build's Flatpak they need the org.freedesktop.Flatpak permission, which its manifest does not grant in this commit. Both put the app into the project's repo first, in build/flatpak-apps/<app-id>/ (FlatpakAppDir), one per app rather than per variant, since flatpak-builder's state there is its cache. Every variant exports into it, so the export and the install or bundle made from it hold a lock there, and another crafter-build exporting meanwhile waits rather than leave this one installing or bundling its program. The user remote an install re-points is every checkout's that builds the app-id, so re-pointing it and installing from it hold a second lock, which every crafter-build installing there takes, natively or in the Flatpak, whatever its XDG_CACHE_HOME: in ~/.cache/crafter.build/flatpak-remotes/, found by HOME, for the user's own installation, which flatpak hides from the sandbox behind a tmpfs of the sandbox's own, and in the directory of a private one, FLATPAK_USER_DIR, one lock for all of them where the sandbox shares that directory with the host. Without modules, the host's flatpak build-finish finishes build/flatpak-apps/<app-id>/build-dir, made afresh each time from a metadata naming the app, its runtime and the Sdk and a tree of hard links to the build's files/, copies where a link cannot be made, across filesystems or on one without links, vfat or exFAT: it writes the command, the sandbox's permissions and export/ by flatpak's own rules, those of whichever flatpak the host runs, and refuses a permission it does not know, and flatpak build-export puts the result into the repo. When cfg.flatpak.modules names flatpak-builder module files for what the app needs in /app besides the program, flatpak-builder does both, from a manifest that lists them and copies the built program in last, so nothing is compiled twice. That manifest keeps share/locale in the app ("separate-locales": false): flatpak-builder would split it into a .Locale extension by default, which a bundle, holding the app alone, leaves out. The loader rebases a dependency's module files as it does its cfg.files. install uses a user remote named after the app-id, re-pointed at the repo each time, and says how to remove both. The app's tree in build/flatpak-apps/<app-id>/build-dir, where flatpak-builder installs a module's files too, is left out of the include walk with every other build/, so the headers a module installed reach no compile. cfg.flatpak gets the runtime, the Platform or the Sdk at the branch crafter-build runs on, and the sandbox's permissions, finish-args as Flatpak spells them, which any configuration may declare: an executable gets its dependencies' first and its own last, so it can take one back. The build reads neither, and a change to either links nothing. install and bundle print the permissions, with where each came from, and hand them to build-finish, the one judge of what they mean, so a refusal can be traced to the configuration that declared it. FlatpakPermissions checks the order everywhere, and that a change to one neither moves the build to another directory nor links anything, and, where the host's flatpak runs, what build-finish makes of them and that it refuses a socket it does not have; FlatpakBundle that build-finish exports the desktop entry and the icon, and that the build's own files/ is left as it was; VariantId's test has the runtime, permissions and modules move no directory. The host's flatpak and flatpak-builder are reached only through HostCommand in :Platform, which builds the command lines of RunHostFlatpak, RunHostFlatpakBuilder and HostFlatpakUnavailable's probes: flatpak-spawn --host --watch-bus inside crafter-build's Flatpak, started in the host's / and passing FLATPAK_USER_DIR on, and the command itself natively. flatpak-spawn would otherwise start a command in crafter-build's own working directory, which the host need not have, and from /app, say, every host command would fail. HostFlatpakUnavailable says why the host cannot be reached: no org.freedesktop.Flatpak permission, no session bus (CI's build sandbox has neither), a host that does not see the project's bin/ and build/ where crafter-build does, as it does not in the sandbox's own /tmp, /var, /usr, /etc and /app or where a link leads into one, or no flatpak natively. That, and an executable that is not packaged as a Flatpak, install and bundle refuse as soon as the project is loaded, before anything is built; FlatpakVerbRefusal shows the second. The host is asked rather than the sandbox's paths modelled, which an override sharing a directory inside the sandbox's own would defeat: its flatpak is started in a directory just made in each of bin/ and build/ under a name no other has, which it enters only where it sees that very directory, and the directory is removed again. --help gets a section on both, and its Clean section says the repo an install points at goes with build/. FlatpakModules runs flatpak-builder only with a flatpak-builder program on the host, crafter-build falling back to the org.flatpak.Builder app, whose `flatpak run` would write ~/.var/app in the real home, and with the Platform and Sdk it builds the app with. The library's install function is InstallFlatpakApp because project.cpp files define an InstallFlatpak script of their own under `using namespace Crafter`, this repository's included, and a library InstallFlatpak would make the name an overload set, which the scripts table's std::function cannot be built from; BundleFlatpakApp is named to match. JsonQuote writes the manifest's strings, and variants.json's, which escaped quotes and backslashes only. FlatpakExport, FlatpakManifestText, ExportFlatpak and FlatpakPermission, which only :Clang uses, stay out of the API a project.cpp compiles against, as RecordFlatpakPlaced does, so their names cannot meet a project's own under `using namespace Crafter`; ExportFlatpak's comment names the app's lock, which its callers hold, beside HostFlatpakUnavailable.
2026-11-02 19:38:30 +01:00
// `crafter-build install`: makes the Flatpak of the files/ `config` was
// built as (see Packaging::Flatpak), with its permissions, puts it into
// the project's repo, and installs it for this user from a user remote
// named after the app-id, updating what an earlier install left. The
// host's flatpak does the work (see HostFlatpakUnavailable and
// ExportFlatpak). Returns why it could not; empty when it did.
std::string InstallFlatpakApp(const Configuration& config);
// `crafter-build bundle`: the same export, then a single-file bundle at
// FlatpakBundlePath(config) that `flatpak install --user <file>` takes
// on any machine, fetching the runtime from Flathub where it is missing.
std::string BundleFlatpakApp(const Configuration& config);
// bin/<variant>.flatpak, beside the bin dir it is made from.
fs::path FlatpakBundlePath(const Configuration& config);
// build/flatpak-apps/<app-id>, where install and bundle keep the app's
// repo and the build directory they finish it in, and with modules the
// manifest and flatpak-builder's state. One per app rather than per
// variant: the state is flatpak-builder's cache, and under a variant's
// name every module would be built again after each compiler update.
fs::path FlatpakAppDir(const Configuration& config);
// The manifest flatpak-builder makes the app from when cfg.flatpak has
// modules (FlatpakManifestText).
std::string FlatpakManifest(const Configuration& config);
refactor: extract GetCompileCommand and StdPcmDir out of Build The clang invocation was assembled inline across four regions of Build, interleaved with the dependency-graph walk, so nothing else could ask "what flags does this Configuration compile with". The linter's AST layer needs exactly that, and it cannot approximate it: a precompiled module is rejected outright by a translation unit whose target features differ from the one that wrote it. Dropping just -march=native produces hundreds of "compiled with the target feature '+avx512bw' but the current translation unit is not" errors and no usable parse, so reconstructed flags fail hard rather than degrade. GetCompileCommand is the config-pure part: target, arch, standard, configuration defines, module search paths, includes, user compileFlags, optimisation and LTO. Build appends only what depends on work having happened — dependency public flags and external dependency flags. The sub-strings it also needs on their own (includes, defines, user flags, LTO) come back as struct members, so the .c compile path is unchanged. Verified by probing `command` at the equivalent point before and after and diffing: byte-identical across all 23 configurations exercised by a full build plus the test suite. Two incidental simplifications fell out. pcmDir was recomputing what Configuration::PcmDir() already returns, and cmakeBuildType is now a one-liner. GetCompileCommand is also most of what a compile_commands.json would need, which this repo lacks. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:15:20 +02:00
// The clang invocation every C++ translation unit in this Configuration is
// compiled with, before anything that depends on work having happened
// (dependency public flags, external dependency flags — Build appends
// those itself). A pure function of the Configuration.
//
// Anything that needs to PARSE this project's sources rather than build
// them — the linter's AST layer, a future compile_commands.json — must go
// through this instead of assembling its own flags. A precompiled module
// is rejected outright by a TU whose target features differ from the one
// that wrote it, so approximately-right flags fail hard rather than
// degrade: omitting -march=native alone produces hundreds of "compiled
// with the target feature '+avx512bw' but the current translation unit is
// not" errors and no usable parse.
struct CompileCommand {
std::string command; // full C++ compile prefix, shell-ready
// Sub-sets Build also needs on its own: the .c compile path takes the
// includes, defines and user flags but not the module-only bits.
std::string includeFlags;
std::string defineFlags;
std::string userFlags;
std::string ltoCompileFlags;
std::string ltoLinkFlags;
feat(lint): no-char-pointer reads the AST, retiring the interop denylist The rule was `\bchar\s*\*` over the text minus a substring denylist — argv, getenv, setenv, dlerror, c_str, .data(, reinterpret_cast, extern ". Every entry was a patch for one interop site, the list could only grow as libraries arrived, and each entry disabled the rule for the whole LINE it appeared on. It now walks declarations and asks the question the denylist was approximating: whose header dictates this spelling? A declaration with C language linkage, or one whose initialiser binds to an entity declared outside the project root, is somebody else's API and keeps its spelling. getenv, c_str and friends are exempt because of where they are declared, not because they are named here, so a new external library needs no new entry. Two bugs found while testing this, both of which had made the rule silently pass over the entire repository: clang_getCursorLanguage cannot be used to detect extern "C". Its default answer is CXLanguage_C for a plain function, variable or parameter even in a C++ translation unit, so isExternC was true almost everywhere and exempted everything. Replaced by tracking CXCursor_LinkageSpec depth during the walk, reading the extent text to tell extern "C" from extern "C++". Attributing any foreign reference in a subtree to the enclosing declaration was too broad: a function that merely touched libc++ somewhere in its body would exempt its own signature. Narrowed to initialiser contexts — a variable, field or parameter — which is where a binding to a foreign API actually occurs. Also: functions now carry their RESULT type rather than the whole function type, since the parameters arrive as their own declarations and would otherwise be reported twice. main's parameters are exempt structurally, its signature being fixed by the language rather than chosen here. Two sites keep an explicit lint-disable, both Crafter::Run taking main's argv verbatim. That is two visible, reasoned suppressions in place of a denylist that silently disabled the rule for every line mentioning one of eight tokens. ExternalCloneDir and ExternalIncludeFlags are now exposed from :External, so a source that includes an external dependency's headers can be parsed without running a build to discover where they are. BuildExternal derives its own working directory through the same function, so the two cannot drift. Crafter.Build-Shader.cpp needed this to parse at all. A file with no compile command — project.cpp, which LoadProject builds with its own flags — is not a translation unit of the build graph, so AST rules skip it the way a rule self-filters by extension. That is distinct from a file that should have parsed and did not, which stays an error. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:46:32 +02:00
// -I flags from external dependencies' declared includeDirs, for this
// configuration and its dependencies. Deliberately NOT folded into
// `command`: Build appends the authoritative set from the external build
// results instead. Exposed for callers that only PARSE sources and so
// cannot wait for a build to tell them where the headers are.
std::string externalIncludeFlags;
refactor: extract GetCompileCommand and StdPcmDir out of Build The clang invocation was assembled inline across four regions of Build, interleaved with the dependency-graph walk, so nothing else could ask "what flags does this Configuration compile with". The linter's AST layer needs exactly that, and it cannot approximate it: a precompiled module is rejected outright by a translation unit whose target features differ from the one that wrote it. Dropping just -march=native produces hundreds of "compiled with the target feature '+avx512bw' but the current translation unit is not" errors and no usable parse, so reconstructed flags fail hard rather than degrade. GetCompileCommand is the config-pure part: target, arch, standard, configuration defines, module search paths, includes, user compileFlags, optimisation and LTO. Build appends only what depends on work having happened — dependency public flags and external dependency flags. The sub-strings it also needs on their own (includes, defines, user flags, LTO) come back as struct members, so the .c compile path is unchanged. Verified by probing `command` at the equivalent point before and after and diffing: byte-identical across all 23 configurations exercised by a full build plus the test suite. Two incidental simplifications fell out. pcmDir was recomputing what Configuration::PcmDir() already returns, and cmakeBuildType is now a one-liner. GetCompileCommand is also most of what a compile_commands.json would need, which this repo lacks. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:15:20 +02:00
// ThinLTO is on: objects hold bitcode, so archiving needs llvm-ar.
bool useLto = false;
fs::path stdPcmDir;
fs::path pcmDir;
};
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
CompileCommand GetCompileCommand(const Configuration& config);
refactor: extract GetCompileCommand and StdPcmDir out of Build The clang invocation was assembled inline across four regions of Build, interleaved with the dependency-graph walk, so nothing else could ask "what flags does this Configuration compile with". The linter's AST layer needs exactly that, and it cannot approximate it: a precompiled module is rejected outright by a translation unit whose target features differ from the one that wrote it. Dropping just -march=native produces hundreds of "compiled with the target feature '+avx512bw' but the current translation unit is not" errors and no usable parse, so reconstructed flags fail hard rather than degrade. GetCompileCommand is the config-pure part: target, arch, standard, configuration defines, module search paths, includes, user compileFlags, optimisation and LTO. Build appends only what depends on work having happened — dependency public flags and external dependency flags. The sub-strings it also needs on their own (includes, defines, user flags, LTO) come back as struct members, so the .c compile path is unchanged. Verified by probing `command` at the equivalent point before and after and diffing: byte-identical across all 23 configurations exercised by a full build plus the test suite. Two incidental simplifications fell out. pcmDir was recomputing what Configuration::PcmDir() already returns, and cmakeBuildType is now a one-liner. GetCompileCommand is also most of what a compile_commands.json would need, which this repo lacks. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:15:20 +02:00
fix(external): fetch and build each clone once per build pass `crafter-build test` builds a project's tests side by side, and a project whose tests each copy its externalDependencies hands every one of them the same unpinned dependency. Each test's Build() pulled the shared clone. Before the clone had a lock, those pulls ran at the same time and broke its .git/FETCH_HEAD, which failed every test of Crafter.Graphics (issue #34). Since 653dd0b they wait for each other, but every one is still a network round trip: 26 tests cost 26 pulls of each dependency, one after another, and for a CMake dependency as many configure checks and builds. depResults already records one build pass, keyed by the PcmDir of every dependency configuration built in it. An external dependency now goes in the same map, keyed by the directory its build leaves (ExternalBuildDir: the clone, or for CMake its build directory). The first configuration that needs it fetches and builds it; the others wait for that and take its outcome. Keying on the build directory rather than the clone keeps a CMake declaration from taking the outcome of a header-only declaration of the same clone, which only fetched it. A fresh depResults is a fresh pass, so the next build still pulls, and every caller of Build() gets this: RunTests, a plain build, and the pragma dependencies LoadProject builds. To make that possible BuildExternal is split. BuildExternal is now the shared work, lock, fetch, configure and build, and returns the error. ExternalOutputs computes what one declaration compiles and links with, because two declarations of one clone can differ in includeDirs, libDirs and libs; ExternalBuildResult loses its error field. The work no longer stops between steps when the configuration that started it is cancelled: others may be waiting on it, and a run cut short would leave them a clone nobody fetched. A dependency configuration's Build() already runs to completion for the same reason. The promise and future the dependency threads used to build or wait for a configuration are now one helper, OncePerPass, which both kinds use. An exception thrown in BuildExternal used to escape its thread into std::terminate; it is now a build error, as for a dependency. With eight tests that share a local dependency, a test run fetched it eight times before this and fetches it once now (SharedExternalFetch, next commit). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 02:09:24 +01:00
// Builds `config` and the configurations it depends on. depResults is the
// record of one build pass, guarded by depMutex and keyed by the directory
// each piece of work writes: a dependency's PcmDir, an external
// dependency's ExternalBuildDir. Configurations built with the same map,
// as RunTests builds its tests, build a shared dependency and fetch a
// shared external once between them. A fresh map starts a new pass, which
// checks everything again and pulls unpinned externals again.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
BuildResult Build(Configuration& config, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex);
2026-04-23 01:57:25 +02:00
feat: let a project file return several configurations A project.cpp described one configuration: CrafterBuildProject returns a Configuration by value, and anything else the project wanted built had to be among that one's dependencies. There it was built as part of that configuration's graph: under the check that a graph builds each module once, with its libraries handed up to whatever links that configuration, and with its tests and scripts out of reach of `test` and `run`. Jorijn asked for a project.cpp that can return several unrelated configurations which all get built, and suggested a separate entry point, so that no existing project file breaks. A project file now defines one of two functions. CrafterBuildProject is as it was. CrafterBuildConfigurations returns std::vector<Configuration*>: pointers to configurations the file keeps alive itself, or that GitProject and LocalProject gave it. The two have different names because the loader finds the entry point by its C symbol, which carries no return type, so one name with two return types would be called as whichever the loader guessed. They are pointers because a project file takes pointers between its configurations, for `dependencies` and for a test's, before it returns them, and a vector of values would move them. LoadConfigurations loads a project file with either entry point and returns the list. A CrafterBuildProject's Configuration comes back as a list of one, constructed by the call where the loader keeps it for the rest of the process; LoadProjectFromRoot, which did that for a sibling's, leaves it to LoadConfigurations, and the project cache holds the lists without owning a Configuration. The Configuration of the project crafter-build is pointed at is kept that long as well, where it was a local of Run(). LoadConfigurations throws for a file that defines both functions or neither, and for a CrafterBuildConfigurations that returns nothing, a null pointer or one configuration twice. It also throws for one that returns a configuration a project loaded through GitProject or LocalProject keeps to itself, which the loader now takes down when it loads that project's file: what the configurations the file returned led to through `dependencies` or through their tests, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. Returned from here, such a configuration would count as this file's own to `test` and `run`, and only the configurations a project file returns are rebased onto its directory. LoadProject stays, for a caller that wants a CrafterBuildProject's Configuration by value, and throws for a file with the other entry point. GitProject and LocalProject keep, per spec and args, the list a sibling's file returned, and return the first one unless the spec's new `configuration` names another by Configuration::name. Every configuration of the list is rebased onto the sibling's directory, except one that another project's file had returned before, which was rebased onto that project's. Specs that differ only in the name they pick share one load. A name the sibling does not have throws, listing the names it has, and a name two of its configurations share throws too. A `#pragma crafter dependency` gets the first. BuildAll builds the returned configurations in one pass. Each is built by Build(), as a project's one configuration is, the first on the calling thread and each other one on a thread of its own, and its result then goes into the record of the pass under its PcmDir, where Build() looks for a dependency. One that another of them is built on is built before that other starts, which then finds it in the record: started beside it, the other would not find it there yet and would build it a second time. A configuration is not put into the record before it is built, because a dependency of its own that is built into the same directory would be handed its unfinished build and wait for it, while it waits for the dependency. All of them are built to the end, and the errors come back in the order given, each message once; an exception a build throws comes back as an error that names the configuration, where Run() printed the exception's own text for a project's one configuration. Refused before anything is built: two that would be built into one directory, which would be two builds writing the same files at once; several that are each built on something of another's directory, so that none could be built first; and one that is built on something of its own directory when another is built on that directory as well, since the record holds one result for a directory and the other could be given either. One shortcut is in it. A wasm executable that declares wasmVariants builds what it is built on once more per variant, and says which variant by rewriting those configurations in place, at the end of its Build(). A library that two returned configurations share would change under the one still building its baseline, so with such an executable anywhere in the graph BuildAll builds the configurations one after the other, on the calling thread. Keeping them side by side takes a variant driver that does not rewrite configurations other builds read, which this commit does not attempt. Run() works on the list. A build builds all of it. `test` runs the tests, and `run` offers the scripts, of the ones in it that the project file made itself. One that another project's file returned to GitProject or LocalProject, and that this file returns in turn, is built with the rest, but its tests and scripts stay that project's, so `run` still reaches only the scripts of the project crafter-build was pointed at. What the list itself rules out Run() refuses once the project file has loaded, before any of the list is built and before AGENTS.md is written: for a build, `-r`, `install` and `bundle` whatever BuildAll refuses a list for, and for `test`, which builds its tests with Build() and never comes to BuildAll, two returned configurations of one directory. BuildAll makes its refusals again for whoever calls it. A script is handed the configuration it is declared on. `lint` and `format` walk from every returned configuration and keep, as before, the configurations in the project's directory: the returned ones first, in the order the file returned them, then what they depend on, so that of two returned ones that register a rule under one name the earlier one's runs. `-r` runs the executable when exactly one of them is one, and `install` and `bundle` export the one that is packaged as a Flatpak; with more than one candidate each refuses and names them, `-r` once everything is built and `install` and `bundle` before anything is. AGENTS.md takes the notes that the dependencyNotes of each returned configuration the file made itself selects among what that one is built against, and the file's pragma tooling and a returned configuration of another project go by the widest of those settings. There, a configuration is another project's when GitProject or LocalProject loaded it from another project file than the one whose AGENTS.md is written, two files being one when they resolve to one path, so UpdateAgentsMd still reads the setting of a Configuration one of the two returned when it is given that Configuration's own project file. For that, RunTests, RunLint, RunScript and UpdateAgentsMd each gained an overload that takes the list, and the one that takes a single Configuration calls it with a list of one. SetParentProject gained one too, and ParentLib searches the graph of every configuration it was given. BuildAll, RunTests and RunScript count a configuration the list names twice once. The tests of several configurations share what one configuration's had to itself: AddTest names a test's sources, tests/<name>, and its build directory after the test and its compile state, not after the configuration that declares it. Two configurations that each declare a test of one name, compiled alike, would have RunTests build both in that one directory, each with the dependencies of its own declaration. RunTests fails both without building either, and each failure names the configurations. It compares tests of different configurations only, so a project of one configuration is treated as it was. The --help text names the second entry point, says what -r, install and bundle do with several configurations, and speaks of the project file's entry point as what gets the project args, where it named CrafterBuildProject. AGENTS.template.md says that a project.cpp returns one configuration or several, that Run() works on the list and what a new verb has to decide about it, which configurations have their path rebased, and that the scripts of a returned configuration of another project cannot be run. Two of its notes named LoadProject as what loads a project.cpp for crafter-build, which Run(), GitProject and LocalProject no longer call, and speak of the load now. Its rule for the link flags of a test that loads a project file names the ways a test loads one, where it named LoadProject, and its entry for `:Script` speaks of the `scripts` of the configurations the driver is given, where it named `cfg.scripts`. Its entry for `:Platform` names LoadConfigurations beside LoadProject. That entry also said that `:Platform` holds all OS-specific code, which it did not before this range either, :Agents, :Progress, :Lint and :Clang including POSIX headers of their own, and no longer says so. The bug-prover lens's section names BuildAll's threads and LoadConfigurations. Not in this commit: a way to say which executable -r runs or which app install and bundle export when there are several, and a keyword that lets a `#pragma crafter dependency` name a configuration.
2026-11-15 02:16:06 +01:00
// Builds every one of `configurations`, the configurations a project
// file returns, in the pass `depResults` records. Each is built by
// Build(), as a project's one configuration is, and its result then
// goes into the record under its PcmDir, where Build() records a
// dependency. What two of them depend on is built once, and so is one
// that another of them is built on: it is built before the other
// starts, and the other finds it in the record. The first is built on
// the calling thread and each other one on a thread of its own, all of
// them to the end: one that fails stops none of the others. Returns the
// errors of the ones that failed, in the order given and each message
// once, so a dependency that failed for three of them is reported once,
// and an empty string when all were built. A configuration the list
// names twice is built once.
//
// With a wasm executable that declares wasmVariants among them, or
// among what they are built on, they are built one after the other on
// the calling thread instead: its build rewrites the configurations it
// is built on for each variant, which no other build may be reading.
//
// Refuses, before building anything, two of them that would be built
// into one directory (same path, name, target and compile state), which
// would be two builds writing the same files at once; a set of them in
// which each is built on something that is built into the directory of
// another, so that none could be built first; and one that is built on
// something of its own directory when another of them is built on that
// directory too, since the record holds one result for a directory and
// the other could be given either.
std::string BuildAll(std::span<Configuration* const> configurations, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex);
feat(lint): no-char-pointer reads the AST, retiring the interop denylist The rule was `\bchar\s*\*` over the text minus a substring denylist — argv, getenv, setenv, dlerror, c_str, .data(, reinterpret_cast, extern ". Every entry was a patch for one interop site, the list could only grow as libraries arrived, and each entry disabled the rule for the whole LINE it appeared on. It now walks declarations and asks the question the denylist was approximating: whose header dictates this spelling? A declaration with C language linkage, or one whose initialiser binds to an entity declared outside the project root, is somebody else's API and keeps its spelling. getenv, c_str and friends are exempt because of where they are declared, not because they are named here, so a new external library needs no new entry. Two bugs found while testing this, both of which had made the rule silently pass over the entire repository: clang_getCursorLanguage cannot be used to detect extern "C". Its default answer is CXLanguage_C for a plain function, variable or parameter even in a C++ translation unit, so isExternC was true almost everywhere and exempted everything. Replaced by tracking CXCursor_LinkageSpec depth during the walk, reading the extent text to tell extern "C" from extern "C++". Attributing any foreign reference in a subtree to the enclosing declaration was too broad: a function that merely touched libc++ somewhere in its body would exempt its own signature. Narrowed to initialiser contexts — a variable, field or parameter — which is where a binding to a foreign API actually occurs. Also: functions now carry their RESULT type rather than the whole function type, since the parameters arrive as their own declarations and would otherwise be reported twice. main's parameters are exempt structurally, its signature being fixed by the language rather than chosen here. Two sites keep an explicit lint-disable, both Crafter::Run taking main's argv verbatim. That is two visible, reasoned suppressions in place of a denylist that silently disabled the rule for every line mentioning one of eight tokens. ExternalCloneDir and ExternalIncludeFlags are now exposed from :External, so a source that includes an external dependency's headers can be parsed without running a build to discover where they are. BuildExternal derives its own working directory through the same function, so the two cannot drift. Crafter.Build-Shader.cpp needed this to parse at all. A file with no compile command — project.cpp, which LoadProject builds with its own flags — is not a translation unit of the build graph, so AST rules skip it the way a rule self-filters by extension. That is distinct from a file that should have parsed and did not, which stays an error. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 23:46:32 +02:00
// Takes main's argv verbatim so the CLI entry point is a one-liner;
// the shape is inherited from the language, not chosen here.
// lint-disable-next-line no-char-pointer
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::int32_t Run(std::int32_t argc, char** argv);
V2: WASI, -r flag, CI pipeline, examples & tests cleanup WASI / wasm32 target support - Auto-detect /usr/share/wasi-sysroot on Linux when target starts_with("wasm32") - Skip -march/-mtune for wasm (clang rejects them) - Apply -fno-exceptions -fno-c++-static-destructors -mllvm -wasm-enable-sjlj -D_WASI_EMULATED_SIGNAL to wasm builds (compile + std PCM, kept in sync) - .wasm output extension in expectedOutputFor and link command - EnableWasiBrowserRuntime(cfg): opt-in helper that drops index.html + runtime.js next to the .wasm; runtime.js reads window.CRAFTER_WASM_URL set in the templated index.html so a single shim handles any output name -r run flag in the CLI: build then exec the artifact (host targets only; rejects libraries; auto .exe/.wasm extension handling) CI pipeline (.forgejo/workflows/ci.yaml) - Triggers: PR/push to master + manual dispatch - Single arch-latest container job: install deps, bootstrap, self-rebuild, run tests, cross-compile mingw, package both archives, upload artifacts - Rolling 'latest' release published only on push/dispatch to master mingw cross-compile from Linux now works end-to-end: - ExternalDependency cache key includes target so per-target glslang builds don't collide; CMAKE_BUILD_TYPE=Release pinned (otherwise glslang appends 'd' to lib names and breaks linking); cross-compile cmake flags (CMAKE_SYSTEM_NAME=Windows, CMAKE_*_COMPILER_TARGET=...) - project.cpp accepts --target=<triple>; Linux-only -Wl,--export-dynamic and -ldl are gated; mingw glslang skips the standalone exe (its libgcc_eh link pulls pthread which mingw doesn't link by default) - mingw compile uses -femulated-tls so std::__once_callable etc reference the same emutls symbols libstdc++ provides - mingw link auto-adds -lstdc++exp -lpthread GetCrafterBuildHome() exposed from the Platform module; LoadProject (Linux + Windows) now both use it instead of duplicating the resolution. Examples reorg: hello-world, library, with-module, wasi, tests — each with its own README. Tests reorg: per-test directory with inner/ fixture, no shared tests/fixtures/ tree. New Wasi test verifies .wasm magic bytes. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 23:24:46 +02:00
fix: key the host PCM cache on source content, add clean, hash project args Three follow-ons to the stale-build report, all cases of an identity not capturing something that changes the output. The host PCM cache under <cache>/crafter.build/<target>-<march>/ is shared by every crafter-build on the machine, and freshness was a per-file mtime comparison. That cannot tell "this PCM is newer than my source" from "this PCM was built from different sources that happen to be newer", so a package install and a working checkout — or two checkouts of different versions — silently compiled their project.cpp against each other's declarations. Invalidation now keys on a stamp over the bytes of every module source, which also covers the case one file's mtime never could: the cached PCMs import each other, so a change to :Interface invalidates :Clang's PCM with Crafter.Build-Clang.cppm untouched. Project args ApplyStandardArgs does not itself interpret are now folded into VariantId. Such a flag typically decides what gets compiled or bundled — the report's example is --no-webgpu dropping entries from cfg.files — and without it both settings shared one bin dir and interleaved their outputs there, leaving a bundle matching neither. Sorted and deduplicated so flag order doesn't split the cache, and inherited by test Configurations. `crafter-build clean` removes the project's bin/ and build/ trees. It deliberately does not load project.cpp: cleaning is most often reached when something is already wrong, and a clean that first needs the project to compile is useless exactly then.
2026-07-30 17:43:09 +00:00
// Delete the bin/ and build/ trees beside `projectFile`, returning the paths
// that existed and were removed. Backs `crafter-build clean`.
//
// Deliberately does not load the project: cleaning is most often reached
// when something is already wrong, and a clean that first needs project.cpp
// to compile (and its git dependencies to be present) is useless exactly
// then. That means variant directories are not enumerated — the whole tree
// goes, which is what the by-hand `rm -rf bin build` did anyway.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
std::vector<fs::path> CleanProject(const fs::path& projectFile);
fix: key the host PCM cache on source content, add clean, hash project args Three follow-ons to the stale-build report, all cases of an identity not capturing something that changes the output. The host PCM cache under <cache>/crafter.build/<target>-<march>/ is shared by every crafter-build on the machine, and freshness was a per-file mtime comparison. That cannot tell "this PCM is newer than my source" from "this PCM was built from different sources that happen to be newer", so a package install and a working checkout — or two checkouts of different versions — silently compiled their project.cpp against each other's declarations. Invalidation now keys on a stamp over the bytes of every module source, which also covers the case one file's mtime never could: the cached PCMs import each other, so a change to :Interface invalidates :Clang's PCM with Crafter.Build-Clang.cppm untouched. Project args ApplyStandardArgs does not itself interpret are now folded into VariantId. Such a flag typically decides what gets compiled or bundled — the report's example is --no-webgpu dropping entries from cfg.files — and without it both settings shared one bin dir and interleaved their outputs there, leaving a bundle matching neither. Sorted and deduplicated so flag order doesn't split the cache, and inherited by test Configurations. `crafter-build clean` removes the project's bin/ and build/ trees. It deliberately does not load project.cpp: cleaning is most often reached when something is already wrong, and a clean that first needs the project to compile is useless exactly then.
2026-07-30 17:43:09 +00:00
V2: WASI, -r flag, CI pipeline, examples & tests cleanup WASI / wasm32 target support - Auto-detect /usr/share/wasi-sysroot on Linux when target starts_with("wasm32") - Skip -march/-mtune for wasm (clang rejects them) - Apply -fno-exceptions -fno-c++-static-destructors -mllvm -wasm-enable-sjlj -D_WASI_EMULATED_SIGNAL to wasm builds (compile + std PCM, kept in sync) - .wasm output extension in expectedOutputFor and link command - EnableWasiBrowserRuntime(cfg): opt-in helper that drops index.html + runtime.js next to the .wasm; runtime.js reads window.CRAFTER_WASM_URL set in the templated index.html so a single shim handles any output name -r run flag in the CLI: build then exec the artifact (host targets only; rejects libraries; auto .exe/.wasm extension handling) CI pipeline (.forgejo/workflows/ci.yaml) - Triggers: PR/push to master + manual dispatch - Single arch-latest container job: install deps, bootstrap, self-rebuild, run tests, cross-compile mingw, package both archives, upload artifacts - Rolling 'latest' release published only on push/dispatch to master mingw cross-compile from Linux now works end-to-end: - ExternalDependency cache key includes target so per-target glslang builds don't collide; CMAKE_BUILD_TYPE=Release pinned (otherwise glslang appends 'd' to lib names and breaks linking); cross-compile cmake flags (CMAKE_SYSTEM_NAME=Windows, CMAKE_*_COMPILER_TARGET=...) - project.cpp accepts --target=<triple>; Linux-only -Wl,--export-dynamic and -ldl are gated; mingw glslang skips the standalone exe (its libgcc_eh link pulls pthread which mingw doesn't link by default) - mingw compile uses -femulated-tls so std::__once_callable etc reference the same emutls symbols libstdc++ provides - mingw link auto-adds -lstdc++exp -lpthread GetCrafterBuildHome() exposed from the Platform module; LoadProject (Linux + Windows) now both use it instead of duplicating the resolution. Examples reorg: hello-world, library, with-module, wasi, tests — each with its own README. Tests reorg: per-test directory with inner/ fixture, no shared tests/fixtures/ tree. New Wasi test verifies .wasm magic bytes. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 23:24:46 +02:00
// Add a small index.html + runtime.js pair next to the .wasm output so the
// build can be loaded directly in a browser (just `serve` the bin dir and
// open it). Opt-in: WASI builds destined for wasmtime/wasmer don't need
// this and shouldn't carry the extra files. Call from project.cpp after
// outputName is set; index.html is generated against the current
fix(wasi-runtime): end exit and park without running the program runtime.js implemented proc_exit by throwing a JavaScript error through the wasm stack, and the switch to -fwasm-exceptions made that error catchable: every cleanup pad, catch (...) and noexcept terminate pad catches a foreign exception. An exit therefore ran the destructors of every frame it left, a catch (...) swallowed it and carried on, and under a noexcept frame it ended in std::terminate. Crafter.Graphics calls std::_Exit(0) in Window::StartSync to hand the thread to requestAnimationFrame; once the exit's destructors had torn down main's locals, every later frame read destroyed state. proc_exit is now a function of a small helper module, bound directly as the program's import, that reports to the runtime and then executes unreachable. A trap is the one thing wasm code cannot catch, and raised in wasm rather than from JS it does not depend on each engine keeping a trap uncatchable when it passes back through a JS frame. Nothing of the program runs on the way out and its shadow stack stays as it was, which is what exit and _Exit require. window.crafter_wasi.exitCode holds the status, also after a return from main, so that bridges which call into the program on their own can stop. Handing the thread to the browser for good is a separate import, crafter_runtime.park. It ends the call the same way but leaves the program alive, and main's locals valid for the calls that follow, so StartSync keeps its contract that no caller code after it runs. Until Crafter.Graphics moves to park, its _Exit behaves as before minus the destructors: the runtime records an exit but cannot stop a bridge that calls exports itself. A WASI reactor build, where main returns and state lives in statics, was the alternative. It breaks StartSync's promise never to return, which the native targets rely on. JSPI would keep the whole stack alive, but Safari does not have it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:55:21 +01:00
// outputName so renaming the binary later requires another call. In that
// runtime exit and _Exit end the program without running any more of it;
// a program that hands the thread to the browser and keeps serving calls
// parks instead, through the crafter_runtime.park import (runtime.js,
// PROGRAM_END).
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void EnableWasiBrowserRuntime(Configuration& cfg);
2026-04-29 18:59:01 +02:00
feat: feature-detected browser-wasm variants (relaxed-SIMD) + variant-aware runtime The browser wasm pipeline hardcoded -msimd128 for every wasm32 target and baked a single wasm URL into index.html, so newer codegen features that aren't yet baseline across engines (relaxed SIMD today; threads, future SIMD revisions later) couldn't be adopted without dropping the browsers that lack them. Add a general, feature-parameterized mechanism owned entirely by Crafter.Build: - Configuration::wasmVariants declares N codegen variants (label, extra -m flags, runtime probes). Build() compiles the baseline plus one outputName.<label>.wasm per variant, recompiling the whole graph (incl. dep libs + std PCM) with the variant's flags — relaxed-SIMD is per-TU codegen, not a link switch. wasmVariantFlags folds into VariantId so each variant's objects/PCMs land in their own build+bin dir. - EnableWasiBrowserRuntime emits a variants.json manifest (label -> url + probes), preferred-first with the baseline as the universal fallback. - The shipped runtime.js runs inlined wasm-feature-detect probes (relaxed-simd, simd, tail-call, bulk-memory, exception-handling, threads), picks the first variant whose probes all pass, and falls back to the single baked CRAFTER_WASM_URL when no manifest is present (backward compatible). - EnableWasiRelaxedSimdVariant registers the relaxed-SIMD variant — the motivating case (Chrome 114+/Firefox 120+ enable it by default; Safari still flag-gates it as of mid-2026). Verified end to end: a wasm32-wasip1 build emits both wasi-hello.wasm and wasi-hello.relaxed-simd.wasm + variants.json; Firefox selects the relaxed-simd variant and runs it. Resolves #24 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 15:14:18 +00:00
// Register the relaxed-SIMD codegen variant on cfg. Builds an additional
// outputName.relaxed-simd.wasm compiled with -mrelaxed-simd (FMA,
// dot-product, relaxed swizzle/laneselect, …); the shipped runtime serves
// it only to engines that report relaxed-SIMD support (Chrome 114+, Firefox
// 120+) and falls back to the baseline outputName.wasm everywhere else
// (e.g. Safari, which still gates relaxed SIMD behind a flag as of mid
fix(wasm): what the review found -flto in a wasm configuration's compileFlags or linkFlags reached the link, where LTO code generation runs without the backend options that keep exception handling: every landing pad was dropped, and the build succeeded with throws that escaped their catch blocks. -fno-exceptions there made every `import std;` fail on the std module built with exceptions, and a wasm shared library failed to link against the eh/ libc++, which is static archives built without -fPIC. Build() refuses all three now, each with a line that says why, before it makes a directory or starts a thread. The sysroot check sat in BuildStdPcm, which the linter calls as well. There the error only dropped the compile command, so lint ran no AST rule on a wasm configuration and reported it clean. It also refused static libraries, which never link, fired after the shader and external threads had started, and called a missing sysroot, or one without the target, "no C++ exception support". It is part of the same early check now, which first says when the sysroot or the target's directory is missing, and asks for libunwind only where something links. C sources got only the signal.h define. setjmp.h refused to compile in C, and a C object given -wasm-enable-sjlj through compileFlags used the legacy exception encoding next to C++ objects in the standard one, a mix engines refuse to load. They get WasmCompileFlags now, like the C++ units, a variant pass's flags included. The baseline probes include simd: V8 and SpiderMonkey switch SIMD off on x86 CPUs without SSE4.1, which virtual machines often present, and such an engine passed the exception-handling probe only to fail compiling the module; the manifest tests expect it on every entry. The Flatpak pins WASI_SDK_EXCEPTIONS=DUAL, which wasi-sdk 34 defaults to only with clang 23 or newer, and checks that the eh/ libunwind got installed: the wasm tests skip without it, so CI would otherwise pass a Flatpak whose every wasm build fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 06:10:41 +01:00
// 2026). Both need what WasmBaselineProbes names, so an engine without
// exception handling gets neither but an error saying so. Idempotent. Call before EnableWasiBrowserRuntime so the emitted
feat: feature-detected browser-wasm variants (relaxed-SIMD) + variant-aware runtime The browser wasm pipeline hardcoded -msimd128 for every wasm32 target and baked a single wasm URL into index.html, so newer codegen features that aren't yet baseline across engines (relaxed SIMD today; threads, future SIMD revisions later) couldn't be adopted without dropping the browsers that lack them. Add a general, feature-parameterized mechanism owned entirely by Crafter.Build: - Configuration::wasmVariants declares N codegen variants (label, extra -m flags, runtime probes). Build() compiles the baseline plus one outputName.<label>.wasm per variant, recompiling the whole graph (incl. dep libs + std PCM) with the variant's flags — relaxed-SIMD is per-TU codegen, not a link switch. wasmVariantFlags folds into VariantId so each variant's objects/PCMs land in their own build+bin dir. - EnableWasiBrowserRuntime emits a variants.json manifest (label -> url + probes), preferred-first with the baseline as the universal fallback. - The shipped runtime.js runs inlined wasm-feature-detect probes (relaxed-simd, simd, tail-call, bulk-memory, exception-handling, threads), picks the first variant whose probes all pass, and falls back to the single baked CRAFTER_WASM_URL when no manifest is present (backward compatible). - EnableWasiRelaxedSimdVariant registers the relaxed-SIMD variant — the motivating case (Chrome 114+/Firefox 120+ enable it by default; Safari still flag-gates it as of mid-2026). Verified end to end: a wasm32-wasip1 build emits both wasi-hello.wasm and wasi-hello.relaxed-simd.wasm + variants.json; Firefox selects the relaxed-simd variant and runs it. Resolves #24 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 15:14:18 +00:00
// variants.json manifest includes it. A no-op for non-wasm targets at build
// time (no wasm is produced), but harmless to declare unconditionally.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
void EnableWasiRelaxedSimdVariant(Configuration& cfg);
feat: feature-detected browser-wasm variants (relaxed-SIMD) + variant-aware runtime The browser wasm pipeline hardcoded -msimd128 for every wasm32 target and baked a single wasm URL into index.html, so newer codegen features that aren't yet baseline across engines (relaxed SIMD today; threads, future SIMD revisions later) couldn't be adopted without dropping the browsers that lack them. Add a general, feature-parameterized mechanism owned entirely by Crafter.Build: - Configuration::wasmVariants declares N codegen variants (label, extra -m flags, runtime probes). Build() compiles the baseline plus one outputName.<label>.wasm per variant, recompiling the whole graph (incl. dep libs + std PCM) with the variant's flags — relaxed-SIMD is per-TU codegen, not a link switch. wasmVariantFlags folds into VariantId so each variant's objects/PCMs land in their own build+bin dir. - EnableWasiBrowserRuntime emits a variants.json manifest (label -> url + probes), preferred-first with the baseline as the universal fallback. - The shipped runtime.js runs inlined wasm-feature-detect probes (relaxed-simd, simd, tail-call, bulk-memory, exception-handling, threads), picks the first variant whose probes all pass, and falls back to the single baked CRAFTER_WASM_URL when no manifest is present (backward compatible). - EnableWasiRelaxedSimdVariant registers the relaxed-SIMD variant — the motivating case (Chrome 114+/Firefox 120+ enable it by default; Safari still flag-gates it as of mid-2026). Verified end to end: a wasm32-wasip1 build emits both wasi-hello.wasm and wasi-hello.relaxed-simd.wasm + variants.json; Firefox selects the relaxed-simd variant and runs it. Resolves #24 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-15 15:14:18 +00:00
// View over the project's args with simple query helpers. Has(flag) for
// boolean switches; Get(prefix) for valued options (e.g. Get("--prefix=")
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
// returns the substring after the equals). Definitions are out-of-line so
// project.so resolves them from the executable: clang does not emit
// module-attached in-class inline bodies into consumers.
2026-04-30 02:20:19 +02:00
struct ArgQuery {
std::span<const std::string_view> args;
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
bool Has(std::string_view flag) const;
std::optional<std::string> Get(std::string_view prefix) const;
2026-04-30 02:20:19 +02:00
};
2026-04-29 18:59:01 +02:00
// Apply the framework's standard CLI args + env vars onto cfg:
// --debug cfg.debug = true
// --target=<triple> cfg.target = <triple>
// --march=<value> cfg.march = <value>
// --mtune=<value> cfg.mtune = <value>
feat(cuda): make the GPU architecture configurable, native by default nvcc ran with -arch=sm_89 for every build, which is code for that one architecture and its PTX, whatever GPU the program was for. Jorijn asked for the architecture to be configurable, and native when nothing sets it, as the CPU's is. cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc compiles for the GPUs it sees, and where it sees none it warns and uses its own default architecture. Like -march=native it is for a program that runs where it is built, since it carries no PTX, and `crafter-build bundle` warns of a bundle whose CUDA code, in the program or a library it is built on, is compiled for native, as it warns of -march=native. ApplyStandardArgs sets it from --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the parent's, as they give them its sysroot and debug flag; and ForceHostTooling gives host tooling the host's, as it gives it the host's march, since project.so runs it on the machine that loads it. A .cu is compiled again only when it is newer than its object, so the architecture keys VariantId, and so does the nvcc that compiles it, by what it is rather than where: Toolchain::nvccStamp, its canonical path, size and time, read without a process, changes when CUDA_PATH names another toolkit and when an update replaces the one at the same path, as a package does at /opt/cuda. native is keyed as well, by Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose and number them, each empty value apart from an unset one, read without a process. It is crafter-build's reading of the machine, not nvcc's. The word alone would keep an object compiled for a GPU the machine no longer has, after a GPU change or on another machine that shares the checkout, and that object carries no PTX for the GPU it has now, where sm_89's carried its PTX. Only a configuration with CUDA sources is keyed, so every other one keeps the directory it had, but for one built with --cuda-arch=, which was a project argument, hashed as one, and is crafter-build's own now.
2026-11-11 19:34:52 +01:00
// --cuda-arch=<value> cfg.cudaArch = <value>
2026-04-30 02:20:19 +02:00
// --lib cfg.type promoted Executable → LibraryStatic
// --shared cfg.type promoted LibraryStatic → LibraryDynamic
feat: lay an executable out as the files/ of a Flatpak A Linux executable built by the Flatpak crafter-build links the libc++, libc++abi and libunwind in its /app/lib and the Sdk's glibc, so it runs inside crafter-build's sandbox and practically nowhere else: a host needs glibc 2.38 or newer and all three LLVM libraries, which not even Arch has. A program built here is meant to run in a Flatpak, so it can now be laid out as one: with cfg.packaging = Packaging::Flatpak, or --packaging=flatpak where the project.cpp crafter-build was pointed at calls ApplyStandardArgs, its BinDir() holds files/, what becomes /app in the app's sandbox, and -r runs the program there against the libraries the app carries. The program is linked into files/bin, where its shaders, files and assets land too (ProgramDir()), with $ORIGIN/../lib as its one run path, and the new :Flatpak partition writes the rest of files/: files/lib with the LLVM runtime libraries, located one by one through clang, and whatever else the program needs, read with llvm-readelf, that the directories of the shared libraries it is built on hold, the ones an unpackaged link records as run paths, or the toolchain's own lib dir, /app/lib in crafter-build's Flatpak, which the link searches too; and the desktop entry, metainfo and icons under the app-id in files/share, the entry refused when its Icon= is not the app-id or desktop-file-validate, where there is one, rejects it, and an icon that is not an .svg or a square .png. The metadata and export/ of a build directory are flatpak build-finish's to write, and crafter-build keeps no copy of its rules: what a permission means and what the host sees of an app change with flatpak's releases, and a copy would have to follow every one. The writer copies a file only when its content differs, compared a block at a time so that a large file costs no more memory than a small one, and writes one only when what it would write differs, never deciding by an mtime, which ostree sets to 0 for every file of /app, and works the program's libraries out on every write, which reads only their dynamic sections, since a library replaced in place, as by a toolchain update, can need others, which FlatpakLibraryChange checks; it prunes from files/bin each top-level entry an earlier build put there and this one does not, reporting those the program wrote there itself. What cannot be a Flatpak is refused before anything is built, saying why: a Windows or wasm executable, a build against a sysroot or for musl, another architecture than the runtime's, a build against CRAFTER_BUILD_LIBCXX_DIR, whose libc++ the Flatpak would not carry, and a build by a native crafter-build, which links the host's glibc: a native process knows no Flatpak runtime, from /.flatpak-info, unless CRAFTER_BUILD_FLATPAK_INFO, the tests' hook, names a file with one. Default stays the executable as linked for now, RunTests runs every test as linked, whatever its Configuration asks for, and RunLint works out its compile command so, and a forwarded --packaging= leaves a dependency's executables alone, since consumers run them by path. A dependency that packages its own executable gets its desktop file, metainfo and icons rebased by the loader as its cfg.files are, so they are its own whatever directory the consumer builds from. Only a Flatpak is keyed into VariantId, so every other configuration keeps its directory, but for one given --packaging=, which was a project arg, hashed into VariantId, and is a standard arg now, a dependency's included. The app-id and what a Flatpak is installed as are not keyed: they change files/share, never what is compiled. The asset name map, kept three times, twice in Build() and once for the browser runtime's files.json, is one function now, CompressedAssetName; CompressAsset, in Crafter.Build-Asset.cpp, keeps the list of the extensions it loads, which has to agree with it. Each copy a Flatpak build makes into the program's directory, of its shaders, assets, cfg.files and what its dependencies forward, records the top-level name it places there, the names of what a directory holds for one copied into it itself ("data/", "data/."), and those are what the writer keeps in files/bin; a build that fails after copying adds them to the writer's record all the same, so the next write removes what no build places any more. SharedLibraryRuns now also packages its program as a Flatpak, whose files/lib has to carry libgreet.so for it to start.
2026-11-01 19:20:55 +01:00
// --packaging=<kind> cfg.packaging = None or Flatpak (none, flatpak),
// in the project crafter-build was pointed at only:
// a dependency loaded with the same args keeps its
// executables as they are, since its consumers run
// them by path
2026-04-30 02:20:19 +02:00
// Promotions chain in priority order so `--lib --shared` lands on
// LibraryDynamic regardless of arg order; each is a no-op when the
// baseline doesn't match (e.g. --shared on an Executable, or --lib on a
// pre-set library).
feat(cuda): make the GPU architecture configurable, native by default nvcc ran with -arch=sm_89 for every build, which is code for that one architecture and its PTX, whatever GPU the program was for. Jorijn asked for the architecture to be configurable, and native when nothing sets it, as the CPU's is. cfg.cudaArch is nvcc's -arch now, and it defaults to "native": nvcc compiles for the GPUs it sees, and where it sees none it warns and uses its own default architecture. Like -march=native it is for a program that runs where it is built, since it carries no PTX, and `crafter-build bundle` warns of a bundle whose CUDA code, in the program or a library it is built on, is compiled for native, as it warns of -march=native. ApplyStandardArgs sets it from --cuda-arch= and CRAFTER_BUILD_CUDA_ARCH as it sets march from --march= and CRAFTER_BUILD_MARCH; AddTest and AddMarchVariants give their tests the parent's, as they give them its sysroot and debug flag; and ForceHostTooling gives host tooling the host's, as it gives it the host's march, since project.so runs it on the machine that loads it. A .cu is compiled again only when it is newer than its object, so the architecture keys VariantId, and so does the nvcc that compiles it, by what it is rather than where: Toolchain::nvccStamp, its canonical path, size and time, read without a process, changes when CUDA_PATH names another toolkit and when an update replaces the one at the same path, as a package does at /opt/cuda. native is keyed as well, by Toolchain::cudaNativeKey: the NVIDIA display devices sysfs lists, by PCI address and device ID, and CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER, which choose and number them, each empty value apart from an unset one, read without a process. It is crafter-build's reading of the machine, not nvcc's. The word alone would keep an object compiled for a GPU the machine no longer has, after a GPU change or on another machine that shares the checkout, and that object carries no PTX for the GPU it has now, where sm_89's carried its PTX. Only a configuration with CUDA sources is keyed, so every other one keeps the directory it had, but for one built with --cuda-arch=, which was a project argument, hashed as one, and is crafter-build's own now.
2026-11-11 19:34:52 +01:00
// $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE / $CRAFTER_BUILD_CUDA_ARCH
// seed march/mtune/cudaArch.
2026-04-29 18:59:01 +02:00
// Env applies first, then args, so CLI wins over env wins over caller's
2026-04-30 02:20:19 +02:00
// pre-set defaults. Returns an ArgQuery over the same span so projects
// can query their own flags (`--timing`, ...) without re-rolling the
// for-arg-in-args loop.
refactor: drop Windows host support crafter-build is moving to a single Flatpak distribution, and there is no Windows host in that picture: no build.cmd, no MSVC or mingw host build, no DLL plus launcher. Delete every host-Windows path instead of leaving it to rot unverified: the cmd.exe command runner and quoting, the LOCALAPPDATA cache, the MSVC and mingw-host LoadProject variants with their LIBCXX_DIR and CRAFTER_MINGW_DIR plumbing, the winsock port probe, the LoadLibrary libclang loader, the console-width and isatty shims, and the preprocessor guards around the Linux bodies. The x86_64-w64-mingw32 cross-compile target stays. It is target logic (output names, -femulated-tls, the libstdc++ link extras, copying a dependency DLL next to a mingw exe, wine as the runner) and did not depend on any of the removed code. The msvc target goes with the host that was the only thing able to use it. Three target-path warts fixed on the way: ExpectedOutput named a mingw static library <name>.lib while the archive step wrote lib<name>.a, so those libraries relinked on every run; the import lib is no longer copied next to a mingw exe, since the dependency's own bin dir is already on the link line; and llvm-ar now writes every archive, not only the LTO ones, so Debug and Release archives are made the same way. CRAFTER_API and Crafter.Build-Api.h existed only for the DLL boundary. Nothing downstream used them, so they are removed rather than kept as an empty macro nobody can verify. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-02 21:56:38 +02:00
ArgQuery ApplyStandardArgs(Configuration& cfg, std::span<const std::string_view> args);
2026-07-23 01:24:42 +02:00
}
feat(wasm): compile C++ with WebAssembly exception handling wasm builds were compiled with -fno-exceptions. A throw did not compile, libc++'s own throws (vector::at, std::format, filesystem) aborted the program, and code that relies on exceptions could not be built for the browser at all. Every wasm unit and the std module now get -fwasm-exceptions, and the link adds -lunwind, which code built that way calls into and the driver does not add. The flag also selects the libc++ under the sysroot's lib/<triple>/eh, which wasi-sdk 33 and later ship next to the noeh one. Those libraries use the standardized encoding (try_table, exnref) while LLVM 23 still emits the legacy one by default, which wasmtime refuses to load and which would put both in one binary, so the flags ask for the standard form with -wasm-use-legacy-eh=false. That makes the setjmp lowering loadable under wasmtime too. The flags live in one constant, WasmBaselineFlags, which the compile command and the std module both take through WasmCompileFlags: a BMI is refused by a unit whose exception setting differs from its own. VariantId and StdPcmDir hash it, so the first build after the update starts fresh instead of importing PCMs built without exceptions, and two releases sharing the Flatpak's cache don't take turns rebuilding one std PCM. A sysroot without the exception-enabled libraries stops the build with a line saying so, rather than at the link with "unable to find library -lunwind". The result needs an engine with exnref: Chrome 137, Firefox 131, Safari 18.4, the bundled wasmtime. The runtime's exception-handling probe tested the legacy encoding; it now tests try_table, every variants.json entry carries it, and a browser without it is told which feature it lacks instead of failing with a CompileError. There is no switch back to -fno-exceptions: engines without exnref are old enough not to keep a second build for them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:54:39 +01:00
namespace Crafter {
// WasmBaselineFlags followed by the active variant pass's
// wasmVariantFlags, each with a leading space: the wasm part of every
// compile command and of the std module's, which have to agree flag for
// flag.
std::string WasmCompileFlags(const Configuration& config);
fix(wasm): resolve the WASI sysroot where it is read, not in Build() A wasm32 configuration that names no sysroot is built against the toolchain's WASI sysroot. ApplyStandardArgs stores that sysroot in cfg.sysroot, for a project file that calls it. For a configuration whose project file sets the target itself, Build() stored it on its way in. VariantId hashes the sysroot, so such a configuration had one BuildDir, BinDir and PcmDir until its build started and others from then on. A build pass records each dependency's build under its PcmDir, and a configuration asks for a dependency by the PcmDir it has at that moment. A wasm32 library that two configurations of one pass are built on was recorded under the first directory for the one that asked first. One that asked after the library's build had started asked under the second directory, found nothing there, and built the library again. Configuration::ResolvedSysroot now gives what cfg.sysroot comes to: the toolchain's WASI sysroot for a wasm32 configuration that names none, cfg.sysroot as it stands for every other, as ResolvedPackaging gives what `packaging` comes to. VariantId, the std module's flags, key and source, the compile and link commands and the check that refuses a wasm build without a usable sysroot read it, and Build() no longer stores the sysroot in the configuration. ApplyStandardArgs still does: what a project file reads in cfg.sysroot after the call stays what it was. The directories a build writes keep their names: a configuration that named no sysroot was built into the ones its VariantId named once Build() had stored it, which are the ones it names now. StdPcmFlags takes the toolchain, as StdPcmKey does, so that a VariantId asked for under a toolchain resolves the sysroot under that one.
2026-11-14 23:42:47 +01:00
// The flags BuildStdPcm compiles the std module with under `toolchain`,
// after the base command and before the source, each with a leading
// space. StdPcmKey hashes the same string, so the command and the
// directory it writes to cannot disagree about what decides the BMI.
std::string StdPcmFlags(const Configuration& config, const Toolchain& toolchain);
feat(wasm): compile C++ with WebAssembly exception handling wasm builds were compiled with -fno-exceptions. A throw did not compile, libc++'s own throws (vector::at, std::format, filesystem) aborted the program, and code that relies on exceptions could not be built for the browser at all. Every wasm unit and the std module now get -fwasm-exceptions, and the link adds -lunwind, which code built that way calls into and the driver does not add. The flag also selects the libc++ under the sysroot's lib/<triple>/eh, which wasi-sdk 33 and later ship next to the noeh one. Those libraries use the standardized encoding (try_table, exnref) while LLVM 23 still emits the legacy one by default, which wasmtime refuses to load and which would put both in one binary, so the flags ask for the standard form with -wasm-use-legacy-eh=false. That makes the setjmp lowering loadable under wasmtime too. The flags live in one constant, WasmBaselineFlags, which the compile command and the std module both take through WasmCompileFlags: a BMI is refused by a unit whose exception setting differs from its own. VariantId and StdPcmDir hash it, so the first build after the update starts fresh instead of importing PCMs built without exceptions, and two releases sharing the Flatpak's cache don't take turns rebuilding one std PCM. A sysroot without the exception-enabled libraries stops the build with a line saying so, rather than at the link with "unable to find library -lunwind". The result needs an engine with exnref: Chrome 137, Firefox 131, Safari 18.4, the bundled wasmtime. The runtime's exception-handling probe tested the legacy encoding; it now tests try_table, every variants.json entry carries it, and a browser without it is told which feature it lacks instead of failing with a CompileError. There is no switch back to -fno-exceptions: engines without exnref are old enough not to keep a second build for them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 05:54:39 +01:00
}