Crafter.Build/interfaces/Crafter.Build-Clang.cppm
Jorijn van der Graaf 4283a3ecd2
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

990 lines
56 KiB
C++

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Crafter.Build:Clang;
import std;
import :Shader;
import :Interface;
import :Implementation;
import :External;
import :Toolchain;
import :Agents;
import :Flatpak;
namespace fs = std::filesystem;
namespace Crafter {
// 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.
//
// -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
// 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"});
}
export namespace Crafter {
struct BuildResult {
std::string result;
bool repack;
// 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;
// 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;
// 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.
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
// 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;
};
struct Define {
std::string name;
std::string value;
};
// 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
// 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.
struct WasmVariant {
std::string label;
std::vector<std::string> flags;
std::vector<std::string> probes;
};
enum class ConfigurationType {
Executable,
LibraryStatic,
LibraryDynamic,
};
// 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(); }
static TestRunner Local();
// Prefix runner: wraps the local binary in `<command> {bin} {args}`.
// Used for qemu-user, wasmtime, and similar single-binary wrappers.
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.
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.
static TestRunner FromEnv(std::string_view target, TestRunner fallback = Local());
// Derive a runner from a Configuration's target triple + sysroot.
// Returns Local() when target equals the host, Wine() for Windows
// targets, `qemu-<arch>` (with QEMU_LD_PREFIX
// 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.
static TestRunner ForTarget(const struct Configuration& cfg);
};
enum class TestOutcome { Pass, Fail, Crash, Timeout, Skipped };
struct TestResult {
std::string name;
TestOutcome outcome = TestOutcome::Pass;
std::int32_t exitCode = 0;
std::int32_t signal = 0;
std::chrono::milliseconds duration{0};
std::string output;
};
// 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;
};
// 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
};
// 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
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.
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.
// ---- 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;
// 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;
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
};
// Per-file view handed to each LintRule's check callback. Every member
// 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).
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'
std::string Extension() const; // ".cppm", ".cpp", ".h", ...
std::string_view Line(std::size_t n) const; // 1-based; empty if out of range
// `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.
const std::string& CommentStripped();
// Record a finding at `line` (1-based; pass 0 for a whole-file finding).
void Report(std::size_t line, std::string message);
// 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.
void SetContent(std::string newContent);
// 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.
bool Suppressed(std::string_view rule, std::size_t line);
// 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.
std::span<const LintToken> Tokens();
// The token's own bytes: content.substr(tok.offset, tok.length).
std::string_view TokenText(const LintToken& token) const;
// 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.
std::span<const LintToken> TokensOnLine(std::size_t line);
// True when a comment token starts on `line`. Replaces `Line(n).contains("//")`,
// which false-positives on a `//` inside a string literal.
bool LineHasComment(std::size_t line);
// 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.
bool LineHasMultiLineToken(std::size_t line);
// 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.
std::span<const LintDecl> Decls();
bool AstAvailable();
// Why AstAvailable() is false — a missing PCM, a parse error, a file
// that is not a translation unit. Empty when the AST is available.
std::string_view AstUnavailableReason();
// 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;
std::optional<std::vector<LintToken>> tokenCache;
// Per-line flag, 0-based, for LineHasMultiLineToken. Derived from
// tokenCache and invalidated with it.
std::optional<std::vector<bool>> spannedLineCache;
// 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;
};
// 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;
// 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;
};
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);
// What a Script's callback is handed when `crafter-build run <name>`
// starts it.
struct ScriptContext {
// 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.
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;
};
// The host target triple: what the resolved toolchain's clang++ prints
// for -print-target-triple (see GetToolchain). Used as the default for
// Configuration::target so projects don't have to hardcode it for the
// 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.
std::string HostTarget();
// 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);
struct Configuration {
fs::path path;
std::string outputName;
std::string name;
std::string march = "native";
std::string mtune = "native";
std::string target = HostTarget();
std::string sysroot;
bool debug = false;
ConfigurationType type = ConfigurationType::Executable;
// What the executable is delivered as (see Packaging).
// ApplyStandardArgs sets it from --packaging=none|flatpak.
Packaging packaging = Packaging::Default;
// 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.
FlatpakApp flatpak;
std::vector<std::unique_ptr<Module>> interfaces;
std::vector<Implementation> implementations;
std::vector<fs::path> cFiles;
std::vector<fs::path> cuda;
// 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";
std::vector<Configuration*> dependencies;
std::vector<fs::path> files;
// 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;
std::vector<Define> defines;
std::vector<Shader> shaders;
// 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.
std::vector<fs::path> assets;
std::vector<ExternalDependency> externalDependencies;
std::vector<std::string> compileFlags;
std::vector<std::string> linkFlags;
// 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;
// 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.
std::vector<std::string> projectArgs;
std::vector<Test> tests;
// Lint rules for `crafter-build lint`. Populate via AddLintRule.
std::vector<LintRule> lintRules;
// 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;
// Which dependencies' AGENTS.consumer.md `crafter-build` and
// `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):
// cfg.dependencyNotes = DependencyNotes::Direct;
// Only read on the Configuration project.cpp returns; a dependency's
// 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.
DependencyNotes dependencyNotes = DependencyNotes::Transitive;
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.
void ResolvePendingImports();
// Declare a test. Sources default to `tests/<name>/main.cpp` resolved
// against this Configuration's path; target/march/mtune/sysroot/debug
// 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.
struct TestBuilder AddTest(std::string_view name);
// 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.
struct TestBuilder AddTest(std::string_view name, std::span<fs::path> interfaces);
// 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>`.
void AddMarchVariants(std::string_view name, std::span<fs::path> interfaces, std::span<const struct MarchTier> tiers);
// 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.
void AddLintRule(std::string name, std::function<void(LintContext&)> check);
// 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.
void AddAstLintRule(std::string name, std::function<void(LintContext&)> check);
// 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
// toolchain, the GPU architecture and the nvcc of CUDA sources)
// 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 {
std::string compileKey;
compileKey += std::to_string(static_cast<std::int32_t>(type));
compileKey += '|';
compileKey += debug ? '1' : '0';
compileKey += '|';
compileKey += ResolvedSysroot(toolchain);
for (const Define& d : defines) {
compileKey += "|D:";
compileKey += d.name;
compileKey += '=';
compileKey += d.value;
}
for (const std::string& f : compileFlags) {
compileKey += "|F:";
compileKey += f;
}
// 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;
}
// 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);
// 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;
}
compileKey += "|T:";
compileKey += toolchain.Key();
// 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;
}
}
// 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";
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
// 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;
}
// 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;
}
fs::path PcmDir() const {
return type == ConfigurationType::Executable ? BuildDir() : BinDir();
}
};
struct Test {
Configuration config;
TestRunner runner;
std::chrono::seconds timeout{60};
std::vector<std::string> args;
// 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.
fs::path StdPcmDir(const Configuration& config);
// 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.
fs::path ExpectedOutput(const Configuration& config);
// `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);
// 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;
// -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;
// ThinLTO is on: objects hold bitcode, so archiving needs llvm-ar.
bool useLto = false;
fs::path stdPcmDir;
fs::path pcmDir;
};
CompileCommand GetCompileCommand(const Configuration& config);
// 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.
BuildResult Build(Configuration& config, std::unordered_map<fs::path, std::shared_future<BuildResult>>& depResults, std::mutex& depMutex);
// 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);
// 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
std::int32_t Run(std::int32_t argc, char** argv);
// 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.
std::vector<fs::path> CleanProject(const fs::path& projectFile);
// 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
// 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).
void EnableWasiBrowserRuntime(Configuration& cfg);
// 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
// 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
// variants.json manifest includes it. A no-op for non-wasm targets at build
// time (no wasm is produced), but harmless to declare unconditionally.
void EnableWasiRelaxedSimdVariant(Configuration& cfg);
// View over the project's args with simple query helpers. Has(flag) for
// boolean switches; Get(prefix) for valued options (e.g. Get("--prefix=")
// 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.
struct ArgQuery {
std::span<const std::string_view> args;
bool Has(std::string_view flag) const;
std::optional<std::string> Get(std::string_view prefix) const;
};
// 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>
// --cuda-arch=<value> cfg.cudaArch = <value>
// --lib cfg.type promoted Executable → LibraryStatic
// --shared cfg.type promoted LibraryStatic → LibraryDynamic
// --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
// 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).
// $CRAFTER_BUILD_MARCH / $CRAFTER_BUILD_MTUNE / $CRAFTER_BUILD_CUDA_ARCH
// seed march/mtune/cudaArch.
// Env applies first, then args, so CLI wins over env wins over caller's
// 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.
ArgQuery ApplyStandardArgs(Configuration& cfg, std::span<const std::string_view> args);
}
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);
// 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);
}