diff --git a/.forgejo/workflows/ci.yaml b/.forgejo/workflows/ci.yaml index dcdff57..ec1a47a 100644 --- a/.forgejo/workflows/ci.yaml +++ b/.forgejo/workflows/ci.yaml @@ -1,52 +1,37 @@ name: Flatpak -# One job, two outcomes: -# pull request, manual run -> build the Flatpak and run the suite inside it -# pushed tag X.Y.Z -> also release the build: publish it as the -# `stable` branch of the Catcrafts repo and -# create release X.Y.Z -# -# A release is a tag that the owner makes and signs locally and pushes with -# the master it releases; a push to master without one runs nothing. The tag -# names the version, and the metainfo's newest entry has to be that -# version: its description is the release notes. +# One job, three outcomes: +# pull request -> build the Flatpak and run the suite inside it +# push master -> also publish the result as the `beta` branch of the +# Catcrafts repo and refresh the rolling `latest` release +# tag X.Y.Z -> publish as `stable` and create release X.Y.Z # # The `crafter-flatpak` runner label is the privileged runner on the Hetzner # box (bubblewrap needs it) with four volumes allowed: the Sdk install, the # flatpak-builder state (ccache and the LLVM module, so only crafter-build # itself rebuilds on a normal run), the published repo's web root, and the # repo signing key, which lives on the runner host and never in the forge. -# No other runner carries that label. Plain `flatpak` is the label of the -# organisation's runner, which serves every Catcrafts repository and also -# mounts the web root and the key, for Crafter.Review's publish job, so any -# job it runs can mount them (AGENTS.template.md, CI and publishing). +# No other runner carries that label. Plain `flatpak` also matches the +# organisation's runner, which mounts none of those volumes; a job it picks +# up fails before building anything. on: pull_request: branches: [master] push: + branches: [master] # Bare semver tags. Spelled with globs so it means the same whether the - # forge reads it as a workflow pattern or as a plain glob. + # forge reads it as a workflow pattern or as a plain glob; `latest`, the + # rolling tag this workflow moves itself, does not start with a digit. tags: ['[0-9]*.[0-9]*.[0-9]*'] workflow_dispatch: -# Pushes are tags only, so every release run is in one group, and a release -# starts only once the one before it has finished. A pull request's group -# also holds its number, which only a pull request's event carries, so a -# new push to it cancels its own outdated run and no other. -concurrency: - group: flatpak-${{ github.event_name }}-${{ github.event.pull_request.number }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - env: APP_ID: net.catcrafts.CrafterBuild - BRANCH: stable MANIFEST: packaging/flatpak/net.catcrafts.CrafterBuild.yaml CI_MANIFEST: packaging/flatpak/ci-manifest.yaml RUNTIME: org.freedesktop.Sdk//26.08 REPO_DIR: /srv/flatpak/repo WEB_DIR: /srv/flatpak - # A release tag carries a signature Forgejo verifies for this address. - RELEASE_SIGNER: jorijnvdgraaf@catcrafts.net jobs: flatpak: @@ -60,12 +45,11 @@ jobs: -v /etc/crafter-flatpak:/run/crafter-flatpak:ro steps: - name: Install tools - # util-linux: flock, for the Publish step. run: | pacman-key --init pacman-key --populate archlinux pacman -Sy --noconfirm --needed archlinux-keyring - pacman -Syu --noconfirm --needed flatpak flatpak-builder ccache git nodejs jq gnupg go-yq ostree python util-linux + pacman -Syu --noconfirm --needed flatpak flatpak-builder ccache git nodejs jq gnupg go-yq ostree python git config --global --add safe.directory '*' - name: Sdk @@ -76,137 +60,40 @@ jobs: flatpak update -y --noninteractive - name: Checkout - # Every branch and tag, for git describe and the release checks; no - # step pushes, so the token is not kept in the checkout. uses: actions/checkout@v4 with: fetch-depth: 0 - persist-credentials: false + persist-credentials: true - - name: Version + - name: Version and channel id: meta run: | set -eu - # The metainfo's newest entry is its first element, the - # one parse that gives both its version and the release notes, - # before anything is built: a comment or another attribute order - # would mislead a text search, and an entry whose notes render - # empty stops the run here. The notes go to release-notes.md, for - # the release page, as Markdown. AppStream has no headings, so a - # paragraph that introduces a list is one:

New

- # comes out as "## New" over its items, the shape the notes take - # since 3.0.0. A paragraph on its own stays a paragraph, as the - # older entries are written. and get their Markdown - # spelling; a code span also keeps text such as lib//eh - # from being read as an HTML tag by the forge. - newest=$(python3 - <<'EOF' - import sys - import xml.etree.ElementTree as ET - - release = ET.parse("packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml").getroot().find("releases/release") - desc = None if release is None else release.find("description") - - def text(el): - parts = [el.text or ""] - for child in el: - inner = text(child) - parts.append({"em": f"*{inner}*", "code": f"`{inner}`"}.get(child.tag, inner)) - parts.append(child.tail or "") - return " ".join("".join(parts).split()) - - blocks = [] if desc is None else list(desc) - out = [] - for i, el in enumerate(blocks): - heads_list = i + 1 < len(blocks) and blocks[i + 1].tag in ("ul", "ol") - if el.tag == "p": - out.append(f"## {text(el)}" if heads_list else text(el)) - elif el.tag == "ul": - out.append("\n".join(f"- {text(li)}" for li in el)) - elif el.tag == "ol": - out.append("\n".join(f"{n}. {text(li)}" for n, li in enumerate(el, 1))) - notes = "\n\n".join(out) - if not notes.strip(): - sys.exit("the metainfo needs a at the top of whose renders release notes") - with open("release-notes.md", "w") as f: - print(notes, file=f) - print(release.get("version", "")) - EOF - ) - if [ "$GITHUB_EVENT_NAME" = push ]; then - # A release: the only pushes this workflow runs for are tags. - # The tag is the version; it has to be annotated, signed by the - # owner as Forgejo verifies it against the keys its users added, - # on master, newer than every published release, and the version - # of the metainfo's newest entry. The tag itself is read from the - # forge: the checkout fetches a pushed tag again as a plain ref - # to its commit, so the local one is never the annotated tag. - version=$GITHUB_REF_NAME - if ! printf '%s\n' "$version" | grep -qxE '[0-9]+\.[0-9]+\.[0-9]+'; then - echo "the tag $version is not a version of the form X.Y.Z" >&2 - exit 1 - fi - api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY" - tag=$(curl -sSf "$api/tags/$version") - object=$(printf '%s' "$tag" | jq -r .id) - commit=$(printf '%s' "$tag" | jq -r .commit.sha) - if [ "$commit" != "$GITHUB_SHA" ]; then - echo "the forge has the tag $version on $commit, not on this run's commit $GITHUB_SHA" >&2 - exit 1 - fi - if [ "$object" = "$commit" ]; then - echo "$version is a lightweight tag; a release tag is annotated and signed: git tag -s $version -m 'crafter-build $version'" >&2 - exit 1 - fi - # Forgejo verifies a signed tag's own signature, and for an - # unsigned one falls back to its commit's, so the verdict also - # has to cover the tag's payload, not the commit's. - signed=$(curl -sSf "$api/git/tags/$object" | - jq -r --arg c "$commit" --arg v "$version" '"\(.verification.verified) \(.verification.signer.email // "") \(.verification.payload // "" | startswith("object \($c)\ntype commit\ntag \($v)\n"))"') - if [ "$signed" != "true $RELEASE_SIGNER true" ]; then - echo "Forgejo does not verify the tag $version itself as signed by $RELEASE_SIGNER (verified, signer, over the tag's payload: $signed)" >&2 - exit 1 - fi - if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/master; then - echo "the tag $version is on $(git rev-parse --short "$GITHUB_SHA"), which is not on master: push the tag with the master it releases" >&2 - exit 1 - fi - # Newer than every release the forge has published, its own - # included, and not every tag: a later tag whose run still - # queues behind this one has no release yet, and a tag that is - # no X.Y.Z version never gets one. - for t in $(git tag --list | awk '/^[0-9]+\.[0-9]+\.[0-9]+$/' | sort -V); do - [ "$(printf '%s\n%s\n' "$t" "$version" | sort -V | tail -n 1)" = "$t" ] || continue - code=$(curl -s -o /dev/null -w '%{http_code}' "$api/releases/tags/$t") - case "$code" in - 404) ;; - 200) - if [ "$t" = "$version" ]; then - echo "$version is released already; to re-run after a release left half made, delete that release first" >&2 - else - echo "$version is not newer than the release $t" >&2 - fi - exit 1 ;; - *) echo "the forge answered $code when asked whether $t is released" >&2; exit 1 ;; - esac - done - if [ "$newest" != "$version" ]; then - echo "the metainfo's newest release is \"$newest\", but the tag is $version: the tagged commit needs the entry for $version at the top of packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml" >&2 + if [ "${GITHUB_REF_TYPE}" = tag ]; then + version="$GITHUB_REF_NAME" + branch=stable + # The metainfo's newest release is the release notes and must be + # the version being tagged. + top=$(grep -m1 -oP '&2 exit 1 fi else - # Nothing is published. The build names itself after the - # release it follows, the way a local checkout does: - # 5.0.0-3-g21746b1 is three commits past 5.0.0. Before the first - # tag there is nothing to describe from and the bare hash gets a - # placeholder in front. - described=$(git describe --tags --always) + # A master build names itself after the release it follows, the + # way a local checkout does: 2.0.0-3-g21746b1 is three commits + # past 2.0.0. Before the first tag there is nothing to describe + # from and the bare hash gets a placeholder in front. + described=$(git describe --tags --always --exclude=latest) case "$described" in [0-9]*.[0-9]*.[0-9]*) version="$described" ;; *) version="0.0.0-dev+$described" ;; esac + branch=beta fi echo "version=$version" >> "$GITHUB_OUTPUT" - echo "version $version" + echo "branch=$branch" >> "$GITHUB_OUTPUT" + echo "version $version, flatpak branch $branch" - name: Build # The manifest is rewritten beside the original so its relative @@ -219,7 +106,7 @@ jobs: grep -n 'CRAFTER_BUILD_VERSION' "$CI_MANIFEST" flatpak-builder --force-clean --ccache --disable-rofiles-fuse \ --state-dir=/root/.cache/flatpak-builder \ - --repo=repo --default-branch="$BRANCH" \ + --repo=repo --default-branch="${{ steps.meta.outputs.branch }}" \ build-dir "$CI_MANIFEST" - name: Smoke test @@ -227,16 +114,18 @@ jobs: flatpak-builder --run build-dir "$CI_MANIFEST" crafter-build --version flatpak-builder --run build-dir "$CI_MANIFEST" sh -c 'cd examples/hello-world && crafter-build && ls bin/*/hello*' - # Everything below releases the build and runs only for a pushed tag. + # Everything below publishes and only runs on master and on tags. - name: Bundle - if: github.event_name == 'push' + if: github.event_name != 'pull_request' run: | mkdir -p dist - flatpak build-bundle repo "dist/crafter-build-${{ steps.meta.outputs.version }}.flatpak" "$APP_ID" "$BRANCH" + flatpak build-bundle repo "dist/crafter-build-${{ steps.meta.outputs.version }}.flatpak" "$APP_ID" "${{ steps.meta.outputs.branch }}" + cp packaging/flatpak/net.catcrafts.CrafterBuild.flatpakref dist/ + (cd dist && sha256sum * > SHA256SUMS) ls -la dist - name: Upload bundle - if: github.event_name == 'push' + if: github.event_name != 'pull_request' uses: actions/upload-artifact@v3 with: name: crafter-build-${{ steps.meta.outputs.version }} @@ -244,24 +133,19 @@ jobs: if-no-files-found: error - name: Publish to the Catcrafts repo - if: github.event_name == 'push' + if: github.event_name != 'pull_request' run: | set -eu # The signing key is generated once on the runner host # (/etc/crafter-flatpak: signing-key.asc and key-id) and mounted # read-only; it is imported into a throwaway keyring per run. if [ ! -s /run/crafter-flatpak/signing-key.asc ] || [ ! -s /run/crafter-flatpak/key-id ]; then - echo "no signing key under /etc/crafter-flatpak on the runner host; generate it as described in AGENTS.template.md (CI and publishing)" >&2 + echo "no signing key under /etc/crafter-flatpak on the runner host; generate it as described in AGENTS.md (CI and publishing)" >&2 exit 1 fi export GNUPGHOME=$(mktemp -d) gpg --batch --quiet --import /run/crafter-flatpak/signing-key.asc FLATPAK_GPG_KEY_ID=$(cat /run/crafter-flatpak/key-id) - # Crafter.Review's workflow publishes into the same repo and holds - # this lock while it does, so a commit and the summary update of - # one workflow never interleave with the other's. - exec 9> "$WEB_DIR/.publish.lock" - flock 9 # The live repo is the canonical copy; builds are promoted into it, # never built into it. # Keyed on the repo's config file, not the directory: the web root @@ -269,49 +153,81 @@ jobs: [ -f "$REPO_DIR/config" ] || ostree init --repo="$REPO_DIR" --mode=archive flatpak build-commit-from --src-repo=repo \ --gpg-sign="$FLATPAK_GPG_KEY_ID" --gpg-homedir="$GNUPGHOME" \ - "$REPO_DIR" "app/$APP_ID/x86_64/$BRANCH" - # Every push to master used to be published as `beta`. Its last - # build is marked end-of-life, once, so that the next - # `flatpak update` of a beta installation says why nothing follows. - # The reason names the branch: with --noninteractive, flatpak's - # message names only the app. - beta="app/$APP_ID/x86_64/beta" - if ostree rev-parse --repo="$REPO_DIR" "$beta" >/dev/null 2>&1 && - ! ostree show --repo="$REPO_DIR" --print-metadata-key=ostree.endoflife "$beta" >/dev/null 2>&1; then - flatpak build-commit-from --src-ref="$beta" \ - --end-of-life="The beta branch gets no more updates: every change now comes as a release on the stable branch. Install stable with flatpak install catcrafts net.catcrafts.CrafterBuild//stable, then remove beta with flatpak uninstall net.catcrafts.CrafterBuild//beta." \ - --gpg-sign="$FLATPAK_GPG_KEY_ID" --gpg-homedir="$GNUPGHOME" \ - "$REPO_DIR" "$beta" - fi + "$REPO_DIR" "app/$APP_ID/x86_64/${{ steps.meta.outputs.branch }}" flatpak build-update-repo --gpg-sign="$FLATPAK_GPG_KEY_ID" --gpg-homedir="$GNUPGHOME" \ --generate-static-deltas --prune "$REPO_DIR" # The repo description and the app ref carry the public key. key=$(gpg --export "$FLATPAK_GPG_KEY_ID" | base64 --wrap=0) sed "s|GPGKey=.*|GPGKey=$key|" packaging/flatpak/catcrafts.flatpakrepo > "$WEB_DIR/catcrafts.flatpakrepo" sed "s|GPGKey=.*|GPGKey=$key|" packaging/flatpak/net.catcrafts.CrafterBuild.flatpakref > "$WEB_DIR/net.catcrafts.CrafterBuild.flatpakref" - flock -u 9 - # The release attaches this .flatpakref, not the one in the - # checkout: that one has a placeholder where the key goes, and - # flatpak cannot install from it. - cp "$WEB_DIR/net.catcrafts.CrafterBuild.flatpakref" dist/ - (cd dist && sha256sum * > SHA256SUMS) - ls -la dist - - name: Publish release - if: github.event_name == 'push' - # The notes are release-notes.md, which the Version step wrote. No - # `override`: it would delete a tag that has moved off this commit - # since the Version step and tag the old commit instead. Without it - # the action refuses such a tag, and a release that an earlier - # attempt left half made, such as a draft whose upload failed, has - # to be deleted before a re-run. + - name: Rolling 'latest' release + if: github.event_name != 'pull_request' && github.ref_type != 'tag' + run: | + git config user.email "ci@catcrafts.net" + git config user.name "Crafter Build CI" + git tag -f latest + git push origin latest --force + - name: Publish rolling 'latest' release + if: github.event_name != 'pull_request' && github.ref_type != 'tag' uses: https://code.forgejo.org/actions/forgejo-release@v2 with: direction: upload url: ${{ github.server_url }} repo: ${{ github.repository }} - tag: ${{ steps.meta.outputs.version }} - title: crafter-build ${{ steps.meta.outputs.version }} + tag: latest + title: Latest master build + prerelease: true + override: true + release-dir: dist + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Release notes + if: github.ref_type == 'tag' + run: | + # The newest block's description as Markdown, for the + # release page. AppStream has no headings, so a paragraph that + # introduces a list is one:

New

    ...
comes out as + # "## New" over its items, the shape the notes take since 3.0.0. + # A paragraph on its own stays a paragraph, as the older entries + # are written. and get their Markdown spelling; a code + # span also keeps text such as lib//eh from being read as + # an HTML tag by the forge. + python3 - > release-notes.md <<'EOF' + import xml.etree.ElementTree as ET + + desc = ET.parse("packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml").getroot().find("releases/release/description") + + def text(el): + parts = [el.text or ""] + for child in el: + inner = text(child) + parts.append({"em": f"*{inner}*", "code": f"`{inner}`"}.get(child.tag, inner)) + parts.append(child.tail or "") + return " ".join("".join(parts).split()) + + blocks = list(desc) + out = [] + for i, el in enumerate(blocks): + heads_list = i + 1 < len(blocks) and blocks[i + 1].tag in ("ul", "ol") + if el.tag == "p": + out.append(f"## {text(el)}" if heads_list else text(el)) + elif el.tag == "ul": + out.append("\n".join(f"- {text(li)}" for li in el)) + elif el.tag == "ol": + out.append("\n".join(f"{n}. {text(li)}" for n, li in enumerate(el, 1))) + print("\n\n".join(out)) + print("\nInstall:\n\n flatpak remote-add --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo\n flatpak install catcrafts net.catcrafts.CrafterBuild\n") + EOF + - name: Publish release + if: github.ref_type == 'tag' + uses: https://code.forgejo.org/actions/forgejo-release@v2 + with: + direction: upload + url: ${{ github.server_url }} + repo: ${{ github.repository }} + tag: ${{ github.ref_name }} + title: crafter-build ${{ github.ref_name }} release-notes-file: release-notes.md release-dir: dist token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index f92f1f1..67d2a68 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,3 @@ share/crafter-build/ .claude # written by CI next to the manifest so relative source paths still resolve packaging/flatpak/ci-manifest.yaml -# written by every build and test run from AGENTS.template.md -/AGENTS.md -.review-gates/push/ -.review-gates/trees/ diff --git a/.review-gates/config.json b/.review-gates/config.json deleted file mode 100644 index 115ee6c..0000000 --- a/.review-gates/config.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "base": "origin/master", - "rangeFrom": "upstream", - "authors": [ - "jorijnvdgraaf@catcrafts.net" - ], - "aiTrailers": "forbid", - "requireSigned": true, - "lenses": { - "repo-better-solution": { - "section": ".review-gates/lenses/repo-better-solution.md" - }, - "repo-bug-prover": { - "section": ".review-gates/lenses/repo-bug-prover.md" - }, - "repo-facts": { - "section": ".review-gates/lenses/repo-facts.md" - } - }, - "modes": { - "commits": { - "kind": "commits", - "lenses": [ - "repo-better-solution", - "repo-bug-prover", - "repo-facts" - ], - "effort": "xhigh" - } - }, - "gate0": [ - "./build.sh", - "./bin/crafter-build", - "./bin/crafter-build test", - "./bin/crafter-build format --check", - "./bin/crafter-build lint" - ] -} diff --git a/.review-gates/lenses/repo-better-solution.md b/.review-gates/lenses/repo-better-solution.md deleted file mode 100644 index 278b12f..0000000 --- a/.review-gates/lenses/repo-better-solution.md +++ /dev/null @@ -1,42 +0,0 @@ -## This repository: Crafter.Build - -A C++26 modules build system that builds itself. The stated design is -`README.md` (the manual) and `AGENTS.template.md` (the contributor guide; -`AGENTS.md` is written from it by a crafter-build build or test run, not -by `build.sh`, and is not in the tree). -Its "Design rules" and "Security considerations" are the owner's -decisions: a range that departs from one without saying so is a finding; -whether one should change is the owner's call, not a defect of the range. -Among them, for CI, which holds the workflow's token and the signing key -its runner mounts: no secret is added to the workflow, and the -environment is never echoed in it. - -The layers: the library (`interfaces/`, `implementations/`), which the -executable wraps and every `project.cpp` is compiled against; this -repository's own `project.cpp`; `build.sh`, the bootstrap that builds the -tool without the tool; the Flatpak (`packaging/flatpak/`), which bundles -the LLVM users build with; CI (`.forgejo/workflows/ci.yaml`). A target -difference branches on `cfg.target` at run time, never on the host; an -output path goes through `BinDir()`, `BuildDir()` or `PcmDir()`; whatever -changes what gets compiled or bundled reaches `VariantId()`. - -Search first: the partitions' own helpers (`RunBuildCommand`, -`RunCommandChecked`, `Progress::Diagnostic`, `ApplyStandardArgs`, -`HostTarget`, `GitProject`, `LocalProject`); the Crafter.* libraries the -tree already uses, cloned under `~/.cache/crafter.build/external/`; libc++ -and clang as the host installs them (`/run/host/usr/include/c++/v1`, -`/run/host/usr/lib/clang/`); git, cmake and flatpak-builder. - -Commit shape here: a fix, its test and its README change are separate -commits when each stands on its own, in that order, and a bug fix ships -with a test that fails before it. That split is not a later commit -repairing an earlier one. - -Compatibility: the `project.cpp` of every sibling repository beside this -checkout (`../Crafter.*/project.cpp`) and of every user compiles against -what `interfaces/` exports and is loaded by the binary; the CLI, the -`CRAFTER_BUILD_*` variables, the cache an older version left under -`~/.cache/crafter.build/` and the `bin/` layout CI globs are contracts too. -Users get master through releases on the Flatpak's `stable` branch. A -change an existing `project.cpp` does not survive is a -finding unless the range documents, in the README, what users must change. diff --git a/.review-gates/lenses/repo-bug-prover.md b/.review-gates/lenses/repo-bug-prover.md deleted file mode 100644 index 10b4f5f..0000000 --- a/.review-gates/lenses/repo-bug-prover.md +++ /dev/null @@ -1,63 +0,0 @@ -## This repository: Crafter.Build - -The execution contexts to enumerate, beside the charter's: -- `project.cpp` is compiled to a shared object and loaded into the running - crafter-build, resolving `Crafter::` symbols from the executable - (`--export-dynamic`); its static initialisers run at load. Its sibling - projects (`GitProject`, `LocalProject`) load the same way into the same - process, and its `#pragma crafter dependency` targets are built for the - host first, on every load. -- The clang++, clang and llvm-ar the tool spawns, and the git and cmake it - runs, are shell commands (`popen`, `std::system` in `:Platform`), many in - parallel; such a step fails on its exit code, never because it printed. - Running a test or a built artifact is a shell command too (`:Test`, - `:Clang`). A path, file name or flag that reaches one with a space or a - shell metacharacter in it is an input to attack. Other steps run inside - the process, among them glslang's shader compiles (`:Shader`), the - compression of an asset in Crafter.Asset, which starts threads of its own - (`:Asset`), and lint's parse through the libclang the linter dlopens - (`:Lint`). -- A build's steps run as jobs on the workers of `JobPool::Process()` - (`:Jobs`): up to as many threads as the machine has hardware threads, one - where that is one or unknown. The compiles of a configuration's stale - shaders, C, CUDA and C++ units, the compression of its stale assets, and - its copies of `cfg.files` and of the other files of an asset directory - go through the `JobGroup` of its `Build()`, which starts a job once the - jobs it was added after have finished; a `RunBuildCommand` waits for a - worker when its caller is not one. Jobs are waited for by threads that - are not workers, among them one that runs a `Build()` (its caller's, one - of `RunTests`', one of `BuildAll`'s, one a `Build()` starts per - dependency) and the one that loads a project file (`LoadConfigurations`, - `LoadProject`), for the compiles of the std module and of - `project.cpp`. The threads a `Build()` starts per external dependency are - not workers either and wait for no job: they run git and cmake. An - executable's copies of what its dependencies forward run on the thread of - its `Build()`. -- Several crafter-build processes share `~/.cache/crafter.build/` at once: - the std and Crafter.Build PCMs per target and march (the - `ConcurrentCacheRace` test), and the external clones with their `.lock` - files. -- Three builds of the tool: the bootstrap from `build.sh` (without - `CRAFTER_BUILD_HAS_ASSET`), the self-hosted binary on the host's LLVM, and - the Flatpak on its own LLVM under `/app`, in a sandbox whose `/usr` is the - Freedesktop SDK's. Their toolchains can be a release apart. -- Targets: the host triple, a sysroot (aarch64, musl), `x86_64-w64-mingw32` - under wine, `wasm32-wasi*` under wasmtime (or wasmer for `-r`), and - browser builds through the runtime in `wasi-runtime/`. -- Incremental builds: a first build, a rebuild after an edit, a rebuild - after a toolchain or flag change and a build after `clean` start from - different states; whatever changes what gets compiled has to reach - `VariantId()`, or a stale artifact is reused. -- Tests: each its own subprocess, in parallel, with a 60 s timeout. A test - that edits or touches files stages a copy under - `fs::temp_directory_path()`; one that only builds its fixture builds it in - place, into the fixture's own `bin/` and `build/` in the checkout. - -Semantics to read on disk rather than recall: libc++ and clang as the host -installs them (`/run/host/usr/include/c++/v1`, -`/run/host/usr/share/libc++/v1/std.cppm`, -`/run/host/usr/lib/clang//include`), the dependencies as cloned -(`~/.cache/crafter.build/external/-/`), the vendored -`lib/DirStackFileIncluder.h`. The Flatpak's own LLVM is not readable from -here: a semantic that may differ between LLVM releases is unverified for -the Flatpak build. diff --git a/.review-gates/lenses/repo-facts.md b/.review-gates/lenses/repo-facts.md deleted file mode 100644 index 7129581..0000000 --- a/.review-gates/lenses/repo-facts.md +++ /dev/null @@ -1,18 +0,0 @@ -## This repository: Crafter.Build - -- A claim that a tree passes `build.sh`, the self-host build, the test - suite, `format --check` or `lint` traces to the Gate 0 log among the - evidence paths INPUTS names: each command with its exit code and the sha - it ran at. A claim of a run anywhere else (the Flatpak through - `run flatpak`, CI, wine, qemu, node, a browser) traces to a capture of - that run that names the commit, or is unverifiable. -- A test a message names exists as a `cfg.AddTest("")` line in - `project.cpp` and a `tests//main.cpp` whose checks pin what the - message says. -- `AGENTS.md` is generated from `AGENTS.template.md` and the dependencies' - `AGENTS.consumer.md` and is not in the tree: a claim about it is checked - against those sources. -- A `` entry in - `packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml` is the - release notes users read: every sentence in it is a claim about the code - since the previous tag. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..1c445f4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,197 @@ +# AGENTS.md + +Guidance for coding agents and contributors working on crafter-build itself. The [README](README.md) is the user-facing manual; this file holds what you need to change the build system. When the two disagree, the code wins: check the interface in `interfaces/` and the `--help` output of the built binary. + +## Project overview + +crafter-build is a C++26 modules build system. A project is described by a `project.cpp` that returns a `Crafter::Configuration`; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own `project.cpp` builds crafter-build with crafter-build, and its tests link the library and drive `Build()` in-process. + +| Path | What lives there | +|---|---| +| `interfaces/Crafter.Build-.cppm` | Module interface partitions. `Crafter.Build.cppm` is the umbrella that re-exports them. | +| `implementations/Crafter.Build-.cpp` | Implementation units, one per partition, named `Crafter.Build:_impl`. `main.cpp` is a thin wrapper around `Crafter::Run`. | +| `project.cpp` | The self-host build description: a `crafter.build-lib` library, a `crafter.build-exe` executable, the test declarations, the lint rules and the `flatpak` and `install` scripts. | +| `tests//main.cpp` | One self-test per directory; `tests//fixture/` holds the sample project it builds. | +| `examples/` | Standalone user-facing projects, MIT licensed. | +| `build.sh` | Bootstrap script. It compiles everything by hand, without crafter-build. | +| `wasi-runtime/` | `runtime.js` and `index.html.in`, shipped for browser targets. | +| `lib/` | Vendored third-party headers (nlohmann/json, glslang's DirStackFileIncluder). Do not edit. | +| `share/crafter-build/`, `bin/`, `build/`, `lib/*.a` | Generated and gitignored. | +| `packaging/flatpak/`, `.forgejo/workflows/ci.yaml` | The Flatpak manifest with its metainfo, repo and ref files, and the Forgejo Actions CI that builds and publishes it. | + +Partitions and what they own: + +- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. +- `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types. +- `:Platform` runs commands, implements `LoadProject` (compile and load `project.cpp`), the host PCM cache, `#pragma crafter dependency`, and all OS-specific code. +- `:Interface` and `:Implementation` model module units, their staleness checks and their compiles. +- `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`. +- `:Test` holds `AddTest`, `RunTests` and `TestRunner`. +- `:Lint` is the lint/format driver plus the libclang token and AST layer. +- `:Script` is the driver behind `crafter-build run`: it looks a name up in `cfg.scripts`, calls the callback and turns what it returns into the exit code. +- `:Agents` keeps the dependency notes section of a project's AGENTS.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them between the section's markers. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configuration `GitProject` and `LocalProject` return has its `path` rebased. +- `:Progress` is console output. `:Shader` compiles shaders through glslang. `:Asset` is the hook into Crafter.Asset. + +## Dev environment + +The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop. + +Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime), `lld`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them. + +```bash +./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/ +./bin/crafter-build # self-host build through project.cpp +``` + +Three things to know about this loop: + +- `bin/crafter-build` is the bootstrap binary and the harness for every command below. The self-host build writes to `bin/crafter.build-exe-/crafter-build` and does not replace it. +- Changes under `implementations/` are picked up by the self-host build and by the tests, which link the local library. Changes under `interfaces/` are not: the harness compiles against the copies in `share/crafter-build/` and the PCM cache built from them, so a new or changed declaration is invisible until you run `./build.sh` again. The symptom is `use of undeclared identifier` for the symbol you just added. A changed default member initialiser has no symptom at all: `project.cpp` compiles against the old one and quietly gets the old default, as `project.cpp`'s sibling loads do with a harness that predates `GitProjectSpec::args = ProjectArgs()`. +- A new exported symbol that a `project.cpp` reaches on its default path also needs `./build.sh`: the old binary does not export it, and `LoadProject` fails with an undefined symbol. + +`./build.sh` clones and builds glslang on first run and takes several minutes; later runs are faster. `./bin/crafter-build clean` deletes `bin/` and `build/` without loading `project.cpp`. That takes `bin/crafter-build` itself with it, and `build/flatpak`, the state of the local Flatpak build (see "CI and publishing"): about 2 GB, and the next `run flatpak` rebuilds LLVM. Set `CRAFTER_BUILD_HOME` only when running a binary from outside this tree; `CRAFTER_BUILD_MARCH` and `CRAFTER_BUILD_MTUNE` default to `native`. + +## Build, test and style commands + +```bash +./bin/crafter-build # build (self-host) +./bin/crafter-build test # build and run every self-test +./bin/crafter-build test 'Incremental*' # name glob +./bin/crafter-build test --list # enumerate without running +./bin/crafter-build test --jobs=1 --timeout=120 +./bin/crafter-build lint # dry style gate, exit 1 on any finding +./bin/crafter-build format # apply the transform rules in place +./bin/crafter-build format --check # CI-style dry run +./bin/crafter-build run # list the scripts project.cpp defines +./bin/crafter-build run [args...] # run one; everything after the name is the script's +./bin/crafter-build clean +``` + +Before you call a change done, all three must exit 0: `format` (then re-read your diff), `lint`, `test`. CI runs `./build.sh` and `crafter-build test` on every PR; its lint step is currently commented out, so lint is enforced only by you. Failed, crashed and timed-out tests leave their output in `build/test-logs/.log`. + +## Testing instructions + +Tests are declared, not discovered. Each one is a line in `project.cpp`: + +```cpp +cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() }); +``` + +The source is `tests//main.cpp`. The test inherits target, march and the rest from the root configuration and links the local `crafter.build-lib`, so `import Crafter.Build;` resolves to the code in this checkout. A test that calls `LoadProject` also needs `.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl")`, as the existing ones show. The declarations sit in an `if (linuxTarget)` block that matches any `*-linux-gnu` or `*-linux-musl` target: the suite is Linux-host only today. + +A test is an ordinary `int main()`. Exit 0 passes, nonzero fails, 77 skips (for a missing tool, never for a failed assertion). Each runs in its own subprocess, in parallel, with a 60 s default timeout. + +Conventions the existing tests follow: + +- Open `main.cpp` with a comment that states the behaviour under test and the failure it guards against. `tests/CompilerWarning/main.cpp` shows the shape. +- Collect failures with a `Check(cond, msg)` helper that prints `FAIL: ...` to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it. +- Drive the engine in-process: `Build(cfg, depResults, depMutex)`, `RunTests`, the lint driver. Do not shell out to `bin/crafter-build` and grep its stdout. +- Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"` and removes it on the next run. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. +- Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`. +- Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration. + +A bug fix ships with a test that fails before the fix and passes after it, in its own `test:` commit when it documents the behaviour on its own. + +Cross-target runs use `test --target=` with `--runner=local` or `--runner=cmd:` (wine, qemu-user, valgrind), or `CRAFTER_BUILD_RUNNER_` as the persistent form. A failed runner probe skips its tests rather than failing the suite. + +## Code style + +`project.cpp` pulls in [Crafter.LintRules](https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules) through `#pragma crafter dependency` and applies its lite set, `LintRules::AddLiteRules`: the 8 rules that ask for different code, without the ones that only decide layout, whitespace and naming. `lint` reports all 8; `format` applies the two transforms among them, `format-concat` and `fixed-width-types`, and leaves everything else as written. Enforced: + +- The first three lines of every source: `// SPDX-License-Identifier: LGPL-3.0-only`, `// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®`, blank. Examples use MIT. +- `enum class` only. `std::println` instead of iostream. `std::format` instead of string concatenation. `std::int32_t` and friends instead of `int` or `long` (exempt: `main`, `argc`/`argv`, `extern "C"` and foreign API signatures). No `char*` outside C interop. +- `const` on scalar locals that are never written; `constexpr` on constants with constant initialisers. + +Not checked, so match the surrounding code: + +- Four-space indentation, no tabs, no trailing whitespace, final newline. +- `PascalCase` for types, functions, statics and constants; `camelCase` for variables; a trailing `_` is allowed. +- One declaration per statement. K&R braces. `if (x) return;` on one line when it fits, and no hand-wrapping of a statement that fits on one line. `if (` and `for (` with a space; no space before a call's `(`. + +Suppress one finding with `// lint-disable-next-line ` or a whole file with `// lint-disable-file `. Both are rare in this tree and need a reason. + +Beyond the rules: + +- `import std;` everywhere; standard headers are never `#include`d. C headers (`clang-c/Index.h`, `dlfcn.h`) go in the global module fragment after `module;`. +- Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule. +- There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests. +- A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. +- Every output path goes through `Configuration::BinDir()`, `BuildDir()` and `PcmDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. +- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, uninterpreted project args and the toolchain (`Toolchain::Key()`). + +## Design rules + +These were decided deliberately. Do not undo them without the maintainer's say-so. + +1. **Configuration is C++.** No JSON, YAML, TOML or DSL for project, runner or lint configuration. Lint rules are C++ callbacks; there is no clang-format or clang-tidy integration and no separate "format rule" type. A rule that calls `ctx.SetContent` is a transform, and that is the whole mechanism. +2. **Per-project artifacts go in `/build` and `/bin`. Only cross-project things go in `~/.cache/crafter.build/`:** the std PCM and Crafter.Build PCMs per target and march, and external clones keyed by their spec hash. +3. **Sources ship, PCMs build locally.** The Flatpak installs `*.cppm` under `/app/share/crafter-build/`. Nothing target-baked ships except the executable and the toolchain beside it, and the executable is built for a portable `-march`. +4. **crafter-build is a monolithic executable with `--export-dynamic`.** `project.so` resolves `Crafter::` symbols from the running binary at dlopen time. There is no Windows host; `x86_64-w64-mingw32` is a cross-compile target for user projects only. +5. **Convention over configuration.** Lead with the zero-config path. Env var, then CLI flag, then full `project.cpp` are the escalation, not the entry point. +6. **One skip mechanism** (runner probe plus exit 77) and **one `TestRunner` shape** (template fields with `{bin}`, `{bundle}` and similar placeholders; `Cmd(...)` covers any wrapper). Do not add a special-case runner class or a hardcoded "skip on this OS" branch. +7. **The house-style rules stay in their own repo.** They are not library API of crafter-build and are not forced on downstream projects. +8. **Fix warts inline; do not stack workarounds.** The previous version of this tool died of accumulated hacks. If a change needs a shortcut, say so in the PR rather than hiding it. +9. **`project.cpp` keeps the library/executable split.** `crafter.build-lib` owns the sources, dependencies and glslang; `crafter.build-exe` is `main.cpp` plus link flags. +10. **Host-tooling builds** (the target of a `#pragma crafter dependency`) get `-fPIC` and the host triple scoped to that build. Keep it scoped. + +## Commit and PR guidelines + +- Branch from `master` and open the PR against `master` on the project's Forgejo at `forgejo.catcrafts.net/Catcrafts/Crafter.Build`. Issue work uses `claude/issue-` branch names. Pushes go over SSH; HTTPS push is disabled on the server. +- Subject line: `type(scope): imperative summary`, with `feat`, `fix`, `refactor`, `docs` or `test`; the scope (`lint`, `incremental`, ...) is optional. Body: what was wrong, why, and why the fix has this shape, wrapped at about 75 columns. Read `git log` for the voice. +- Separate commits for the fix, its test and the README change when each stands on its own. +- Update the README in the same PR when user-visible behaviour changes. +- `format`, `lint` and `test` green before pushing. CI builds the Flatpak and runs the suite inside it on PRs, publishes the `beta` branch of the Catcrafts repo on every push to `master`, and the `stable` branch plus a release on an `X.Y.Z` tag. +- Never commit `bin/`, `build/`, `share/crafter-build/`, `lib/*.a` or fixture build outputs (all gitignored), and never edit the vendored files in `lib/`. +- Keep `CRAFTER_BUILD_MARCH=x86-64-v2` in the manifest for the shipped binary: it has to run on any x86_64 machine. User projects still default to `native`. + +## Security considerations + +- `project.cpp` is compiled and loaded into the crafter-build process, and every `GitProject`, `#pragma crafter dependency` and `ExternalDependency` clones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin with `commit` when adding anything else, and whenever reproducibility matters. +- Unpinned dependencies `git pull` on every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built. +- `--runner=cmd:` executes the named wrapper around every test binary. Wrappers come from `--runner=` or `CRAFTER_BUILD_RUNNER_*`; do not hardcode hosts, wrappers or credentials in `project.cpp` or tests. +- `crafter-build run ` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's; keep it that way. +- The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library. +- CI force-pushes the rolling `latest` tag and publishes a prerelease on every push to `master` with the workflow's own token, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it. +- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`. Keep it that way. + +## CI and publishing + +`.forgejo/workflows/ci.yaml` runs on the `crafter-flatpak` runner label: a dedicated privileged forgejo-runner on the Hetzner box (`forgejo-runner-flatpak.service`, config `/etc/forgejo-runner/config-flatpak.yaml`), registered to this repository only and the only runner with that label. It is privileged because bubblewrap inside the job container needs it, and separate from the other runners so that privilege is not shared with any other repository. Its config allows four volumes, which the workflow mounts: `crafter-flatpak-system` (the Sdk install at `/var/lib/flatpak`), `crafter-flatpak-builder` (flatpak-builder state and ccache, so the LLVM and WASI modules are rebuilt only when their sources change; a cold run takes about 80 minutes on 8 cores, a warm one a fraction of that), `/var/www/flatpak`, the web root Caddy serves as `https://flatpak.catcrafts.net/`, and `/etc/crafter-flatpak`, which holds the repo signing key (`signing-key.asc`, no passphrase, and `key-id`), generated once on the host and mounted read-only into the job; nothing is stored in the forge. The live repo at `/var/www/flatpak/repo` is canonical; builds are promoted into it with `flatpak build-commit-from`, never built into it. + +Keep the label unique to that runner. Plain `flatpak` also belongs to the organisation-wide runner (`forgejo-runner-org-flatpak.service`), which serves every Catcrafts repository and on purpose allows no volumes. Whenever this job lands there, flatpak-builder stops with `The state dir (/root/.cache/flatpak-builder) is not on the same filesystem as the target dir`; the top of the job log shows which runner took it and lists every volume it ignored. + +The key is made once, as root on the runner host, and the step fails with a message pointing here when it is missing: + +```bash +install -d -m 700 /etc/crafter-flatpak/gnupg && export GNUPGHOME=/etc/crafter-flatpak/gnupg +gpg --batch --pinentry-mode loopback --passphrase '' --quick-generate-key 'Catcrafts Flatpak Repository ' ed25519 sign never +KEYID=$(gpg --list-secret-keys --with-colons | awk -F: '/^sec/{print $5; exit}') +gpg --batch --pinentry-mode loopback --passphrase '' --export-secret-keys --armor "$KEYID" > /etc/crafter-flatpak/signing-key.asc +printf '%s\n' "$KEYID" > /etc/crafter-flatpak/key-id && chmod 600 /etc/crafter-flatpak/signing-key.asc /etc/crafter-flatpak/key-id +``` + +To release: add a `` to `packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml` (its description becomes the release notes), merge, and push the tag `X.Y.Z`. CI refuses a tag that does not match the newest entry. +Local builds are two scripts in `project.cpp`. Run them with the native binary: the Flatpak build of crafter-build has no `flatpak` to drive. + +```bash +./bin/crafter-build run flatpak [--jobs=] # build the Flatpak, then print its version from inside the sandbox +./bin/crafter-build run install # install that build as branch `local` and make it current +``` + +`run flatpak` needs `flatpak-builder` or the `org.flatpak.Builder` app, and the Sdk (`flatpak install flathub org.freedesktop.Sdk//26.08`). It builds the working tree, uncommitted changes included, runs the whole suite inside the sandbox and reports version `0.0.0-dev`. Its state is `build/flatpak/` (`state/`, `repo/`, `build-dir/`). The first run builds LLVM and the WASI sysroot, about 25 minutes on a 56-core machine; later runs rebuild only the crafter-build module, a few minutes, because flatpak-builder never caches a `type: dir` source. The checkout must not be under `/tmp`, which `org.flatpak.Builder` cannot see. Use it for anything toolchain-sensitive: the native loop compiles with the distro's clang and the Flatpak with its bundled LLVM, and the two can be a major version apart. + +`run install` does not build; it installs what `run flatpak` last exported. It points the user remote `crafter-build-local` at `build/flatpak/repo`, installs `net.catcrafts.CrafterBuild//local` from it next to whichever published branch is installed, and makes it the branch `flatpak run net.catcrafts.CrafterBuild` starts. `flatpak make-current --user net.catcrafts.CrafterBuild ` switches back. Before `crafter-build clean`, or before deleting the checkout, run `flatpak uninstall --user net.catcrafts.CrafterBuild//local` and `flatpak remote-delete --user crafter-build-local`; otherwise the remote is left pointing at a repo that is gone. + +## Gotchas + +- A new partition is listed in four places, in import order: `PARTITIONS` in `build.sh`, `CrafterBuildModules` in `Crafter.Build-Platform.cpp`, both arrays in `project.cpp`, and the umbrella `Crafter.Build.cppm`. Then `./build.sh`. +- A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away. +- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because `LoadProject` fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard. +- `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache. +- The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. Changing asset extensions means updating two maps in `Crafter.Build-Clang.cpp`: `assetOutput` and the transitive copy loop. +- A warning is printed only when its unit actually recompiles. A build with nothing to do is silent, which is not evidence that a warning is gone. +- A std module source only compiles against the headers of its own libc++ release, and a sysroot does not always ship one (Alpine). The Flatpak therefore carries the sources of the release next to the bundled one under `share/crafter-build/libc++-modules//`, one `libcxx--modules` manifest module each. When the bundled LLVM is bumped, keep the release it leaves behind as such a module: sysroots on the stable distro stay on it for months. The native loop has no such directory; stage one by hand under `share/crafter-build/` to test against a foreign sysroot. +- The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib//eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`. +- `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`. +- `VariantId()` names the output directory, so CI globs `bin/crafter.build-exe---*/` rather than predicting the hash. The hash includes the compiler, so after a toolchain update the previous variant's directories stay in `bin/` and `build/` until `clean`, and such a glob matches both. +- The self-host build and `test` keep the dependency notes section of this very file. None of Crafter.Math, Crafter.Asset and Crafter.LintRules ships an `AGENTS.consumer.md` yet. Once one does, a build here can change AGENTS.md whenever that repository changes its notes, since all three are unpinned. The tree is then dirty, so the next build's `git describe --dirty` version differs, which is a new `crafter.build-lib` variant and a full rebuild. Commit the section to settle it. diff --git a/AGENTS.template.md b/AGENTS.template.md deleted file mode 100644 index 6e4b9f7..0000000 --- a/AGENTS.template.md +++ /dev/null @@ -1,223 +0,0 @@ -# AGENTS.md - -Guidance for coding agents and contributors working on crafter-build itself. The [README](README.md) is the user-facing manual; this file holds what you need to change the build system. When the two disagree, the code wins: check the interface in `interfaces/` and the `--help` output of the built binary. - -## Project overview - -crafter-build is a C++26 modules build system. A project is described by a `project.cpp` that returns a `Crafter::Configuration`, or several of them; the tool compiles that file to a shared object, loads it in-process and builds what it describes. This repository is self-hosting: its own `project.cpp` builds crafter-build with crafter-build, and its tests link the library and drive `Build()` in-process. - -| Path | What lives there | -|---|---| -| `interfaces/Crafter.Build-.cppm` | Module interface partitions. `Crafter.Build.cppm` is the umbrella that re-exports them. | -| `implementations/Crafter.Build-.cpp` | Implementation units, one per partition, named `Crafter.Build:_impl`. `main.cpp` is a thin wrapper around `Crafter::Run`. | -| `project.cpp` | The self-host build description: a `crafter.build-lib` library, a `crafter.build-exe` executable, the test declarations, the lint rules and the `flatpak` and `install` scripts. | -| `AGENTS.template.md` | The source of AGENTS.md. Every build and test run writes AGENTS.md from it, with the notes the dependencies ship; AGENTS.md is gitignored, so changes go here. | -| `tests//main.cpp` | One self-test per directory; `tests//fixture/` holds the sample project it builds. | -| `examples/` | Standalone user-facing projects, MIT licensed. | -| `build.sh` | Bootstrap script. It compiles everything by hand, without crafter-build. | -| `wasi-runtime/` | `runtime.js` and `index.html.in`, shipped for browser targets. | -| `lib/` | Vendored third-party headers (glslang's DirStackFileIncluder). Do not edit. | -| `share/crafter-build/`, `bin/`, `build/`, `lib/*.a` | Generated and gitignored. | -| `packaging/flatpak/`, `.forgejo/workflows/ci.yaml` | The Flatpak manifest with its metainfo, repo and ref files, and the Forgejo Actions CI that builds and publishes it. | -| `.review-gates/` | The pre-push review's `config.json` and this repository's lens sections (`lenses/`), read by Crafter.Review. Its `push/` and `trees/` are generated and gitignored. | - -Partitions and what they own: - -- `:Toolchain` resolves the compiler once per process (`GetToolchain`): clang++, clang, llvm-ar, llvm-readelf, clang-scan-deps, libclang, libc++'s std module source and the default sysroots, from `CRAFTER_BUILD_LLVM_DIR`, else a toolchain installed beside crafter-build, else PATH. It also holds the version baked in at build time, and the arch and branch of the Flatpak runtime crafter-build runs on, from `/.flatpak-info` or the file `CRAFTER_BUILD_FLATPAK_INFO` names, and the nvcc `cfg.cuda` compiles with: `$CUDA_PATH/bin/nvcc`, else `bin/nvcc` under `/opt/cuda` or `/usr/local/cuda`, else the first in an absolute entry of PATH, which it searches itself, and `cudaRuntime`, the `lib64/libcudart_static.a` beside that nvcc's `bin` where there is one, which a configuration with CUDA sources links. In the Flatpak the host's `/usr` and `/etc` are under `/run/host`, and a link to an absolute path names a host path, so where the path of a toolkit is a link, it follows that link, and the link its target is in turn, each as the host's (`HostPath`); a link in a directory partway along that path, or inside the toolkit, is the kernel's to resolve, in the sandbox's root. `SysrootStdModule` picks the std module source for a sysroot build by the sysroot's libc++ release. `MingwSysroot` settles the mingw target's `--sysroot`: the mingw-w64 prefix itself, or, for a prefix that also holds a Linux system (the host's `/usr`, anything whose `include/` has `features.h`), a view in the cache of its mingw-w64 directories, since clang would search its `include/` and `lib/` too (issue #43). `MingwViewToPrefix` turns paths into the view back into paths into the prefix for messages. -- `:Clang` holds `Configuration`, `Build()`, `VariantId()`, `ApplyStandardArgs`, `HostTarget`, the CLI entry point `Crafter::Run`, and the lint, test and script data types. -- `:Platform` runs commands, implements `LoadConfigurations` and `LoadProject` (compile and load `project.cpp`), the host PCM cache and `#pragma crafter dependency`. -- `:Jobs` is what build steps run on: `JobPool`, worker threads behind one queue, started as jobs need them up to a fixed number, with `JobPool::Process()` the pool of at most one worker per hardware thread that `Build()` and `RunBuildCommand` use, and `JobGroup`, the jobs of one configuration's build, each started once the jobs it was added after have finished, with the first error among them and what `Build()` reports to it through `Fail()`. -- `:Interface` and `:Implementation` model module units, their staleness checks and the jobs that compile them (`Schedule`). -- `:External` handles git + cmake dependencies, `GitProject` and `LocalProject`. -- `:Test` holds `AddTest`, `RunTests` and `TestRunner`, and starts the headless compositor of a test that sets `Test::wayland` (`RunSingleTest`), through `:Platform`'s `BackgroundCommand` and `PrivateDirectory`. -- `:Lint` is the lint/format driver plus the libclang token and AST layer. -- `:Script` is the driver behind `crafter-build run`: it looks a name up in the `scripts` of the configurations it is given, calls the callback and turns what it returns into the exit code. -- `:Agents` writes a project's AGENTS.md from its AGENTS.template.md: it walks the dependencies `cfg.dependencyNotes` selects, reads each one's `AGENTS.consumer.md` and merges them into the template's dependency notes section. Which Configurations belong to another project, and where it lives, comes from the loader (`LoadedProjectOf` in `:External`, `PragmaDependencies` in `:Platform`), because only the Configurations returned by a project file that `GitProject` or `LocalProject` loaded have their `path` rebased. -- `:Progress` is console output. `:Shader` compiles shaders through glslang. `:Asset` is the hook into Crafter.Asset. -- `:Flatpak` is an executable packaged as a Flatpak: `FlatpakApp` (app-id, runtime, permissions, desktop file, metainfo, icons, share entries, modules), the writer of its `files/`, which becomes `/app` in the app's sandbox, and what makes the app of that for `install` and `bundle`: the host's `flatpak build-finish`, which writes the metadata and `export/` by flatpak's own rules, then `flatpak build-export` into a repo, or flatpak-builder from a generated manifest when there are modules. It works on plain data; `Build()` and the `InstallFlatpakApp` and `BundleFlatpakApp` of `:Clang` gather it from the Configuration. The host's flatpak and flatpak-builder are reached through `RunHostFlatpak` and `RunHostFlatpakBuilder` in `:Platform`. - -## Dev environment - -The shipped artifact is the Flatpak (see "CI and publishing"); the loop below is the native development loop. - -Prerequisites on Linux: `clang` (with `libclang`, which the AST lint rules load at runtime, and `clang-scan-deps`, which a build reads what each C++ source declares and imports with), `lld`, LLVM's `llvm-ar` and `llvm-readelf`, `libc++` with its std module source (`share/libc++/v1/std.cppm`), `cmake`, `git`. `crafter-build --version` prints which compiler was resolved; `CRAFTER_BUILD_LLVM_DIR` points it at another LLVM prefix, and `build.sh` honours the same variable. Network access to `forgejo.catcrafts.net` and `github.com` is needed: loading `project.cpp` fetches Crafter.Math, Crafter.Asset and Crafter.LintRules into `~/.cache/crafter.build/external/`, and the bootstrap clones glslang. Those sources are unpinned, so every invocation runs `git pull` on them. - -```bash -./build.sh # bootstrap: bin/crafter-build, lib/libcrafter-build.a, share/crafter-build/ -./bin/crafter-build # self-host build through project.cpp -``` - -Three things to know about this loop: - -- `bin/crafter-build` is the bootstrap binary and the harness for every command below. The self-host build writes to `bin/crafter.build-exe-/crafter-build` and does not replace it. -- Changes under `implementations/` are picked up by the self-host build and by the tests, which link the local library. Changes under `interfaces/` are not: the harness compiles against the copies in `share/crafter-build/` and the PCM cache built from them, so a new or changed declaration is invisible until you run `./build.sh` again. The symptom is `use of undeclared identifier` for the symbol you just added. A changed default member initialiser has no symptom at all: `project.cpp` compiles against the old one and quietly gets the old default, as `project.cpp`'s sibling loads do with a harness that predates `GitProjectSpec::args = ProjectArgs()`. -- A new exported symbol that a `project.cpp` reaches on its default path also needs `./build.sh`: the old binary does not export it, and loading `project.cpp` fails with an undefined symbol. - -`./build.sh` clones and builds glslang on first run and takes several minutes; later runs are faster. `./bin/crafter-build clean` deletes `bin/` and `build/` without loading `project.cpp`. That takes `bin/crafter-build` itself with it, and `build/flatpak`, the state of the local Flatpak build (see "CI and publishing"): about 4 GB after a first run, and the next `run flatpak` rebuilds LLVM. Set `CRAFTER_BUILD_HOME` only when running a binary from outside this tree; `CRAFTER_BUILD_MARCH` and `CRAFTER_BUILD_MTUNE` default to `native`. - -## Build, test and style commands - -```bash -./bin/crafter-build # build (self-host) -./bin/crafter-build test # build and run every self-test -./bin/crafter-build test 'Incremental*' # name glob -./bin/crafter-build test --list # enumerate without running -./bin/crafter-build test --jobs=1 --timeout=120 -./bin/crafter-build lint # dry style gate, exit 1 on any finding -./bin/crafter-build format # apply the transform rules in place -./bin/crafter-build format --check # CI-style dry run -./bin/crafter-build run # list the scripts project.cpp defines -./bin/crafter-build run [args...] # run one; everything after the name is the script's -./bin/crafter-build clean -``` - -Before you call a change done, all three must exit 0: `format` (then re-read your diff), `lint`, `test`. CI runs `./build.sh` and `crafter-build test` for every release tag, every pull request into `master` and every manual run, and has no lint step, so lint is enforced only by you. Failed, crashed and timed-out tests leave their output in `build/test-logs/.log`. - -## Testing instructions - -Tests are declared, not discovered. Each one is a line in `project.cpp`: - -```cpp -cfg.AddTest("IncrementalHeaderChange").Dependencies({ CrafterBuildLib.get() }); -``` - -The source is `tests//main.cpp`. The test inherits target, march and the rest from the root configuration and links the local `crafter.build-lib`, so the engine it calls is the one built from this checkout. A test that loads a project file, through `LoadConfigurations`, `LoadProject`, `LocalProject`, `GitProject` or `Run()`, also needs `.LinkFlag("-Wl,--export-dynamic").LinkFlag("-ldl")`, as the existing ones show. The declarations sit in an `if (linuxTarget)` block that matches any `*-linux-gnu` or `*-linux-musl` target: the suite is Linux-host only today. - -A test is an ordinary `int main()`. Exit 0 passes, nonzero fails, 77 skips (for a missing tool, never for a failed assertion). Each runs in its own subprocess, in parallel, with a 60 s default timeout. - -Conventions the existing tests follow: - -- Open `main.cpp` with a comment that states the behaviour under test and the failure it guards against. `tests/CompilerWarning/main.cpp` shows the shape. -- Collect failures with a `Check(cond, msg)` helper that prints `FAIL: ...` to stderr and counts, then return nonzero at the end. Do not stop at the first failure unless later steps are meaningless without it. -- Drive the engine in-process: `Build(cfg, depResults, depMutex)`, `RunTests`, the lint driver. Do not shell out to `bin/crafter-build` and grep its stdout. -- Fixtures under `tests//fixture/` are inputs. A test that edits or touches files first stages a copy under `fs::temp_directory_path() / "crafter-build-"`, after removing what an earlier run left there, which matters where the test runs by hand: under `crafter-build test` the copy is in the test's own `TMPDIR`, which goes when the test ends unless the test failed, crashed or timed out and left something in it: then it is kept until a later run removes it, a minute after the run that kept it ended, or, where that run was killed, a minute after its last change to the run's directory. Most tests here remove their copy themselves before they report, and so leave nothing to keep. Variant sources are checked in as `*.in` files and copied over the original inside the staged copy. The fixed name is safe because `RunTests` gives every test a `TMPDIR` of its own for the run, so two runs at once, natively or in the Flatpak, whose sandboxes all share the app's `/tmp`, stage into different directories. A test that writes to `/tmp` by name, as `HostFlatpak` has to, makes a directory of its own there, a `PrivateDirectory`, which a later run removes, where a killed run left it, once it has not changed for a minute. A test that builds against a sysroot it stages, or has crafter-build fetch a repository it stages, points `XDG_CACHE_HOME` into its scratch directory too, as `SysrootStdModule` and the external-dependency tests do: the cache's key holds that path or URL, which is a new one every run. -- Use a fresh `depResults` map per build pass: the map memoises each configuration's result, and each external dependency's fetch and build, for one pass, so reusing it skips rebuilds and pulls you meant to observe. `Build()` itself is safe to call repeatedly on the same `Configuration`. -- Set `cfg.path` before calling `GetInterfacesAndImplementations`, and spell `cFiles` as absolute paths: both resolve against the working directory, not the configuration. -- `GetInterfacesAndImplementations` only lists the sources. A configuration's `interfaces` and `implementations`, its modules and units with what each imports, are made by `Build()` from what it reads in them, so a test that looks at them builds first. -- A test that needs the host's flatpak goes through `RunHostFlatpak`, skips (77) with the reason `HostFlatpakUnavailable` gives (flatpak-builder's build sandbox, where CI runs, has no way out), and installs only into a private `FLATPAK_USER_DIR` under its fixture's `build/`, as `FlatpakInstall` does. It never runs an installed app: `flatpak run` makes `~/.var/app/` in the real home. -- A test that packages a Flatpak stages the runtime: it writes a `.flatpak-info` whose `[Application]` group has a `runtime=runtime/org.freedesktop.Sdk/x86_64/26.08` line, as the parser takes only that group's, and points `CRAFTER_BUILD_FLATPAK_INFO` at it with `setenv`, first thing in `main`, since the toolchain is read once per process. That works natively and wins over the sandbox's own file in the Flatpak; `FlatpakNative` stages an empty one for the native case. - -A bug fix ships with a test that fails before the fix and passes after it, in its own `test:` commit when it documents the behaviour on its own. - -Cross-target runs use `test --target=` with `--runner=local` or `--runner=cmd:` (wine, qemu-user, valgrind), or `CRAFTER_BUILD_RUNNER_` as the persistent form. A failed runner probe skips its tests rather than failing the suite. - -## Code style - -`project.cpp` pulls in [Crafter.LintRules](https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules) through `#pragma crafter dependency` and applies its lite set, `LintRules::AddLiteRules`: the 8 rules that ask for different code, without the ones that only decide layout, whitespace and naming. `lint` reports all 8; `format` applies the two transforms among them, `format-concat` and `fixed-width-types`, and leaves everything else as written. Enforced: - -- The first three lines of every source: `// SPDX-License-Identifier: LGPL-3.0-only`, `// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®`, blank. Examples use MIT. -- `enum class` only. `std::println` instead of iostream. `std::format` instead of string concatenation. `std::int32_t` and friends instead of `int` or `long` (exempt: `main`, `argc`/`argv`, `extern "C"` and foreign API signatures). No `char*` outside C interop. -- `const` on scalar locals that are never written; `constexpr` on constants with constant initialisers. - -Not checked, so match the surrounding code: - -- Four-space indentation, no tabs, no trailing whitespace, final newline. -- `PascalCase` for types, functions, statics and constants; `camelCase` for variables; a trailing `_` is allowed. -- One declaration per statement. K&R braces. `if (x) return;` on one line when it fits, and no hand-wrapping of a statement that fits on one line. `if (` and `for (` with a space; no space before a call's `(`. - -Suppress one finding with `// lint-disable-next-line ` or a whole file with `// lint-disable-file `. Both are rare in this tree and need a reason. - -Beyond the rules: - -- `import std;` everywhere; standard headers are never `#include`d. C headers (`clang-c/Index.h`, `dlfcn.h`) go in the global module fragment after `module;`. -- Comments explain why: the failure mode, the constraint, the rejected alternative. The codebase carries long comments on purpose. Do not strip them, and write them for new non-obvious code. Commit bodies follow the same rule. -- There is no host-platform preprocessor split: the host is Linux. Target differences (mingw, wasm) branch on `cfg.target` strings at runtime, in the library as well as in `project.cpp` and tests. -- A build step fails when its command exits nonzero, never because it printed. Use `RunBuildCommand` or `RunCommandChecked`; warnings go to `Progress::Diagnostic`. -- Give a build step that keeps a hardware thread busy to the pool, not a thread of its own: that is what holds a build to as many steps at once as there are hardware threads. Add a step of a configuration's build to its `JobGroup` in `Build()`, after the jobs whose output it reads; run a step that stands by itself, as a link does, through `RunBuildCommand`, which runs on a worker of `JobPool::Process()` whoever calls it. Do not wait for a job inside a job, or anywhere else on a worker, where the wait would hold the thread the job needs: a `JobGroup` made on a worker of its own pool throws. A job owns what it uses, or uses only what outlives its group. -- Every output path goes through `Configuration::BinDir()`, `BuildDir()`, `PcmDir()` and `ProgramDir()`. Hand-rolled `path / "bin" / ...` clobbered variants before; do not add new ones. `ProgramDir()` is where an executable and the files it reads beside it land, its shaders, `cfg.files`, assets and what its dependencies forward, and the directory `-r` runs a host executable in and serves a browser build from (a Flatpak's `cfg.flatpak.share` entries go to `files/share` instead); `ExpectedOutput()` names the executable in it. A Flatpak's bundle and the directory `install` and `bundle` work in are `FlatpakBundlePath()` and `FlatpakAppDir()`. -- `ObjectPath()` names the object of a `.cpp`, `.c` or `.cu`, from where its source lies: `objects/a/Thing_impl.o` in the build directory for `a/Thing.cpp`. Do not name one from its source's file name: two sources of one name in different directories then share an object, each compiled over the other (issue #50). A step that takes every object of a configuration reads them from a response file, as the link does, and not from its command, which the system holds to a length. -- A static library's archive and the list of objects a step reads are written under another name beside them and renamed into place (`WrittenBeside` and `MoveIntoPlace` in `Crafter.Build-Clang.cpp`), not removed first or written over where they lie: a link or archive step of another crafter-build may be reading them. Two crafter-builds can build a project loaded with `GitProject` at once, in the clone the cache keeps for its source, and one then links against the library, or reads that list, while the other writes it. Write anything else such a step reads the same way. -- Anything that changes what gets compiled or bundled belongs in `VariantId()`. It already hashes type, debug, sysroot, defines, compile flags, the wasm baseline and variant flags, the std module the units import (`StdPcmKey`), uninterpreted project args, the toolchain (`Toolchain::Key()`), the GPU architecture (`cudaArch`), for `native` crafter-build's reading of the GPUs it compiles for, the NVIDIA display devices sysfs lists with `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` (`Toolchain::cudaNativeKey`, which is not what nvcc detects), and the nvcc (`Toolchain::nvccStamp`; `Toolchain::Key()` leaves both out) of a configuration with CUDA sources and, only when it is one, that the executable is packaged as a Flatpak. What a Flatpak is installed as (`FlatpakApp`) is not hashed: it changes `files/share`, which the writer rewrites in place, and what `install` and `bundle` finish the app with, never what is compiled. Its modules are not hashed either: flatpak-builder builds them for `install` and `bundle` in `FlatpakAppDir()`, one per app, outside any variant's directory. - -## Design rules - -These were decided deliberately. Do not undo them without the maintainer's say-so. - -1. **Configuration is C++.** No JSON, YAML, TOML or DSL for project, runner or lint configuration. Lint rules are C++ callbacks; there is no clang-format or clang-tidy integration and no separate "format rule" type. A rule that calls `ctx.SetContent` is a transform, and that is the whole mechanism. -2. **Per-project artifacts go in `/build` and `/bin`. Only cross-project things go in `~/.cache/crafter.build/`:** the std PCM and Crafter.Build PCMs per target, march, toolchain and std module flags, external clones keyed by their spec hash, the mingw sysroot views keyed by prefix, and the locks `install` holds on the remotes of the user's installation (`flatpak-remotes/`, found by `HOME` and never by `XDG_CACHE_HOME`, in the Flatpak as well, so that every crafter-build installing for the user takes the same one; that of a private installation, `FLATPAK_USER_DIR`, is kept in it). -3. **Sources ship, PCMs build locally.** The Flatpak installs `*.cppm` under `/app/share/crafter-build/`. Nothing target-baked ships except the executable and the toolchain beside it, and the executable is built for a portable `-march`. -4. **crafter-build is a monolithic executable with `--export-dynamic`.** `project.so` resolves `Crafter::` symbols from the running binary at dlopen time. There is no Windows host; `x86_64-w64-mingw32` is a cross-compile target for user projects only. -5. **Convention over configuration.** Lead with the zero-config path. Env var, then CLI flag, then full `project.cpp` are the escalation, not the entry point. -6. **One skip mechanism** (runner probe plus exit 77) and **one `TestRunner` shape** (template fields with `{bin}`, `{bundle}` and similar placeholders; `Cmd(...)` covers any wrapper). Do not add a special-case runner class or a hardcoded "skip on this OS" branch. -7. **The house-style rules stay in their own repo.** They are not library API of crafter-build and are not forced on downstream projects. -8. **Fix warts inline; do not stack workarounds.** The previous version of this tool died of accumulated hacks. If a change needs a shortcut, say so in its commit message rather than hiding it. -9. **`project.cpp` keeps the library/executable split.** `crafter.build-lib` owns the sources, dependencies and glslang; `crafter.build-exe` is `main.cpp` plus link flags. -10. **Host-tooling builds** (the target of a `#pragma crafter dependency`) get `-fPIC` and the host triple scoped to that build. Keep it scoped. - -## Commit and push guidelines - -- Branch from `master`; issue work uses `claude/issue-` branch names. Once the owner approves its frozen hash, a range goes straight to `master` on the project's Forgejo at `forgejo.catcrafts.net/Catcrafts/Crafter.Build`, as a fast-forward push with no merge commit and no pull request; open a pull request against `master` only when the owner asks for one. If `master` has moved since the freeze, rebase onto it, then freeze and review the rebased range again. Pushes go over SSH; HTTPS push is disabled on the server. -- Subject line: `type(scope): imperative summary`, with `feat`, `fix`, `refactor`, `docs` or `test`; the scope (`lint`, `incremental`, ...) is optional. Body: what was wrong, why, and why the fix has this shape, wrapped at about 75 columns. Read `git log` for the voice. -- Separate commits for the fix, its test and the README change when each stands on its own. -- Update the README in the same push when user-visible behaviour changes. -- `format`, `lint` and `test` green before pushing. CI builds the Flatpak and runs the suite inside it for every release tag, every pull request into `master` and every manual run. Without a pull request, CI does not run on a range before it reaches `master` unless someone starts it by hand (`workflow_dispatch`), so the review's gate0, the commands in `.review-gates/config.json`, is the check before the push. -- Every push to `master` is a release, made by the signed tag pushed with it (see "CI and publishing"). Every pushed range adds a `` entry for its version at the top of `packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml`, in a commit of its own (`docs(packaging): add the X.Y.Z release entry`), dated the day of the push in UTC. Its notes have up to three sections, `

New

`, `

Fixes

` and `

Breaking

` in that order, each followed by a `
    ` of its items, the most important first, and nothing after the last section. The version follows from them: a Breaking section makes it a major, New items a minor, and Fixes alone a patch. Once the owner has approved the frozen hash, the commit `master` is to receive gets the signed tag of that version, made locally, and both go out in one push: `git tag -s X.Y.Z -m 'crafter-build X.Y.Z'`, then `git push --atomic origin HEAD:master X.Y.Z`. That commit is the range's last one, or, when the owner asks for a pull request instead, the merge of the reviewed branch into `master`. -- Every push of new commits goes through Crafter.Review's pre-push review first, and goes out only once the owner approves the frozen hash. Run `flatpak run net.catcrafts.CrafterReview init` once in a fresh checkout or worktree: it writes the `/prepush` skill that drives the review, and the skill stays untracked. `freeze` refuses merge commits: a range reaches `master` as a fast-forward, and when the owner asks for a pull request instead, the merge of the reviewed branch into `master` is pushed without a freeze of its own. -- Every commit of a pushed range is GPG-signed, has `jorijnvdgraaf@catcrafts.net` as its author and committer, and carries no AI attribution trailer in its message, neither `Co-Authored-By:` nor `Assisted-by:`. `freeze` refuses a range with a commit that breaks any of these (`requireSigned`, `authors` and `aiTrailers` in `.review-gates/config.json`). -- Never commit `bin/`, `build/`, `share/crafter-build/`, `lib/*.a`, `AGENTS.md` or fixture build outputs (all gitignored), and never edit the vendored files in `lib/`. -- Keep `CRAFTER_BUILD_MARCH=x86-64-v2` in the manifest for the shipped binary: it has to run on any x86_64 machine. User projects still default to `native`. - -## Security considerations - -- `project.cpp` is compiled and loaded into the crafter-build process, and every `GitProject`, `#pragma crafter dependency` and `ExternalDependency` clones a repository and runs its build on the host. Treat a dependency URL as code you are choosing to run. This repo's own dependencies are sibling Catcrafts repos tracking their default branch on purpose; pin with `commit` when adding anything else, and whenever reproducibility matters. -- Unpinned dependencies `git pull` on every invocation, so builds and tests need network. A missing or private repo surfaces as a clone failure before anything is built. -- `--runner=cmd:` executes the named wrapper around every test binary. Wrappers come from `--runner=` or `CRAFTER_BUILD_RUNNER_*`; do not hardcode hosts, wrappers or credentials in `project.cpp` or tests. -- `--compositor=` and `CRAFTER_BUILD_COMPOSITOR` name the command that crafter-build runs through `sh` beside every test that sets `Test::wayland`, unless they name `host`; the default is the weston on `PATH`. -- `crafter-build run ` executes whatever the script does, with your permissions. Only the scripts of the project crafter-build was pointed at can be run, never a dependency's: `run` leaves out a configuration that another project's file returned and the project file returns in turn, and the load refuses one that another project keeps to itself (`KeptBy`); keep it that way. -- The linter loads `libclang` at runtime by name. `CRAFTER_BUILD_LIBCLANG` pins an exact path and must fail loudly when wrong, never fall back to another library. -- crafter-build's Flatpak has `--talk-name=org.freedesktop.Flatpak`, and the permission is the whole sandbox's: anything that runs there can run commands on the host through `flatpak-spawn --host`. That is every process of crafter-build's sandbox: crafter-build itself, every `project.cpp` it loads with its scripts, the builds of its dependencies and pragma dependencies, the programs `-r` and `test` start, and whatever `flatpak run --command=` and `flatpak enter` start in it, the debuggers of the README's Debugging section and the programs under them included. crafter-build's own code uses it only through `HostCommand` in `:Platform`, which builds the command lines of `RunHostFlatpak`, `RunHostFlatpakBuilder` and `HostFlatpakUnavailable`'s probes, for the host's `flatpak` and `flatpak-builder` behind `install` and `bundle`; add no other host command to crafter-build. `RunHostFlatpak` is exported for the tests, and gives a `project.cpp` nothing the sandbox does not. The trust model allows the permission because `--filesystem=host` already lets sandboxed code write `~/.bashrc`, `~/.config/autostart` and `~/.config/systemd/user`: it makes running something on the host immediate, not newly possible, for everything the sandbox runs. -- CI creates a release for each release tag with the workflow's own token, pushes nothing to git, and signs the Flatpak repo with the key mounted from the runner host. Do not add secrets to the workflow or echo the environment in it. -- Tests write only under `fs::temp_directory_path()` and the fixture's own `bin/` and `build/`, and in the caches of what they run, unless they point `XDG_CACHE_HOME` elsewhere: crafter-build's, what a build puts there, and wasmtime's, the modules the wasm tests run. Keep it that way. Two tests write elsewhere, and both remove what they make, and a later run removes what a killed one left once that has not changed for a minute (`PrivateDirectory`): `tests/HeadlessCompositor`, which makes its compositors' directories in a directory of its own in `$XDG_RUNTIME_DIR`, or in `/tmp` when that is not a directory, and has one made in `/tmp` itself, as crafter-build makes it where there is no `$XDG_RUNTIME_DIR`, because a socket's path holds 107 bytes and a temp directory's path can use them up; and `tests/HostFlatpak`, which in the Flatpak makes a directory of its own in the sandbox's `/tmp`, the place it asks the host about. - -## CI and publishing - -`.forgejo/workflows/ci.yaml` runs on the `crafter-flatpak` runner label: a dedicated privileged forgejo-runner on the Hetzner box (`forgejo-runner-flatpak.service`, config `/etc/forgejo-runner/config-flatpak.yaml`), registered to this repository only and the only runner with that label. It is privileged because bubblewrap inside the job container needs it, and no other repository's job runs on it. Its config allows four volumes, which the workflow mounts: `crafter-flatpak-system` (the Sdk install at `/var/lib/flatpak`), `crafter-flatpak-builder` (flatpak-builder state and ccache, which later runs reuse: flatpak-builder builds a module again when its sources or its `build-commands` change, and every module after it with it, so a new version of `swig` or `libedit`, which come before LLVM, also rebuilds the LLVM and WASI modules), `/var/www/flatpak`, the web root Caddy serves as `https://flatpak.catcrafts.net/`, and `/etc/crafter-flatpak`, which holds the repo signing key (`signing-key.asc`, no passphrase, and `key-id`), generated once on the host and mounted read-only into the job; nothing is stored in the forge. The web root and the key are not this runner's alone: the organisation-wide `flatpak` runner (`forgejo-runner-org-flatpak.service`), which serves every Catcrafts repository, mounts both for Crafter.Review's publish job, and the volumes a runner allows (`valid_volumes` in its config) are open to every job it runs, so a job of any Catcrafts repository that runs there can mount them as well. The live repo at `/var/www/flatpak/repo` is canonical; builds are promoted into it with `flatpak build-commit-from`, never built into it. Crafter.Review's workflow publishes into the same repo, and each workflow holds an flock on `/var/www/flatpak/.publish.lock` while it commits and updates the summary. - -Keep the label unique to that runner. Plain `flatpak` belongs to the organisation-wide runner. When this job still asked for `flatpak` and that runner took it (runs #368 and #370, in October 2026), the runner allowed none of the job's volumes, and flatpak-builder stopped with `The state dir (/root/.cache/flatpak-builder) is not on the same filesystem as the target dir`; the top of such a job's log shows which runner took it and lists every volume it ignored. - -The key is made once, as root on the runner host, and the step fails with a message pointing here when it is missing: - -```bash -install -d -m 700 /etc/crafter-flatpak/gnupg && export GNUPGHOME=/etc/crafter-flatpak/gnupg -gpg --batch --pinentry-mode loopback --passphrase '' --quick-generate-key 'Catcrafts Flatpak Repository ' ed25519 sign never -KEYID=$(gpg --list-secret-keys --with-colons | awk -F: '/^sec/{print $5; exit}') -gpg --batch --pinentry-mode loopback --passphrase '' --export-secret-keys --armor "$KEYID" > /etc/crafter-flatpak/signing-key.asc -printf '%s\n' "$KEYID" > /etc/crafter-flatpak/key-id && chmod 600 /etc/crafter-flatpak/signing-key.asc /etc/crafter-flatpak/key-id -``` - -A release is a tag `X.Y.Z`, annotated and signed, pushed with the `master` it releases; a push to `master` without one runs nothing. Before building, every run renders the release notes from the newest `` entry in `packaging/flatpak/net.catcrafts.CrafterBuild.metainfo.xml`, and stops when the metainfo does not parse or the notes come out empty. A tag run also checks that Forgejo verifies the tag as signed by the address the workflow's `RELEASE_SIGNER` names, that the tag's commit is on `master`, that its version has the form `X.Y.Z` and is newer than every release the forge has published, its own included, and that the newest entry is that version. Once the build and the suite inside it pass, the tag run publishes `stable` and creates the release, with the notes, the bundle, the `.flatpakref` and `SHA256SUMS` attached. Release runs queue one behind another, and a failed one can be re-run while no newer release exists, once a release it left half made is deleted; when the fix needs a commit of its own, that push is the next version's release. Pull requests and manual runs publish nothing. The `beta` branch, which every push to `master` used to go to, gets no more builds: the publish step marks its last build end-of-life, once, and the next `flatpak update` of a beta installation prints the reason. - -Local builds are two scripts in `project.cpp`. Run them with the native binary: they run `flatpak` and `flatpak-builder` themselves, which the Flatpak build of crafter-build has none of. crafter-build's own `install` and `bundle` reach the host's through `RunHostFlatpak` and `RunHostFlatpakBuilder` instead. - -```bash -./bin/crafter-build run flatpak [--jobs=] # build the Flatpak, then print its version from inside the sandbox -./bin/crafter-build run install # install that build as branch `local` and make it current -``` - -`run flatpak` needs `flatpak-builder` or the `org.flatpak.Builder` app, and the Sdk (`flatpak install flathub org.freedesktop.Sdk//26.08`). It builds the working tree, uncommitted changes included, runs the whole suite inside the sandbox and reports version `0.0.0-dev`. Its state is `build/flatpak/` (`state/`, `repo/`, `build-dir/`). The first run builds every module, LLVM with lldb, the WASI sysroot and the Vulkan validation layer among them, in about 30 minutes with 56 CPU threads; later runs rebuild only the crafter-build module while the manifest is unchanged, a few minutes, because flatpak-builder never caches a `type: dir` source. The checkout must not be under `/tmp`, which `org.flatpak.Builder` cannot see. Use it for anything toolchain-sensitive: the native loop compiles with the distro's clang and the Flatpak with its bundled LLVM, and the two can be a major version apart. - -`run install` does not build; it installs what `run flatpak` last exported. It points the user remote `crafter-build-local` at `build/flatpak/repo`, installs `net.catcrafts.CrafterBuild//local` from it next to whichever published branch is installed, and makes it the branch `flatpak run net.catcrafts.CrafterBuild` starts. `flatpak make-current --user net.catcrafts.CrafterBuild ` switches back. Before `crafter-build clean`, or before deleting the checkout, run `flatpak uninstall --user net.catcrafts.CrafterBuild//local` and `flatpak remote-delete --user crafter-build-local`; otherwise the remote is left pointing at a repo that is gone. - -## Gotchas - -- A new partition is listed in four places, in import order: `PARTITIONS` in `build.sh`, `CrafterBuildModules` in `Crafter.Build-Platform.cpp`, both arrays in `project.cpp`, and the umbrella `Crafter.Build.cppm`. Then `./build.sh`. -- A `#pragma crafter dependency` target is rebuilt on every load on purpose: clang crashes rather than erroring when it imports a BMI whose own imported PCM was rebuilt underneath it, and the depfile check is what catches a regenerated host cache. Do not optimise the rebuild away. -- A host-tooling library such as Crafter.LintRules may `import Crafter.Build;` without declaring it as a dependency, because loading a project file fills the cache it resolves from. Listing Crafter.Build in its `cfg.dependencies` would clone and build all of crafter-build for every consumer. Its test does link crafter-build, so that test is wired behind `IsTopLevelProject()`: without the guard, crafter-build loading the library as a dependency would load its own `project.cpp` again through the test's `GitProject` and hit the cycle guard. -- `crafter-build clean` leaves a pragma dependency's build alone; it lives with the clone in the cache. -- A project file returns one configuration from `CrafterBuildProject` or several from `CrafterBuildConfigurations`, and `Crafter::Run` works on the list `LoadConfigurations` gives it for both. A new verb has to say what it does with several, and whether it takes all of them or leaves out another project's: `test` and `run` leave out a configuration that another project's file returned and this one returns in turn, which `LoadedProjectOf` tells apart. The load has refused, before a verb sees the list, a returned configuration that a loaded project keeps to itself (`KeptBy`): one the loader took down when that project's file was loaded, among what the configurations the file returned led to through `dependencies` and `tests`, as far as the first configuration on each way that a loaded project's file had returned or another loaded project keeps. -- The limit of as many steps at once as there are hardware threads holds for what runs on `JobPool::Process()`: the jobs `Build()` adds and the commands of `RunBuildCommand`. Among what runs outside it: an `ExternalDependency`'s `cmake --build`, which `BuildCMake` gives `--parallel ` of its own; the tests `RunTests` runs, `--jobs=` of them at once on threads of its own, while other tests may still be building; the Crafter.Build modules `EnsureCrafterBuildPcms` precompiles for the host cache, one after another; and the threads a step starts for itself, lld's for a link and, for an asset, those of the GDeflate compressor in Crafter.Asset, up to 31 for each stream it compresses. The pool is one process's: a self-test of this repository that builds a fixture does so in its own process, on a pool of its own. -- An interface unit takes two compiler runs, one for its BMI and one for the object made from the BMI, and they are two jobs so that the units importing it start once the first is done. `Check` reads staleness off the BMI; the object is `Schedule`'s to look at, which adds the object job alone for a unit whose BMI is up to date and whose object is missing or older than the BMI. A build that fails between the two jobs leaves a unit like that, since no job starts after a failure. -- `Build()` reads what each `.cppm` and `.cpp` declares and imports with clang-scan-deps (`ReadSources` in `Crafter.Build-Clang.cpp`) once the configuration's dependencies and external dependencies are built: the compile command takes their include paths, and a source may include their headers. Until then nothing knows a configuration's modules, so `DuplicateModuleError` and `ImportCycleError` refuse a graph there, after the dependencies are built and before any `.cppm` or `.cpp` of the configuration is compiled; its `.c` and `.cu` sources, which compile while the dependencies are built, may have been by then. A scan is kept in the build directory as an object is, in `scans/` or, for a source outside `cfg.path`, in `scans-outside/`, as JSON holding the compile command it was taken for and what clang-scan-deps wrote, with a dependency file beside it, and taken again when that command differs, when the source or a file the dependency file lists is newer, and when it cannot be read; clang-scan-deps is given that command with its first word made the compiler where clang started with that command takes itself to be: the directory it is installed in, or, for a command whose last of `-canonical-prefixes` and `-no-canonical-prefixes` is `-no-canonical-prefixes`, that of the compiler as written (`ScannedAs`, `Toolchain::InstalledClangxx`). A `Build()` makes its own configuration's modules and units, never a dependency's: those are the dependency's own `Build()`'s to make, and the builds of other configurations built on it read them, through the pass record (`BuildResult::built`): a pass builds a directory once, so of two configurations of one directory, as the loader makes of one project loaded with its args in two orders, only the one it built has the modules of that build. -- Units see a std module rebuilt in place, because their depfiles list the BMIs they import (`-fmodule-file-deps`), but not one that moved to another directory: their old depfiles still name the old one. So anything that changes how the std module is compiled goes into `StdPcmFlags`, which `BuildStdPcm` compiles with and `StdPcmKey` hashes. `VariantId()` hashes `StdPcmKey`, so the build moves with it. A flag added to the command anywhere else leaves both directories where they are. -- A CMake external whose recorded configure inputs (`/.crafter-options`) differ from this build's is built again from an empty build directory, not reconfigured in place: CMake keeps what an old compiler or `--sysroot` compiled, and the check results it cached. -- The bootstrap binary is compiled without `CRAFTER_BUILD_HAS_ASSET`, so `cfg.assets` only works in the self-hosted binary. What an asset is compressed to is decided in one place, `CompressedAssetName` in `Crafter.Build-Clang.cpp`, which an executable's own assets, the ones its dependencies forward and the browser runtime's `files.json` all use; a Flatpak's `files/bin` keeps what those copies record as placed. `CompressAsset` in `Crafter.Build-Asset.cpp` does the compressing and has to load every extension that function maps. -- A warning is printed only when its unit actually recompiles. A build with nothing to do is silent, which is not evidence that a warning is gone. -- `RunCommandWithTimeout` runs its command under `timeout`, which can only start programs, so a shell builtin such as `command -v` fails there wherever no program of that name is on PATH, as on Arch and in the Sdk: a probe built on it reports the tool missing, and whatever it guards is skipped without a word. Probe through `RunCommandChecked`, which goes through `sh`, or `std::system` in a test. -- A std module source only compiles against the headers of its own libc++ release, and a sysroot does not always ship one (Alpine). The Flatpak therefore carries the sources of the release next to the bundled one under `share/crafter-build/libc++-modules//`, one `libcxx--modules` manifest module each. When the bundled LLVM is bumped, keep the release it leaves behind as such a module: sysroots on the stable distro stay on it for months. The native loop has no such directory; stage one by hand under `share/crafter-build/` to test against a foreign sysroot. -- The Flatpak carries the debugging tools for what it builds, because those programs run in its sandbox: lldb is a project of the `llvm` module, with `LLDB_ENABLE_PYTHON`, `LIBEDIT`, `CURSES`, `LIBXML2` and `LZMA` set ON so that a missing dependency fails the configure step (SWIG through Python, which needs it), and the `swig` and `libedit` modules come before it. The Khronos validation layer is the `vulkan-validation-layers` module plus four modules before it, build-only except for SPIRV-Tools' programs (`spirv-val` and the rest), all after the LLVM and WASI modules, so that bumping them reuses the cached LLVM and WASI builds. The layer follows the Sdk's Vulkan loader: when `runtime-version` moves to a runtime with a newer loader, move the layer to the Vulkan SDK release of that loader and take the other four revisions from that release's `scripts/known_good.json`. -- The Flatpak carries weston for the tests that set `Test::wayland`: the `libevdev`, `libinput`, `libdisplay-info` and `weston` modules, just before `crafter-build`, so that bumping them rebuilds only them and crafter-build. weston's frontend links the first three whatever the backend, so they ship. weston is configured with its headless backend, its GL renderer and its desktop shell, and with none of its other backends or shells and no Vulkan renderer. libinput is a `git` source pinned by commit, since its 1.32.0 release has no tarball attached. `tests/HeadlessCompositor` stands in a fake compositor, so the suite needs no weston: only a project's own tests that set `Test::wayland` run the real one. -- The wasm compile flags live in one place, `WasmBaselineFlags` in `Crafter.Build-Clang.cppm`: the std module and every unit have to agree on them, and `VariantId()` and the std PCM directory hash them, so a change rebuilds instead of mixing old and new BMIs. They enable C++ exceptions, so the link takes the exception-enabled libc++ and libunwind from the sysroot's `lib//eh/` (wasi-sdk 33 and later). The Flatpak's sysroot has them and a distro's may not; where they are missing the wasm tests skip, so run those through the Flatpak. A browser page checks the engine with the `WasmBaselineProbes` named in `variants.json`. -- `WasiBrowserRuntimeExit` runs `wasi-runtime/runtime.js` under node and skips where there is none. The Flatpak has no node, so CI never runs it: after touching `runtime.js`, run the suite in the native loop with node on `PATH`. -- `CudaCompile` builds with a real CUDA toolkit whose `lib64` beside `bin/nvcc` holds `libcudart_static.a`, and skips everywhere else, and nothing in CI installs one: after touching how `cfg.cuda` is compiled, or how the CUDA runtime is linked and handed on through `BuildResult::runtimeLibs`, run it in the native loop on a machine with such a toolkit, as Arch's `/opt/cuda` is. Where nvcc is looked for, `/run/host` and its links included, is `ToolchainResolve`'s to check, on staged directories, so that one runs everywhere, and so is whether the `lib64` beside it holds the static runtime. `CudaMissing` checks what a build with a `.cu` says when no nvcc is found, and needs no toolkit either. -- `VariantId()` names the output directory, so CI globs `bin/crafter.build-exe---*/` rather than predicting the hash. The hash includes the compiler, so after a toolchain update the previous variant's directories stay in `bin/` and `build/` until `clean`, and such a glob matches both. -- AGENTS.md is build output: the self-host build and `test` write it from `AGENTS.template.md`, with the `AGENTS.consumer.md` of each dependency that ships one (Crafter.Math, today) merged in, and it is gitignored. Edit the template; an edit made in AGENTS.md is gone after the next build. A fresh clone or worktree has no AGENTS.md until its first `./bin/crafter-build` or `test`, since `./build.sh` does not write it. A harness from before the template (3.0.0 and older) never creates one and keeps its section in one it finds; the next build with a current harness writes it over. diff --git a/README.md b/README.md index 3dc7f20..77514ec 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,22 @@ # Crafter Build -A C++26 modules build system. Project descriptions are written in C++ with no JSON, no Lua, no embedded DSL. You write a `project.cpp` that constructs a `Configuration`, or several, and returns them. Crafter Build compiles, loads, and executes it. +A C++26 modules build system. Project descriptions are written in C++ with no JSON, no Lua, no embedded DSL. You write a `project.cpp` that constructs a `Configuration` and returns it. Crafter Build compiles, loads, and executes it. ## Install -crafter-build ships as a Flatpak that carries its own clang, lld, libc++ and WASI sysroot, so every machine builds with the same compiler, and lldb and the Vulkan validation layers to debug the result (see [Debugging](#debugging)): +crafter-build ships as a Flatpak that carries its own clang, lld, libc++ and WASI sysroot, so every machine builds with the same compiler: ```bash flatpak remote-add --if-not-exists catcrafts https://flatpak.catcrafts.net/catcrafts.flatpakrepo flatpak install catcrafts net.catcrafts.CrafterBuild -alias crafter-build='flatpak run --die-with-parent net.catcrafts.CrafterBuild' +alias crafter-build='flatpak run net.catcrafts.CrafterBuild' ``` -`--die-with-parent` ends the sandbox with the `flatpak run` that started it. Without the flag, killing only the `flatpak run` process leaves the sandbox running: a build carries on writing into `bin/` and `build/`, and a program started with `-r` keeps running. With it, bubblewrap kills everything in the sandbox with SIGKILL when the `flatpak run` process dies or when that process's parent does. For `crafter-build …` or `crafter-build … &` typed at a bash or zsh prompt, that parent is the shell, so the sandbox ends with the shell, even after a `disown`. Ctrl-C reaches the program either way. - -Releases are published to the `stable` branch that the commands above install, and every release also attaches a single-file bundle on the Forgejo releases page (`flatpak install --user crafter-build-.flatpak`). The sandbox sees the host's own files where it shares them, the home, `/mnt`, `/opt`, `/srv` and `/run/media` among them, so a project can live there; it has its own `/tmp`, `/var`, `/usr`, `/etc` and `/app`. Binaries built for the host link the bundled `libc++.so.1` through an rpath into the Flatpak: they run inside it (`-r`, the test runner), and are not meant to be copied out onto the host. To run a program outside crafter-build's sandbox, package it as a Flatpak of its own ([Flatpak output](#flatpak-output)). +Pre-release builds of `master` are the `beta` branch (`flatpak install catcrafts net.catcrafts.CrafterBuild//beta`), and every release also attaches a single-file bundle on the Forgejo releases page (`flatpak install --user crafter-build-.flatpak`). The sandbox sees the whole host filesystem, so projects can live anywhere. Binaries built for the host link the bundled `libc++.so.1` through an rpath into the Flatpak: they run inside it (`-r`, the test runner), and are not meant to be copied out onto the host. ## Writing a project.cpp -Crafter Build loads a `project.cpp` from the current directory. The file exports one function: `CrafterBuildProject`, which returns a populated `Configuration`, or `CrafterBuildConfigurations` for [several](#several-configurations): +Crafter Build loads a `project.cpp` from the current directory. The file exports one function that returns a populated `Configuration`: ```cpp import std; @@ -41,119 +39,13 @@ extern "C" Configuration CrafterBuildProject(std::span a } ``` -Run `crafter-build` in that directory, outputs land at `bin/myapp----/myapp` and intermediates at `build/myapp----/`. The hash covers everything that changes what is compiled (build type, defines, flags, sysroot, the compiler itself), so two such builds never share a directory. After a compiler update, a new crafter-build release included, the first build starts a fresh directory and recompiles. `crafter-build clean` removes the ones left behind. Add `-r` to run the produced executable straight after a successful build, in its own directory, where its shaders, `cfg.files` and assets are; a wasm32 one runs under wasmtime, or wasmer where there is no wasmtime, with no directory given to it, and one built for the browser (`EnableWasiBrowserRuntime`) is served over HTTP from that directory instead. - -A `.cpp`, `.c` or `.cu` of a configuration is compiled into an object named from its path: `a/Thing.cpp` into `objects/a/Thing_impl.o` in that `build/` directory, at the source's path from `cfg.path`, and a source outside `cfg.path` into `objects-outside/` there, at its whole path. Two sources may therefore have the same file name in different directories, and a `.c` may lie beside a `.cpp` or a `.cu` of its name. The progress line of such a source's compile names it by the same path, `Compiling a/Thing.cpp`. The link, and the archive step of a static library, read their objects from a file in that directory, `.objects`, so the command is no longer for many sources than for one. - -crafter-build orders a configuration's units by what their sources import: a unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions. What a `.cppm` or `.cpp` declares and imports is read by clang-scan-deps, which preprocesses the source with the command it is compiled with, so it reads them as the compiler does: an import in a comment, in a string literal or in a branch that `#if` leaves out is none, and a define or a header decides one as it does for the compile. It reads them once the configuration's dependencies are built, since the command takes their include paths, and keeps what it found in the `build/` directory, as it keeps objects: in `scans/` at the source's path from `cfg.path`, and in `scans-outside/` at its whole path for a source outside `cfg.path`, until the source, a file it includes or the command changes. Interface units of one configuration that import each other cannot be built in any order: two partitions, a partition and its own module, or two modules. Such a configuration is refused once its sources are read, before any of its `.cppm` and `.cpp` is compiled, with an error that names the units in the order they wait. - -A build runs at most as many of its steps at once as the machine has hardware threads, however many sources are stale: the scans and the compiles of its sources, its shaders and assets, and its links and archives, counted together for the project and the dependencies it is built on. An `ExternalDependency`'s CMake build is not among them and is given that many jobs of its own, and the tests `crafter-build test` runs are counted by `--jobs=`. A step counts as one whatever threads it starts for itself: a link runs on lld's, and an asset is compressed on threads its compressor starts. - -### Several configurations - -A project that builds more than one thing, such as a library and the tool that comes with it or the programs of one repository, returns all of them from `CrafterBuildConfigurations` instead. They need not have anything to do with each other, and `crafter-build` builds every one of them: - -```cpp -extern "C" std::vector CrafterBuildConfigurations(std::span args) { - static std::deque owned; - - Configuration& lib = owned.emplace_back(); - lib.path = "./"; - lib.name = "mylib"; - lib.outputName = "mylib"; - lib.type = ConfigurationType::LibraryStatic; - std::array libIfaces = { "interfaces/MyLib" }; - std::array libImpls = { "implementations/MyLib" }; - lib.GetInterfacesAndImplementations(libIfaces, libImpls); - - Configuration& tool = owned.emplace_back(); - tool.path = "./"; - tool.name = "mytool"; - tool.outputName = "mytool"; - tool.type = ConfigurationType::Executable; - tool.dependencies = { &lib }; - std::array toolIfaces = {}; - std::array toolImpls = { "implementations/main" }; - tool.GetInterfacesAndImplementations(toolIfaces, toolImpls); - - return { &lib, &tool }; -} -``` - -A project file has one of the two functions, never both. `CrafterBuildConfigurations` gets the same args as `CrafterBuildProject`, and `ProjectArgs()` and `IsTopLevelProject()` answer the same inside it. It returns pointers, so the configurations have to stay where they are for as long as crafter-build runs. A `std::deque` that the file only adds to keeps them there, with a new set for every call; a `std::vector` would move them when it grows, and a single static `Configuration` would be filled in again by every load of the file. A pointer that `GitProject` or `LocalProject` returned can be in the list as well, which is how one file builds a set of sibling projects. - -With several configurations: - -- **A build** builds all of them in one pass, so what two of them depend on is built once. One that fails does not stop the others, and the build then fails with the errors of the ones that failed. -- **`test`** runs the tests of every one the file made itself, in one run. By default a test is built from `tests//` into `build/-/` and `bin/-/`, whichever configuration declares it, so a test belongs to one of them: where two each declare a test that would be built into the same directories, both tests fail without being built and name the two configurations. Give each test a name of its own. -- **`run`** offers the scripts of every one the file made itself: a script gets the configuration it is declared on as `ctx.project`, and a name two of them declare is an error. -- **`lint`** and **`format`** take the rules and the sources of every one that lies in the project's directory, and a rule two of them register under one name runs once. -- **`-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 to choose from they stop and name them, as `install` and `bundle` do when none is packaged: `-r` once everything is built, `install` and `bundle` before anything is. -- **A configuration of another project**, which the file got from `GitProject` or `LocalProject` and returns, is built with the rest and counts for `-r`, `install` and `bundle`. Its tests and its scripts stay that project's. -- **Two that would be built into the same directory**, as two with the same `path` and `name` and no other difference are, are refused by a build, `test`, `-r`, `install` and `bundle`, before anything is built. Give each a `name` of its own. A build, `-r`, `install` and `bundle` refuse two more sets before they build anything: configurations 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. -- **`cfg.dependencyNotes`** is read on every one the file made itself (see [Dependency notes for agents](#dependency-notes-for-agents)). - -## Flatpak output - -A program crafter-build's Flatpak links for Linux without a sysroot takes the libc++, libc++abi and libunwind of its LLVM and the glibc of its runtime, so outside the Flatpak it starts only on a host that has those libraries and a glibc with every symbol version they and the program reference, 2.38 or newer for the bundled libc++. A build lays the program out as a Flatpak of its own when it is packaged: - -```cpp -cfg.packaging = Packaging::Flatpak; // or, for one build: --packaging=flatpak, where project.cpp calls ApplyStandardArgs -``` - -Its bin directory then holds `files/`, what becomes `/app` inside the app's sandbox: - -``` -bin/myapp-/ -└── files/ - ├── bin/ myapp and the files it reads beside it: shaders, cfg.files, assets - ├── lib/ libc++, libc++abi, libunwind, and the shared libraries it links from its dependencies and from crafter-build's /app/lib - └── share/ the desktop entry, metainfo and icons under the app-id, and cfg.flatpak.share -``` - -`-r` runs `files/bin/myapp` from that directory, inside crafter-build's sandbox, against the libraries in `files/lib`, the ones the app carries. To install the app for yourself, or to hand it to someone else: - -```bash -crafter-build install # build it and install it for this user: `flatpak run local.crafterbuild.myapp` -crafter-build bundle # build it into bin/myapp-.flatpak, for `flatpak install --user ` -``` - -Both make the app first. Without modules, crafter-build makes `build/flatpak-apps//build-dir` of `files/`, as hard links to the build's own where they can be made and copies where they cannot, and a `metadata` naming the app, its runtime and the Sdk, and the host's `flatpak build-finish` finishes it by flatpak's own rules: it adds the command and the sandbox's permissions to the metadata and writes `export/`, what the host sees of the app, such as its desktop entry and icons. With modules, flatpak-builder does all of it. - -`install` puts the app into a repo of the project's, in `build/flatpak-apps//`, and installs it from a user remote named `crafter-build-`, updating what an earlier install left; it prints how to remove both, which matters before `crafter-build clean` deletes the repo. Installs of one app-id from two checkouts take turns on that remote, by a lock in `~/.cache/crafter.build/flatpak-remotes/` that every crafter-build installing for the user takes, the Flatpak's too. `bundle` writes a single file that `flatpak install --user` installs, naming Flathub's repository in it for the runtime. `install` takes the runtime from an installation that has it, the system's or the user's, or from a remote of the user's installation; where none does, flatpak stops with `requires the runtime ... which was not found`, and `flatpak install flathub org.freedesktop.Platform//26.08`, or the Sdk for an app that runs on it, puts it in place. An app with modules needs `org.freedesktop.Sdk//26.08` whatever it runs on, since flatpak-builder makes it with that: `flatpak install flathub org.freedesktop.Sdk//26.08`. Both run the host's `flatpak`, and with modules its flatpak-builder, which crafter-build's Flatpak reaches through the Flatpak session helper (the `org.freedesktop.Flatpak` permission) and uses for nothing else. The permission belongs to the whole sandbox, so a `project.cpp`, its scripts, the builds of its dependencies and the programs `-r` and `test` start can reach the host through it too; through the sandbox's `--filesystem=host` they could already write files the host runs, such as `~/.bashrc`. The host sees the project at the path crafter-build does where the sandbox shares the host's directories, as it does the home, `/mnt`, `/opt`, `/srv` and `/run/media`, and not in the sandbox's own `/tmp`, `/var`, `/usr`, `/etc` and `/app`. Before building, `install` and `bundle` ask the host whether it sees the project's `bin/` and `build/` where crafter-build does, following their links as the host does: they start its `flatpak` in a directory made in each for the question and removed again, and refuse the project where it cannot start there. To try the app on the host without installing it, run `flatpak build --runtime --readonly build/flatpak-apps//build-dir myapp` there after an `install` or `bundle`: it runs on the app's runtime, with the filesystems and the environment its metadata grants. - -Installed, the program starts in the directory it is started from, when its permissions let it see that directory, and in `$HOME` otherwise. A program that reads its own files therefore finds them next to its executable (`/proc/self/exe`) rather than in the working directory, which is only its own under `-r`. - -What the app is installed as is `cfg.flatpak`; a hello world sets none of it: - -```cpp -cfg.flatpak.appId = "net.example.MyGame"; // default: local.crafterbuild. -cfg.flatpak.runtime = FlatpakRuntime::Sdk; // default Platform; the Sdk has git, gcc and the like -cfg.flatpak.permissions = { "--socket=pulseaudio" }; // finish-args, spelled as in a Flatpak manifest -cfg.flatpak.desktopFile = "packaging/MyGame.desktop"; // installed as .desktop; its Icon= is the app-id -cfg.flatpak.metainfo = "packaging/MyGame.metainfo.xml"; -cfg.flatpak.icons = { "packaging/icon.svg" }; // an .svg is scalable, a square .png goes under its size -cfg.flatpak.share = { // under /app/share, not beside the program like cfg.files - { "data", "mygame/data" }, // a directory: every regular file in it, at its path inside it - { "LICENSE", "licenses/net.example.MyGame/LICENSE" }, -}; -cfg.flatpak.modules = { "packaging/flatpak/node.yaml" }; // flatpak-builder modules for more in /app -``` - -- **Permissions** are the sandbox's: sockets, devices, shares, filesystems, bus names, environment. A library declares what every program built on it needs in its own `cfg.flatpak.permissions`, and those reach the program before the program's own, which can take one back (`--nosocket=x11`). `install` and `bundle` print the resulting list, with where each came from, and hand it to `flatpak build-finish`, which refuses a misspelled argument, and a share, socket, device or feature flatpak does not have, naming the ones it has. The build itself does not read them, so changing one builds nothing. -- **The runtime** is always at the branch crafter-build runs on (26.08 today), since the program links that runtime's glibc. The Platform is enough to run a program; the Sdk is for one that runs tools such as git at run time. -- **Share entries** are files of the project the program reads from `/app/share` instead of from beside itself: data it finds at `/../share/`, licences. `files/share` is the build's own, so they are kept there as long as they are listed and removed once they are not, and anything else put there is removed too. `-r` runs the program from `files/bin`, so the same `../share` lookup finds them. Any file can be one, a second desktop entry or an add-on's metainfo among them: what flatpak exports of an app's `share/`, it exports of them too, by its own rules, such as an icon, D-Bus service, MIME package, search provider or KRunner plugin named after the app-id. `flatpak build-export` refuses an exported icon that is not a square image and a D-Bus service that is not a key file, and warns of the app's own desktop entry where `desktop-file-validate` rejects it; a second desktop entry, a MIME package or metainfo it exports as it is. A directory entry places every regular file in it, and every link to one, at its path inside it; anything else in it is left out: empty directories, links to directories, dangling links, FIFOs and sockets. Two files for one path in `share/`, a field's own file among them, or a file where another entry needs a directory, fail the build. The app's desktop entry, `applications/.desktop`, is held to `desktopFile`'s checks whichever placed it. A directory that holds what the build writes fails too, since it would be copied into itself, growing each time the app is built or exported: `files/`, and the app's directory in `build/flatpak-apps/`, where `install` and `bundle` put another copy of `files/` and the exported app, the project's own directory holding both, as written and where links lead, so also where `bin/` is a link elsewhere. So does one that lies in them, which is the build's own output. -- **Modules** are for what the app needs in `/app` besides the program: a runtime it starts, a tool it runs, data built from source. They are flatpak-builder module files in Flatpak's own format, which crafter-build names and never reads. With any, `install` and `bundle` have the host's flatpak-builder (or the `org.flatpak.Builder` app) make the app with `org.freedesktop.Sdk//26.08`, which the host then needs as well as the runtime, from a manifest in `build/flatpak-apps//` that lists them and copies the built program in last, so it is not compiled again; flatpak-builder's defaults then also strip it and split its debug info into a `.Debug` extension. Translations under `share/locale` stay in the app rather than going into a `.Locale` extension, which a bundle would leave out. `-r` runs the program without them. -- **What cannot be a Flatpak** fails the build saying why: Windows and wasm targets, which keep their `.exe` and `.wasm`; a build against a sysroot, which links that sysroot's libraries and not the runtime's, or one for musl, a C library no runtime has; an architecture other than the runtime's; a build against `CRAFTER_BUILD_LIBCXX_DIR`, since a Flatpak carries the toolchain's own libc++, built against the runtime's glibc; and a build by a native crafter-build, whose programs link the host's glibc, unless `CRAFTER_BUILD_FLATPAK_INFO`, which the tests set, names a runtime. A dependency's executables stay as linked even when `--packaging=flatpak` reaches their project, since their consumers run them by path, and tests are never packaged. A dependency that sets `cfg.packaging` in its own `project.cpp` is packaged, and the files its `cfg.flatpak` names are found in its own directory, as its `cfg.files` are. -- **For other machines**, build with `--march=x86-64-v3` rather than the default `native`, which can crash with SIGILL on an older CPU. Pass it on the command line or in `CRAFTER_BUILD_MARCH`: either reaches every configuration of the program that `ApplyStandardArgs` is called on, a sibling's whose `project.cpp` calls it included, while CMake externals are compiled without `-march`, and a `#pragma crafter dependency`, tooling built for `project.so` alone, with `-march=native`. A program with CUDA sources also needs a `--cuda-arch=` other than `native`, such as `all-major` (see CUDA), and `bundle` warns of a bundle built for either `native`. - -Without packaging (`Packaging::None`, and for now `Default`), a program is the executable as linked: it runs inside crafter-build's sandbox (`-r`, `test`, `run` scripts), and on a host only where the host has what it links. +Run `crafter-build` in that directory, outputs land at `bin/myapp----/myapp` and intermediates at `build/myapp----/`. The hash covers everything that changes what is compiled (build type, defines, flags, sysroot, the compiler itself), so two such builds never share a directory. After a compiler update, a new crafter-build release included, the first build starts a fresh directory and recompiles. `crafter-build clean` removes the ones left behind. Add `-r` to run the produced executable straight after a successful build. ## Dependencies Three kinds, all fetched/built incrementally: -**Cross-project Crafter sub-projects** — point `cfg.dependencies` at another `Configuration*`. Cross-project module imports (`import OtherProject;`) are tracked per-import: only the modules that actually import a changed dep rebuild. A dependency's headers reach the C++ and C compiles of the projects built on it by themselves: its directory and every directory named `include` in its tree are on their include path, except those under a directory named `bin` or `build`, where builds leave their output. A header kept under one of those needs an `-I` of its own in the `cfg.compileFlags` of the projects that include it. A `cfg.cuda` source gets neither. +**Cross-project Crafter sub-projects** — point `cfg.dependencies` at another `Configuration*`. Cross-project module imports (`import OtherProject;`) are tracked per-import: only the modules that actually import a changed dep rebuild. **External git+cmake deps** — for things like glslang. Declare in `cfg.externalDependencies`: @@ -182,21 +74,13 @@ Configuration* sibling = LocalProject({ .projectFile = "../Crafter.Math/project. cfg.dependencies = { math }; ``` -The sibling's entry point gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that exports modules and that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths, unless both lists give the project one build directory, as two orders of the same flags of its own can: it is then built once. Releases up to 2.2.0 forward nothing when `.args` is left out. +The sibling's `CrafterBuildProject` gets the args this `project.cpp` was loaded with (`ProjectArgs()`), so `--target=`, `--march=`, `--debug` and the project's own flags reach every sibling down the chain. That is all of them: `cfg.projectArgs` holds only what `ApplyStandardArgs` did not interpret, and passing it on would drop the target and the build type. Set `.args` to send something else: `{}` for nothing, or a list built from the project's args, such as one without a flag only this project reads. Build such a list once and give it to every sibling. A project that two paths load with different lists would end up in the program twice, so the build stops with an error that names both paths. Releases up to 2.2.0 forward nothing when `.args` is left out. -The default is read when the spec is made, so make it inside the entry point, `CrafterBuildProject` or `CrafterBuildConfigurations`, on the thread that calls it. A spec made at namespace scope, on a thread of your own or in a script forwards nothing. +The default is read when the spec is made, so make it inside `CrafterBuildProject`, on the thread that calls it. A spec made at namespace scope, on a thread of your own or in a script forwards nothing. Clones share the external cache and identical specs share one `Configuration`. An unpinned source is `git pull`ed on every invocation, set `.commit` for reproducible, offline-after-first-fetch builds. -A sibling whose project file returns [several configurations](#several-configurations) gives its first one, or the one `.configuration` names by its `name`: - -```cpp -Configuration* packer = LocalProject({ .projectFile = "../tools/project.cpp", .configuration = "packer" }); -``` - -Only the configuration a consumer names is built for it, with what that one depends on, and specs that differ only in `.configuration` share one load of the sibling. A name the sibling does not have is an error that lists the ones it has, and a name two of its configurations share is an error too. A library that comes to return a second configuration puts it after the first, so that a consumer that names none keeps getting the one it had. Its consumers then need a crafter-build that has `CrafterBuildConfigurations`: an older one loads only a `CrafterBuildProject`. - -A project loaded this way runs its entry point as a dependency, and `IsTopLevelProject()` is `false` while it does (`true` in the project crafter-build was pointed at, and outside any project file). Wire test-only dependencies behind it: a library whose test links crafter-build itself would otherwise load crafter-build's `project.cpp` from inside crafter-build and recurse. +A project loaded this way runs its `CrafterBuildProject` as a dependency, and `IsTopLevelProject()` is `false` while it does (`true` in the project crafter-build was pointed at, and outside any project file). Wire test-only dependencies behind it: a library whose test links crafter-build itself would otherwise load crafter-build's `project.cpp` from inside crafter-build and recurse. ### Dependencies of project.cpp itself @@ -213,27 +97,13 @@ import Crafter.LintRules; #pragma crafter dependency "" [branch "" | commit ""] [project ""] ``` -Such a dependency is built for the host, whatever the project targets, and its `project.cpp` gets none of the project's args. Of a project that returns [several configurations](#several-configurations), the dependency is the first. +Such a dependency is built for the host, whatever the project targets, and its `project.cpp` gets none of the project's args. ### Dependency notes for agents -An agent working on a project reads its `AGENTS.md`, which says nothing about the libraries the project builds against unless someone copied that in by hand. A library ships it instead: an `AGENTS.consumer.md` beside its `project.cpp`, written for whoever uses the library rather than whoever works on it. - -A consumer that wants its dependencies' notes writes its own instructions in an `AGENTS.template.md` beside its `project.cpp`, and commits that instead of an `AGENTS.md`. `crafter-build`, `crafter-build test`, `crafter-build install` and `crafter-build bundle` then write `AGENTS.md` from the template with the notes added, so `AGENTS.md` is build output and stays out of version control: a dependency that changes its notes changes nothing a diff shows. A project with a committed `AGENTS.md` moves over from the directory of its `project.cpp`: - -```bash -git mv AGENTS.md AGENTS.template.md -echo /AGENTS.md >> .gitignore -``` - -What a build then writes: +An agent working on a project reads its `AGENTS.md`, which says nothing about the libraries the project builds against unless someone copied that in by hand. A library ships it instead: an `AGENTS.consumer.md` beside its `project.cpp`, written for whoever uses the library rather than whoever works on it. When a consumer has an `AGENTS.md` beside its own `project.cpp`, `crafter-build` and `crafter-build test` keep its dependencies' notes in a section of it: ```markdown - -# The template's text - -... - @@ -246,13 +116,11 @@ What a build then writes: ``` - Each file goes in as written, under a line naming the dependency: its repository's name, or a `LocalProject`'s directory name. That reads the same on every machine, and for a `--local` checkout and its git clone alike. The file lands among the consumer's own headings, so start it with a `##` heading that names the library. -- The section goes after the template's text and a blank line. To have it elsewhere, put the begin and end marker lines in the template where it should go: whatever they enclose is replaced. A template moved over from a committed `AGENTS.md` has them where its section was, around notes that can be deleted. -- `AGENTS.md` is written only when its text changes, in place, so a `CLAUDE.md` linked to it, its ownership and a read-only `AGENTS.md` are respected. An edit made in it is gone after the next build, and a fresh clone has none until its first build. The template is never written. -- An `AGENTS.md` that no build wrote, such as a committed one still next to a new template, is never replaced: each build warns instead, until it is deleted. Without a template, `AGENTS.md` is never touched. One that still holds a section from crafter-build 3.0.0, which kept the notes in a committed `AGENTS.md`, gets a warning: move it over as above, or delete the section. -- In a build or a test run that is not refused before it starts, the update runs once `project.cpp` has loaded and before the project compiles, so a build that fails while it compiles still has the notes. It does not run for a `project.cpp` that fails to load, for `test --list`, `lint`, `format`, `run` and `clean`, or for a verb that is refused before it starts a build: an `install` or `bundle` of a project that is not packaged as a Flatpak, or for which crafter-build cannot run the host's flatpak, and a build, `test`, `install` or `bundle` of [several configurations](#several-configurations) that are refused as a set. +- The section is appended the first time, after a blank line, and rewritten in place after that, wherever it has been moved to. Edits inside it are lost on the next build; the text around it is left as it is. The file is written only when the section changes, in place, so hard links, ownership and a read-only `AGENTS.md` are respected, and an `AGENTS.md` is never created. +- The update runs once `project.cpp` has loaded and before the project compiles, so a build that fails still has the notes. A `project.cpp` that fails to load gets no update. `test --list`, `lint`, `format`, `run` and `clean` leave the file alone. - The section follows what the build loaded: a dependency that only some flags pull in (a `--target=`, a flag of the project's own) comes and goes with them. An unpinned dependency's notes follow its default branch, as its code does, so the section can change on any build. Pin a `commit` to decide when. - A library reached through two specs, pinned at one revision here and another further down, is described once, as the nearer one has it. -- When there are notes to write, unbalanced markers in the template leave `AGENTS.md` as it is, with a warning. A notes file that would break the section (a code block it never closes, a marker line of its own) is left out, also with a warning. Markers quoted inside a fenced code block don't count. +- When there are notes to write, unbalanced markers leave the file as it is, with a warning. A notes file that would break the section (a code block it never closes, a marker line of its own) is left out, also with a warning. Markers quoted inside a fenced code block don't count. `cfg.dependencyNotes` picks the dependencies: @@ -260,27 +128,10 @@ What a build then writes: |---|---| | `DependencyNotes::Transitive` (default) | everything the project builds against, all the way down: its `dependencies` and its own `#pragma crafter dependency` tooling | | `DependencyNotes::Direct` | only the projects the project's own configurations and `#pragma crafter dependency` lines name | -| `DependencyNotes::None` | none: `AGENTS.md` holds the template's text alone | +| `DependencyNotes::None` | none, and a section from an earlier build is removed | Three things never count: the project's own `AGENTS.consumer.md`; its tests' dependencies, since a plain build never looks at the tests; and a dependency's `#pragma crafter dependency` tooling, which is about how the dependency is built, not how it is used. -In a project of [several configurations](#several-configurations), the `dependencyNotes` of each one the file made itself selects among what that one is built against, and a dependency's notes are in when a configuration that asks for them leads to it: what a `Direct` configuration names is followed further when a `Transitive` one reaches it too. The project's own `#pragma crafter dependency` tooling, and a configuration of another project that the file returns, which counts as a dependency here, go by the widest setting among the configurations the file made itself. - -## CUDA - -`cfg.cuda` lists CUDA sources, named without `.cu`. A relative name is read from the directory crafter-build runs in, except in a project loaded through `GitProject` or `LocalProject`, whose relative names crafter-build rebases onto that project's directory: - -```cpp -cfg.cuda = { fs::absolute("kernels/blur") }; // kernels/blur.cu -``` - -nvcc compiles each into an object that joins the configuration's other objects, and the configuration links the CUDA runtime of nvcc's toolkit, as does whatever is built on it: `libcudart_static.a` from the toolkit's `lib64`, with the `-lrt -lpthread -ldl` nvcc's own link puts after it. Being static, it takes no run path into the toolkit. It comes after `cfg.linkFlags` and the libraries of what the configuration is built on, so a `-lcudart` named there is the one the linker takes. A toolkit whose `lib64` holds no `libcudart_static.a`, as where a distribution keeps the toolkit's libraries in its own directories, gets no runtime linked: `cfg.linkFlags` names it, as before. - -- **The toolkit** is the one `CUDA_PATH` names, else the first of `/opt/cuda`, where Arch's package installs it, and `/usr/local/cuda`, the link NVIDIA's installer and packages make to theirs, that has a `bin/nvcc`, else the first `nvcc` in an absolute entry of `PATH`. A `CUDA_PATH` without a `bin/nvcc` is an error, not a reason to look elsewhere. `crafter-build --version` prints the nvcc it found and, where there is one, the static runtime beside it; a build with a `.cu` to compile and no nvcc says where it looked. -- **In the Flatpak**, `/opt` and your home are where the host has them, the host's `/usr/local/cuda` is found under `/run/host`, as is the toolkit it is a link to, and `PATH` is the sandbox's own `/app/bin:/usr/bin`, so for a toolkit anywhere else, set `CUDA_PATH`. nvcc compiles the host code with the Sdk's `g++` (GCC 16.2), not the host's: `NVCC_CCBIN` still applies, and names a path inside the sandbox. The programs `-r` and `test` start find the driver's `libcuda.so.1` in the runtime's NVIDIA GL extension for the host's driver. -- **The GPU architecture** is `cfg.cudaArch`, nvcc's `-arch`. It defaults to `native`, the GPUs of the machine that builds, as `march` defaults to its CPU; where there is none, nvcc warns and uses its own default (sm_75 in CUDA 13.4). Like `-march=native`, it is for a program that runs where it is built: it carries no PTX, which a GPU of a newer architecture compiles when it loads the program. For other machines, build with `--cuda-arch=all-major`, nvcc's major architectures (`sm_*0`) and its earliest, with the PTX of the newest major, or name one, such as `sm_89`, which comes with its own PTX. `--cuda-arch=` and `CRAFTER_BUILD_CUDA_ARCH` set it where `project.cpp` calls `ApplyStandardArgs`, as `--march=` and `CRAFTER_BUILD_MARCH` set `march`, and a test inherits it. Another architecture builds in a directory of its own, and so does `native` when the GPUs change: the NVIDIA GPUs on the machine's PCI bus (its display devices, PCI class 0x03), the slots they are in, `CUDA_VISIBLE_DEVICES` and `CUDA_DEVICE_ORDER` key it. That is crafter-build's reading of the machine, not nvcc's own: after a change it cannot see, such as a GPU bound to another driver, run `crafter-build clean`, or build with a named architecture, which depends on nothing on the machine. -- **nvcc gets** `-O3` and `-arch`, beside `-c`, the `.cu` and its outputs (`-o`, and `-MD -MF` for the depfile): none of the include paths, defines and `cfg.compileFlags` the C and C++ compiles get, and no `-g` for `cfg.debug`. A `.cu` compiles again when it, or a header it includes, is newer than its object, as a C or C++ source does. - ## Tests Tests live under `tests//`. The simplest case is a single C++ file: @@ -299,9 +150,8 @@ Test conventions: - **Exit codes**: `0` = ✅ pass, nonzero = ❌ fail, **`77`** = ⏭ skipped (autoconf convention; use it for runtime opt-outs like "tool not on PATH"). - Each test runs in its own subprocess — a segfault doesn't take the runner down. -- Each test runs with `TMPDIR` naming a directory of its own, `/` in a directory made for the run in the temp directory, or, where the run has given that name out already, the first of `-2`, `-3` and on that it has not, so `fs::temp_directory_path()` in a test is the test's alone, even with another run going at the same time. Its path is longer than the temp directory's by 28 bytes and the name of the test's own directory, room a test that binds a Unix socket there has to leave: a socket's path holds 107 bytes. That takes a runner that hands the test `TMPDIR`, as running it directly and qemu-user do: under wine a Windows test does not get `TMPDIR`, and its `TMP`, `TEMP` and temp directory are the Wine prefix's, which every run in that prefix shares; wasmtime gives a test no environment at all. What a test leaves in its `TMPDIR` is removed when it passes or skips. When it fails, crashes or times out, what it left is kept, and its log in `build/test-logs/` says where, as does what is printed of a test that fails or crashes. A later run removes it once the run's directory has gone a minute unchanged: a minute after the run that kept it ended, or, where that run was killed, a minute after it last made or removed a test's directory there. A test that builds against a sysroot or mingw prefix it stages there, or has crafter-build fetch a repository it stages there (an `ExternalDependency` or a `GitProject` of it), keys crafter-build's cache on that path or URL, which is a new one every run: point `XDG_CACHE_HOME` into its `TMPDIR` as well, or every run leaves an entry of its own in the cache. -- Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()` tests (`--jobs=`). The steps of their builds share one limit, a build's: as many at once as there are hardware threads. -- Stdout+stderr is captured and printed atomically on completion. A test that fails, crashes or times out once it is built also writes what it printed, and what crafter-build said of it, to `build/test-logs/.log`, when that is anything, and, where it sets `Test::wayland` and ran, what its compositor printed, if anything, to `.compositor.log` beside it (what a compositor that did not start printed is in `.log`); one that failed to build, or did not get that far, writes neither. `` is the test's name with `-2`, `-3` and on after it where the run has given that name out already, as two configurations or two targets may each declare a test of one name. +- Default timeout is 60 s per test, runs in parallel up to `hardware_concurrency()`. +- Stdout+stderr is captured and printed atomically on completion. Failed/crashed/timed-out tests also write to `build/test-logs/.log`. - A broken fixture `project.cpp` is reported as a single failed test, not a fatal error — other tests still run. CLI: @@ -312,9 +162,8 @@ crafter-build test 'Unit*' # glob-filter te crafter-build test --list # enumerate without running crafter-build test --target=x86_64-w64-mingw32 # only tests for this target crafter-build test --target=x86_64-w64-mingw32 --runner=cmd:wine -crafter-build test --jobs=1 # one test at a time +crafter-build test --jobs=1 # serial mode crafter-build test --timeout=5 # override per-test timeout -crafter-build test --compositor=host # Wayland tests on this session's display ``` Outcomes: ✅ pass, ❌ fail, 💥 crash (with signal name), ⏱ timeout, ⏭ skipped. The runner exits 0 only if every non-skipped test passed. @@ -336,11 +185,11 @@ For elaborate setups (rsync, ssh ControlMaster, env vars on the spawn, `QEMU_LD_ For cross-arch builds, set `cfg.sysroot` on the `Configuration` to point at a sysroot for the target. `BuildStdPcm` and the compile/link commands both consume it: `--sysroot=` is passed to clang, and the std module is precompiled against the sysroot's libc++ headers. Ordinary compiles are pointed at the same headers (`-nostdinc++ -isystem /usr/include/c++/v1`), so a unit that `#include`s a standard header gets the sysroot's libc++ and not the host toolchain's. The module source has to come from the same libc++ release as those headers, so it is taken from `/usr/share/libc++/v1/std.cppm` when the sysroot ships it, else from the toolchain when both are the same major release, else from the sources crafter-build carries for other releases (`share/crafter-build/libc++-modules//`, `crafter-build --version` lists them). Alpine is the common case for the last two: its `libc++-dev` has the headers and no module source. When nothing matches, the build stops with one line naming both releases, installing that release's `share/libc++/v1` directory into the sysroot resolves it. The cheapest aarch64 sysroot is an extracted [Arch Linux ARM rootfs](http://os.archlinuxarm.org/) plus `libc++` + `libc++abi` + `gcc` installed into it via `pacman --root --config --dbpath /var/lib/pacman -Sy …` (point pacman at ALARM's mirrors via explicit config to avoid pulling host-arch packages). -For `--target=x86_64-w64-mingw32` (Windows from Linux), the pipeline cross-compiles as long as `mingw-w64` is installed, with libstdc++ 15 or newer for its std module. clang finds it by the `x86_64-w64-mingw32-gcc` on `PATH`; `CRAFTER_MINGW_DIR` names another prefix (the directory holding `x86_64-w64-mingw32/` and `lib/gcc/`), and inside the Flatpak the host's `/usr` is used when it has mingw-w64. Without one the build stops with a message saying where it looked. The prefix is clang's sysroot as it is, so Windows libraries installed into its `include/` and `lib/` are found, unless it also holds a Linux system: the host's `/usr` in the Flatpak, or any prefix whose `include/` has a C library's `features.h`, as `/usr` does. clang searches a sysroot's `include/` and `lib/`, and in such a prefix those hold glibc's headers and Linux libraries, so clang is shown only its `x86_64-w64-mingw32/`, `lib/gcc/` and `lib64/gcc/`, as links in `mingw-sysroot/` in the cache (`~/.cache/crafter.build/`, in the Flatpak `~/.var/app/net.catcrafts.CrafterBuild/cache/crafter.build/`, or `$XDG_RUNTIME_DIR/crafter.build/` when the cache's filesystem takes no symbolic links). Compiler messages still name those headers by their paths in the prefix. Pair it with `--runner=cmd:wine` to run the result. Only the MinGW ABI is supported, there is no MSVC target and no Windows host. `-fuse-ld=lld` is auto-injected on every link, and `-lstdc++exp` is auto-linked for the mingw target so user projects don't need to declare those flags. +For `--target=x86_64-w64-mingw32` (Windows from Linux), the pipeline cross-compiles as long as `mingw-w64` is installed, with libstdc++ 15 or newer for its std module. clang finds it by the `x86_64-w64-mingw32-gcc` on `PATH`; `CRAFTER_MINGW_DIR` names another prefix (the directory holding `x86_64-w64-mingw32/` and `lib/gcc/`), and inside the Flatpak the host's `/usr` is used when it has mingw-w64. Without one the build stops with a message saying where it looked. Pair it with `--runner=cmd:wine` to run the result. Only the MinGW ABI is supported, there is no MSVC target and no Windows host. `-fuse-ld=lld` is auto-injected on every link, and `-lstdc++exp` is auto-linked for the mingw target so user projects don't need to declare those flags. For `--target=wasm32-wasip1`, the WASI sysroot is the one beside the toolchain (the Flatpak bundles one) unless `CRAFTER_BUILD_WASI_SYSROOT` names another, and tests run under `wasmtime`. C++ exceptions work as on the other targets: every unit and the std module are compiled with `-fwasm-exceptions` in the standardized form of WebAssembly exception handling (exnref), against the exception-enabled libc++ in the sysroot's `lib//eh/`, and `-lunwind` is linked automatically. A sysroot without that libc++ (wasi-sdk before 33) stops the build with one line saying so. The result runs on engines with that proposal: Chrome 137, Firefox 131 and Safari 18.4 or newer, and the wasmtime the Flatpak bundles. A page from `EnableWasiBrowserRuntime` checks first and names what an older browser lacks in the console, instead of failing to compile the module. An exception that escapes `main` leaves the program as an uncaught WebAssembly exception (wasmtime reports `thrown Wasm exception` and exits 1, a page gets a `WebAssembly.Exception`) without calling `std::terminate`, so a `std::set_terminate` handler does not run and nothing prints the exception's type or `what()`: wasm exception handling unwinds in a single phase, and nothing finds out that no handler is left until the stack is gone. Catch it in `main` to report it. -A wasm build refuses four things before it starts, each with a message that says why: `-flto` in `compileFlags` or `linkFlags` (LTO code generation drops the exception handling, [WebAssembly/wasi-sdk#629](https://github.com/WebAssembly/wasi-sdk/issues/629)), `-fno-exceptions` (the std module is built with exceptions, and a unit without them cannot import it), a shared library (the exception-enabled libc++ is static archives only) and packaging as a Flatpak (a wasm build stays a `.wasm`; see [Flatpak output](#flatpak-output)). `setjmp` and `longjmp` work in C and C++ sources, with `-lsetjmp` linked automatically like `-lunwind`; a `longjmp` across a `noexcept` function ends the program, because it is a wasm exception and the function's terminate handler catches it. Outside the Flatpak, a wasmtime older than 47 has exception handling off and needs `-W exceptions=y`, and a `wasm-opt` on `PATH` from a binaryen that cannot read the standardized encoding breaks release links, since clang runs it on optimized wasm links when it finds one. +A wasm build refuses three things before it starts, each with a message that says why: `-flto` in `compileFlags` or `linkFlags` (LTO code generation drops the exception handling, [WebAssembly/wasi-sdk#629](https://github.com/WebAssembly/wasi-sdk/issues/629)), `-fno-exceptions` (the std module is built with exceptions, and a unit without them cannot import it) and a shared library (the exception-enabled libc++ is static archives only). `setjmp` and `longjmp` work in C and C++ sources, with `-lsetjmp` linked automatically like `-lunwind`; a `longjmp` across a `noexcept` function ends the program, because it is a wasm exception and the function's terminate handler catches it. Outside the Flatpak, a wasmtime older than 47 has exception handling off and needs `-W exceptions=y`, and a `wasm-opt` on `PATH` from a binaryen that cannot read the standardized encoding breaks release links, since clang runs it on optimized wasm links when it finds one. In a page from `EnableWasiBrowserRuntime`, `exit` and `_Exit` end the program as they would anywhere else: none of its code runs on the way out, no destructor and no `catch (...)`, its status is in `window.crafter_wasi.exitCode`, and bridges that call into it on their own are expected to stop. A program that hands the thread to the browser for good and goes on serving calls, as Crafter.Graphics's `Window::StartSync()` does, parks instead of exiting. Parking never returns, runs nothing of the program either, and leaves `main`'s locals valid for the calls that follow: @@ -377,24 +226,6 @@ cmd: # cmd:wine, cmd:qemu-aarch64, cmd:valgrind, ... Each runner carries a `probe` command (e.g. `which wine`), if it fails, every test using that runner is reported as ⏭ skipped and the rest of the suite continues. Skipped tests count toward the summary but don't fail the suite (`AllPassed()` returns true on skip-only runs). -### Tests that open windows - -A test that talks to a Wayland compositor sets `Test::wayland`, and every run of it gets a headless compositor of its own instead of your session's display, so the windows it opens through `WAYLAND_DISPLAY` show up there and not on your desktop: - -```cpp -cfg.AddTest("Swapchain").Wayland(); // or, on a Test you build yourself: test.wayland = true; -``` - -Before the test, crafter-build starts the compositor with `XDG_RUNTIME_DIR` set to a directory made for it (in your `XDG_RUNTIME_DIR`, else in `/tmp`) and without `WAYLAND_DISPLAY`, `WAYLAND_SOCKET` or `DISPLAY`, and waits up to 30 s for a `wayland-` socket to appear there. The test then runs with `WAYLAND_DISPLAY` set to that socket's full path and with `DISPLAY` and `WAYLAND_SOCKET` unset; its `XDG_RUNTIME_DIR` stays yours. Afterwards the compositor's process group is sent SIGTERM, what is left of the group SIGKILL once the compositor has ended or 5 s have passed, and the directory is removed. No two tests share a compositor, so tests that run at once cannot cover each other's windows or take each other's focus. - -The compositor is `weston --backend=headless --renderer=gl --no-config --idle-time=0` unless `CRAFTER_BUILD_COMPOSITOR` names another, and `--compositor=` wins over both. The Flatpak ships weston 16.0.2; outside it, install weston 12 or newer, the first release to take `--renderer=`. Its GL renderer takes the GPU buffers (dmabufs) that a GPU's Vulkan driver presents, as Mesa's and NVIDIA's do, and which the headless backend's default, a renderer that draws nothing, and pixman take none of; `--no-config` keeps your `weston.ini` out, and `--idle-time=0` keeps the output from going idle after 5 minutes, which would stop frame callbacks. Another compositor is any command, run through `sh`, that listens on a `wayland-` socket in the `XDG_RUNTIME_DIR` it is given. `host` starts none and gives these tests your own display, to watch what they draw: - -```bash -crafter-build test --compositor=host 'Swapchain*' -``` - -A compositor that ends before it listens, `sh` not finding it included, or does not listen within 30 s fails the test with what it printed. A test that may run where weston is missing declares it with `.Requires("tool:weston")`, and is then skipped there before it is built, as for any tool it declares. When a test that ran fails, crashes or times out, what its compositor printed, if anything, goes to `build/test-logs/.compositor.log`, named as the test's own log is, and the test's output says so, and also when the compositor ended before the test did; what a compositor that did not start printed is in the test's own failure, in `build/test-logs/.log`. A crafter-build that is killed takes its compositors with it; the directories it leaves behind are removed by a test that starts a compositor after they have gone a minute unchanged. - ### Linking the parent project's library A test fixture can depend on the project's own library so it can `import` and exercise its API: @@ -495,7 +326,7 @@ The callback returns the exit status, and `crafter-build run` exits with it. `ct cfg.scripts.push_back({"package", [](Crafter::ScriptContext& ctx) { const std::string dist = Crafter::ShellQuote((ctx.projectDir / "dist").string()); if (const std::int32_t code = ctx.Run(std::format("mkdir -p {}", dist)); code != 0) return code; - return ctx.Run(std::format("tar -czf {}/myapp.tar.gz -C {} .", dist, Crafter::ShellQuote(ctx.project.ProgramDir().string()))); + return ctx.Run(std::format("tar -czf {}/myapp.tar.gz -C {} .", dist, Crafter::ShellQuote(ctx.project.BinDir().string()))); }}); ``` @@ -503,7 +334,7 @@ cfg.scripts.push_back({"package", [](Crafter::ScriptContext& ctx) { | Member | Meaning | |---|---| -| `project` | 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 through a `cfg` captured by reference | +| `project` | the `Configuration` that `project.cpp` returned. Read the project through this; a `cfg` captured by reference is gone by the time a script runs | | `projectDir` | absolute directory of the project file | | `args` | everything typed after the script's name, untouched | | `Run(command)` | run a shell command with the terminal attached and return its exit code | @@ -517,32 +348,6 @@ Things to know: - Inside the Flatpak, commands run in its sandbox: the host's files are visible, but the tools on `PATH` are the ones the Flatpak ships (`git`, `cmake`, `python3`, `tar`, ...), not everything installed on the host. - A return value outside 0 to 255 is not an exit status and becomes 1. So does a script that throws, with the exception's message printed. -## Debugging - -Programs that `-r` and the test runner start run inside the Flatpak's sandbox, and so do the tools to debug them: lldb, with `lldb-server`, `lldb-dap` and `lldb-mcp`, from the same LLVM build as the compiler; `gdb`, `gdbserver`, `valgrind` and `strace` from the Freedesktop Sdk; the Khronos Vulkan validation layer; and the SPIRV-Tools programs (`spirv-val`, `spirv-opt`, `spirv-dis`, ...). A default build is optimised (`-O3`, and ThinLTO except for wasm) and carries no debug information: set `cfg.debug = true` for a program you want to debug, which compiles its C++ units with `-g` and links it without LTO; its C and CUDA sources (`cfg.cFiles`, `cfg.cuda`) stay at `-O3` without debug information. A `project.cpp` that calls `ApplyStandardArgs` sets it from the `--debug` argument, as in `crafter-build --debug -r`. Start the tools with `--command`: - -```bash -flatpak run --die-with-parent --command=lldb net.catcrafts.CrafterBuild ./bin/myapp-/myapp -flatpak run --die-with-parent --command=valgrind net.catcrafts.CrafterBuild ./bin/myapp-/myapp -``` - -Every `flatpak run` is a sandbox of its own, with process IDs of its own, so a debugger in one cannot see a program that another one, such as `crafter-build -r`, started. Either start the program under the debugger, or run the debugger inside that program's sandbox with `flatpak enter`, giving the instance `flatpak ps` lists for net.catcrafts.CrafterBuild and the debugger's full path: - -```bash -flatpak ps --columns=instance,application -flatpak enter /app/bin/lldb -n myapp -``` - -Where `/proc/sys/kernel/yama/ptrace_scope` is 1, a debugger in the sandbox, where processes hold no capabilities, can attach to a program that is not its descendant only when the program allowed it with `prctl(PR_SET_PTRACER, …)`: with the debugger's process ID, or with `PR_SET_PTRACER_ANY` for any process. Otherwise the attach fails. A program started under the debugger is its descendant. Prefer `flatpak enter` to `lldb-server gdbserver` in one sandbox and lldb's `gdb-remote` from another: when a process in lldb's own sandbox has the remote program's process ID, lldb takes that process's executable for the program's: symbols come out wrong, and a breakpoint in the program's source finds no location. - -The validation layer is enabled the usual ways, by the program itself or from the environment: `flatpak run` passes `VK_INSTANCE_LAYERS`, `VK_LOADER_LAYERS_ENABLE` and the layer's `VK_KHRONOS_VALIDATION_*` settings into the sandbox. `VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1` adds GPU-assisted validation (GPU-AV): - -```bash -VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_KHRONOS_VALIDATION_GPUAV_ENABLE=1 crafter-build -r -``` - -The layer is the Vulkan SDK release of the runtime's own Vulkan loader. `VK_LAYER_PATH` and `VK_ADD_LAYER_PATH` are cleared on the way into the sandbox, so a layer installed on the host is out of reach. - ## Examples [examples/](examples/) contains progressively larger self-contained projects: @@ -562,7 +367,7 @@ This project is licensed under the GNU Lesser General Public License, version 3 The example code under [examples/](examples/) is licensed under the MIT license (see [examples/LICENSE](examples/LICENSE)), so it can be freely copied into your own projects. -The [lib/](lib/) directory contains vendored third-party code (glslang's DirStackFileIncluder) that remains under its own permissive license, see the header of that file. +The [lib/](lib/) directory contains vendored third-party code (nlohmann/json, glslang's DirStackFileIncluder) that remains under its own permissive licenses, see the headers of those files. ## Copyright diff --git a/build.sh b/build.sh index 6e48b9f..02b089b 100755 --- a/build.sh +++ b/build.sh @@ -36,9 +36,10 @@ else STD_CPPM=/usr/share/libc++/v1/std.cppm fi -# The version baked into the binary: the environment (CI sets it), else the -# nearest tag, else a development marker. -VERSION="${CRAFTER_BUILD_VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo 0.0.0-dev)}" +# The version baked into the binary: the environment (CI sets it from the +# tag), else the nearest tag, else a development marker. `latest` is the +# rolling CI tag and never a version. +VERSION="${CRAFTER_BUILD_VERSION:-$(git describe --tags --always --dirty --exclude=latest 2>/dev/null || echo 0.0.0-dev)}" mkdir -p build bin lib share/crafter-build share/crafter-build/wasi-runtime @@ -47,7 +48,7 @@ cp wasi-runtime/index.html.in share/crafter-build/wasi-runtime/ # Partition order is the import order: every unit is listed before the # units that import it, and the umbrella last. -PARTITIONS="Toolchain Shader Platform Flatpak Jobs Interface Implementation External Agents Clang Test Lint Script Progress Asset" +PARTITIONS="Toolchain Shader Platform Interface Implementation External Agents Clang Test Lint Script Progress Asset" cp interfaces/Crafter.Build.cppm share/crafter-build/ for p in $PARTITIONS; do diff --git a/examples/tests/README.md b/examples/tests/README.md index 8f46338..6dcbf5c 100644 --- a/examples/tests/README.md +++ b/examples/tests/README.md @@ -37,7 +37,6 @@ builder methods overlay overrides: - `.Dependencies({ &otherCfg, ... })` - `.Path(p)` — rebase the test's source-resolution path - `.LinkFlag(s)` / `.CompileFlag(s)` -- `.Wayland()` — a headless Wayland compositor of the test's own, so that the windows it opens stay off your desktop ([Tests that open windows](../../README.md#tests-that-open-windows)) ## Test conventions diff --git a/implementations/Crafter.Build-Agents.cpp b/implementations/Crafter.Build-Agents.cpp index acb73bf..f26c8c2 100644 --- a/implementations/Crafter.Build-Agents.cpp +++ b/implementations/Crafter.Build-Agents.cpp @@ -22,26 +22,12 @@ namespace { // Right under the begin marker, for whoever opens the file: an edit made // inside the section is gone after the next build. constexpr std::string_view Preamble = ""; - // The first line of every AGENTS.md a build writes. It tells whoever - // opens the file, an agent asked to change it included, where an edit - // has to be made to outlive the next build, and it is how a build tells - // its own AGENTS.md from one someone wrote, which it never replaces. A - // changed word would make every AGENTS.md written before look like - // someone's own. - constexpr std::string_view GeneratedLine = ""; constexpr std::string_view NotesFileName = "AGENTS.consumer.md"; - constexpr std::string_view TemplateFileName = "AGENTS.template.md"; - constexpr std::string_view AgentsFileName = "AGENTS.md"; void Warn(std::string_view message) { Progress::Diagnostic(std::format("warning: {}", message)); } - // The line ending `text` uses, so a CRLF file does not end up mixed. - std::string_view LineEnd(std::string_view text) { - return text.contains("\r\n") ? "\r\n" : "\n"; - } - std::string ErrnoMessage() { return std::error_code(errno, std::generic_category()).message(); } @@ -263,9 +249,9 @@ namespace { } // Why `text` cannot go into the section as it is; empty when it can. A - // marker line of its own would end or restart the section for whoever - // reads it, a template copied from the result included, and a code block - // left open would run on over the notes after it and the end marker. + // marker line of its own would end or restart the section once the file + // is read back, and a code block left open would hide the end marker: + // either way the next build could no longer find what this one wrote. // Lines are numbered from `firstLine`. std::string NoteProblem(std::string_view text, std::size_t firstLine) { const MarkerScan scan = ScanMarkers(text); @@ -345,60 +331,18 @@ namespace { return DependencyNote{ .name = name, .text = std::move(note.text) }; } - // Tells a configuration of another project from one of the project - // whose AGENTS.md is written, the one of the project file it is made - // with. GitProject and LocalProject hold the configurations of a project - // file they loaded, so held or not does not tell the two apart: the - // project whose notes are written may itself have been loaded through - // one of them, by a program that then writes its AGENTS.md for it. Two - // files are one project file when they resolve to one path, which is - // how the loader tells project files apart: a hard link to the project - // file in another directory is another project's. Each loaded project's - // file is compared with the project file once and the answer kept, so a - // configuration is the same thing every time one collection asks, - // whatever happens to the files meanwhile. - class OtherProjects { - public: - explicit OtherProjects(const fs::path& projectFile) { - // Left empty when the file cannot be resolved, and then no - // loaded project's file is it. - std::error_code ec; - projectFile_ = fs::canonical(projectFile, ec); - if (ec) projectFile_.clear(); - } - // The project `cfg` was loaded from when that is another one; - // nullopt for a configuration the project's own file made. - std::optional Of(const Configuration& cfg) { - std::optional loaded = LoadedProjectOf(cfg); - if (!loaded) return loaded; - const auto [known, added] = same_.try_emplace(loaded->projectFile, false); - if (added && !projectFile_.empty()) { - std::error_code ec; - const fs::path file = fs::canonical(loaded->projectFile, ec); - known->second = !ec && file == projectFile_; - } - if (known->second) loaded.reset(); - return loaded; - } - private: - // The project file, resolved. - fs::path projectFile_; - // By a loaded project's file: whether it is projectFile_. - std::unordered_map same_; - }; - - // The other projects `configs` lead to without passing through another - // of them, in the order the configurations name them: one ring further - // out. `walked` spans the whole collection, so each Configuration is - // looked at once however many paths reach it. - std::vector NextRing(std::span configs, std::unordered_set& walked, OtherProjects& others) { + // The loaded projects `configs` lead to without passing through another + // loaded project, in the order the configurations name them: one ring + // further out. `walked` spans the whole collection, so each + // Configuration is looked at once however many paths reach it. + std::vector NextRing(std::span configs, std::unordered_set& walked) { std::vector ring; std::vector pending(configs.rbegin(), configs.rend()); while (!pending.empty()) { const Configuration* cfg = pending.back(); pending.pop_back(); if (!cfg || !walked.insert(cfg).second) continue; - if (others.Of(*cfg)) { + if (LoadedProjectOf(*cfg)) { ring.push_back(cfg); continue; } @@ -407,72 +351,21 @@ namespace { return ring; } - // The AGENTS.consumer.md of every project the project is built against, - // as the dependencyNotes of `configurations`, the configurations its - // project file returns, select them, ring by ring: first the other - // projects (the ones GitProject and LocalProject loaded from another - // project file) that its `#pragma crafter dependency` lines and its - // configurations name, in that order, then the ones those depend on. - // Its own configurations, and a dependency's internal ones, are only - // walked through. - // - // Each configuration the file made itself selects for what it is built - // against: None nothing, Direct the first ring from it, Transitive every - // ring. Another project therefore has its own dependencies followed - // when a Transitive configuration leads to it, at whatever depth, and - // not when only Direct ones do. The pragma lines belong to the file and - // not to one configuration, and a configuration the file loaded from - // another project and returns is a project of the first ring itself, - // with a setting that is that project's own: both go by the widest - // setting among the configurations the file made, and by Transitive - // when it made none. + // The AGENTS.consumer.md of every project `project` depends on, as + // project.dependencyNotes selects them, ring by ring: first the loaded + // projects (the ones GitProject and LocalProject returned) that its + // `#pragma crafter dependency` lines and its configurations name, in + // that order, then the ones those depend on. Its own configurations, and + // a dependency's internal ones, are only walked through. Direct stops + // after the first ring. // // Never walked: the project's tests, since a plain build never touches - // them and a test's dependency can point at the Configuration a - // CrafterBuildProject returned by value, which a caller of LoadProject - // may have moved since; and a dependency's own pragma tooling, which is - // about how the dependency is built, not how it is used, and is no - // `dependencies` edge to begin with. - std::vector CollectNotes(std::span configurations, const fs::path& projectFile, const fs::path& projectDir) { - OtherProjects others(projectFile); - const auto made = [&](const Configuration* cfg) { return !others.Of(*cfg); }; - const auto asks = [&](DependencyNotes setting) { - return std::ranges::any_of(configurations, [&](const Configuration* cfg) { return made(cfg) && cfg->dependencyNotes == setting; }); - }; - const bool transitive = asks(DependencyNotes::Transitive) || std::ranges::none_of(configurations, made); - if (!transitive && !asks(DependencyNotes::Direct)) return {}; - - // Where the walk starts, and the starts that ask for every ring. - std::vector start; - std::vector deep; - for (const Configuration* dep : PragmaDependencies(projectFile)) { - start.push_back(dep); - if (transitive) deep.push_back(dep); - } - for (const Configuration* cfg : configurations) { - const DependencyNotes setting = made(cfg) ? cfg->dependencyNotes : transitive ? DependencyNotes::Transitive : DependencyNotes::Direct; - if (setting == DependencyNotes::None) continue; - start.push_back(cfg); - if (setting == DependencyNotes::Transitive) deep.push_back(cfg); - } - // Every other project those lead to: the ones whose own - // dependencies are followed. Worked out ahead of the walk below, - // which meets each project once, at its nearest ring, and that can - // be a ring a Direct configuration put it in. - std::unordered_set followed; - { - std::unordered_set reached; - for (std::vector ring = NextRing(deep, reached, others); !ring.empty();) { - std::vector next; - for (const Configuration* cfg : ring) { - followed.insert(cfg); - next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end()); - } - ring = NextRing(next, reached, others); - } - } - - std::unordered_set walked; + // them and a test's dependency can point at the Configuration the project + // file returned by value, which has since moved; and a dependency's own + // pragma tooling, which is about how the dependency is built, not how it + // is used, and is no `dependencies` edge to begin with. + std::vector CollectNotes(const Configuration& project, const fs::path& projectFile, const fs::path& projectDir) { + std::unordered_set walked = { &project }; // The project's own notes are for its consumers, so they never go // into its own AGENTS.md, whatever dependency they sit beside. Both // places count for a symlinked project file. @@ -482,11 +375,13 @@ namespace { std::unordered_set identities; std::vector notes; - for (std::vector ring = NextRing(start, walked, others); !ring.empty();) { + std::vector start; + for (const Configuration* dep : PragmaDependencies(projectFile)) start.push_back(dep); + start.insert(start.end(), project.dependencies.begin(), project.dependencies.end()); + for (std::vector ring = NextRing(start, walked); !ring.empty();) { std::vector next; for (const Configuration* cfg : ring) { - // Another project's, or NextRing had walked through it. - const std::optional loaded = others.Of(*cfg); + const std::optional loaded = LoadedProjectOf(*cfg); const fs::path file = loaded->projectFile.parent_path() / NotesFileName; // One library under two specs (a pin here, another revision // further down) is described once, as the ring nearest the @@ -494,40 +389,14 @@ namespace { if (identities.insert(loaded->identity).second && files.insert(file).second) { if (std::optional note = ReadNote(file, loaded->name)) notes.push_back(std::move(*note)); } - if (followed.contains(cfg)) next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end()); + next.insert(next.end(), cfg->dependencies.begin(), cfg->dependencies.end()); } - ring = NextRing(next, walked, others); + if (project.dependencyNotes == DependencyNotes::Direct) break; + ring = NextRing(next, walked); } return notes; } - // Whether a build may replace `agentsMd`, the AGENTS.md beside a - // template: one a build wrote, or one with no text at all, which is what - // a write cut short leaves of a new file. Anything else someone wrote, - // and beside a template that is easily the case: an AGENTS.md committed - // before the template was, or one an agent kept its own notes in. - bool Replaceable(std::string_view agentsMd) { - if (agentsMd.find_first_not_of(" \t\r\n") == std::string_view::npos) return true; - std::string_view first = agentsMd.substr(0, agentsMd.find('\n')); - if (first.ends_with('\r')) first.remove_suffix(1); - return first == GeneratedLine; - } - - // An AGENTS.md with no template beside it is someone's own, and no build - // writes it. One that still holds a section from the builds that kept the - // notes in a committed AGENTS.md would go stale without a word, under a - // preamble saying every build rewrites it, so each build says so until - // the file has moved to a template or the section is gone. - void WarnStaleSection(const fs::path& agents) { - std::error_code ec; - if (!fs::is_regular_file(agents, ec)) return; - std::string text; - if (!ReadFile(agents, text).empty()) return; - const MarkerScan scan = ScanMarkers(text); - if (scan.begins.empty() && scan.ends.empty()) return; - Warn(std::format("{} has a dependency notes section, which builds no longer update; rename the file to {} and keep {} out of version control to have every build write it with current notes, or delete the section", agents.string(), TemplateFileName, AgentsFileName)); - } - // Bring `fd`, which holds `current`, to `wanted`: from the first byte the // two differ at, so the text in front of the section is never rewritten, // then cut to length and synced. Empty on success, otherwise the error. @@ -536,9 +405,10 @@ namespace { // rename swaps in another file, which drops whatever belongs to the old // one (a hard link such as a CLAUDE.md beside it, ACLs, ownership, being // read-only) and needs fsyncs to be crash safe at all. The price is that - // a reader can catch the file half written, and that a write failing - // partway, on a full disk say, leaves it so until the next build writes - // it again. + // a reader can catch the section half written, and that a write failing + // partway, on a full disk say, leaves it so. With the section last, + // where it is appended, only the section can be damaged, and the next + // build reports its markers instead of guessing. std::string WriteChanged(std::int32_t fd, std::string_view current, std::string_view wanted) { const auto diverge = std::ranges::mismatch(current, wanted); for (auto done = static_cast(diverge.in2 - wanted.begin()); done < wanted.size();) { @@ -557,24 +427,24 @@ namespace { } } -std::string Crafter::MergeDependencyNotes(std::string_view templateMd, std::span notes) { +std::string Crafter::MergeDependencyNotes(std::string_view agentsMd, std::span notes) { for (const DependencyNote& note : notes) { if (const std::string problem = NoteProblem(note.text, 1); !problem.empty()) throw std::runtime_error(std::format("the notes from {}: {}", note.name, problem)); } - const MarkerScan scan = ScanMarkers(templateMd); + const MarkerScan scan = ScanMarkers(agentsMd); const bool section = scan.begins.size() == 1 && scan.ends.size() == 1 && scan.begins[0] < scan.ends[0]; - const std::string_view eol = LineEnd(templateMd); + // The file's own line ending, so a CRLF file does not end up mixed. + const std::string_view eol = agentsMd.contains("\r\n") ? "\r\n" : "\n"; if (notes.empty()) { - // With nothing to place, nothing can land in the wrong place, so - // anything short of a well-formed section is left as it was written. - if (!section) return std::string(templateMd); - std::string_view before = templateMd.substr(0, scan.lines[scan.begins[0]].begin); - const std::string_view after = templateMd.substr(scan.lines[scan.ends[0]].next); - // A section that ends the template takes the blank line in front of - // it, which an appended one gets. One placed elsewhere keeps the text - // around it apart. + // With nothing to write, leaving the file alone loses nothing, so + // anything short of a well-formed section is no concern of this one. + if (!section) return std::string(agentsMd); + std::string_view before = agentsMd.substr(0, scan.lines[scan.begins[0]].begin); + const std::string_view after = agentsMd.substr(scan.lines[scan.ends[0]].next); + // The blank line a section at the end was appended after goes with + // it. One the user moved keeps the text around it apart. if (after.empty() && before.ends_with(std::format("{0}{0}", eol))) before.remove_suffix(eol.size()); return std::format("{}{}", before, after); } @@ -585,101 +455,75 @@ std::string Crafter::MergeDependencyNotes(std::string_view templateMd, std::span if (!scan.begins.empty() && scan.ends.empty()) throw std::runtime_error(std::format("line {}: a dependency notes begin marker with no end marker after it", scan.begins[0] + 1)); const std::string rendered = RenderSection(notes, eol); - if (section) return std::format("{}{}{}", templateMd.substr(0, scan.lines[scan.begins[0]].begin), rendered, templateMd.substr(scan.lines[scan.ends[0]].next)); - // Appended, the section would sit inside that block and read as code. + if (section) return std::format("{}{}{}", agentsMd.substr(0, scan.lines[scan.begins[0]].begin), rendered, agentsMd.substr(scan.lines[scan.ends[0]].next)); + // Appended, the section would sit inside that block and never be found + // again, so every build would add another. if (scan.unclosedBlock) throw std::runtime_error(std::format("line {}: a code block opens here and never closes", *scan.unclosedBlock + 1)); - if (templateMd.empty()) return rendered; + if (agentsMd.empty()) return rendered; // On a line of its own, after a blank one. - return std::format("{}{}{}{}", templateMd, templateMd.ends_with('\n') ? std::string_view() : eol, eol, rendered); + return std::format("{}{}{}{}", agentsMd, agentsMd.ends_with('\n') ? std::string_view() : eol, eol, rendered); } bool Crafter::UpdateAgentsMd(const Configuration& project, const fs::path& projectFile) { - std::array one = { &project }; - return UpdateAgentsMd(std::span(one), projectFile); -} - -bool Crafter::UpdateAgentsMd(std::span configurations, const fs::path& projectFile) { std::error_code ec; // Beside the project file as it was named, so a symlinked project.cpp // keeps the AGENTS.md beside the link. const fs::path projectDir = fs::absolute(projectFile, ec).lexically_normal().parent_path(); if (ec) return false; - const fs::path agents = projectDir / AgentsFileName; - const fs::path templateFile = projectDir / TemplateFileName; - if (!fs::is_regular_file(templateFile, ec)) { - WarnStaleSection(agents); - return false; - } - // Linked to the template, AGENTS.md would have every build write the - // file that is committed, which is what the template is there to stop. - if (fs::equivalent(agents, templateFile, ec)) { - Warn(std::format("{} and {} are the same file, so {} was not written", agents.string(), templateFile.string(), AgentsFileName)); - return false; - } - std::string templateMd; - if (const std::string error = ReadFile(templateFile, templateMd); !error.empty()) { - Warn(std::format("{} could not be read ({}), so {} was not written", templateFile.string(), error, agents.string())); - return false; - } + const fs::path agents = projectDir / "AGENTS.md"; + if (!fs::is_regular_file(agents, ec)) return false; - const std::vector notes = CollectNotes(configurations, projectFile, projectDir); - std::string wanted; - try { - wanted = std::format("{}{}{}", GeneratedLine, LineEnd(templateMd), MergeDependencyNotes(templateMd, notes)); - } catch (const std::exception& e) { - Warn(std::format("{}: {}, so {} was not written", templateFile.string(), e.what(), agents.string())); - return false; - } + const std::vector notes = project.dependencyNotes == DependencyNotes::None ? std::vector() : CollectNotes(project, projectFile, projectDir); - // Created when missing, since a fresh clone has no build output, and only - // now, with the text in hand, so a template the notes cannot be placed - // in leaves no empty AGENTS.md behind. Locked from the read through the - // write, so two builds never interleave their writes, and on the file - // itself, which also covers two projects that link one AGENTS.md. A - // read-only descriptor takes the lock as well, so a read-only AGENTS.md - // is still read without complaint. - const Descriptor reading(::open(agents.c_str(), O_RDONLY | O_CREAT | O_CLOEXEC, 0666)); + // Locked from the read through the write, so two builds never interleave + // their writes, and on the file itself, which also covers two projects + // that link one AGENTS.md. A read-only descriptor takes the lock as + // well, so a read-only AGENTS.md is still read without complaint. + const Descriptor reading(::open(agents.c_str(), O_RDONLY | O_CLOEXEC)); if (!reading.Valid()) { - Warn(std::format("{} could not be opened ({}), so it was not written", agents.string(), ErrnoMessage())); + Warn(std::format("{} could not be read ({}), so its dependency notes were not updated", agents.string(), ErrnoMessage())); return false; } while (::flock(reading.Get(), LOCK_EX) != 0 && errno == EINTR) {} std::string current; if (const std::string error = ReadAll(reading.Get(), current); !error.empty()) { - Warn(std::format("{} could not be read ({}), so it was not written", agents.string(), error)); + Warn(std::format("{} could not be read ({}), so its dependency notes were not updated", agents.string(), error)); return false; } - if (current == wanted) return false; - if (!Replaceable(current)) { - Warn(std::format("{} was not written by a build, so it was not replaced by one written from {}; once the template holds what it says, delete it", agents.string(), TemplateFileName)); + + std::string merged; + try { + merged = MergeDependencyNotes(current, notes); + } catch (const std::exception& e) { + Warn(std::format("{}: {}, so its dependency notes were not updated", agents.string(), e.what())); return false; } + if (merged == current) return false; // Only now, with something to write: a read-only AGENTS.md is refused // here, and not on every build that leaves it as it is. const Descriptor writing(::open(agents.c_str(), O_WRONLY | O_CLOEXEC)); if (!writing.Valid()) { - Warn(std::format("{} could not be opened for writing ({}), so it was not written", agents.string(), ErrnoMessage())); + Warn(std::format("{} could not be opened for writing ({}), so its dependency notes were not updated", agents.string(), ErrnoMessage())); return false; } - if (const std::string error = WriteChanged(writing.Get(), current, wanted); !error.empty()) { + if (const std::string error = WriteChanged(writing.Get(), current, merged); !error.empty()) { // Put back what was there. A full disk that refused the new bytes // usually still takes the old ones, whose space was just freed. - if (WriteChanged(writing.Get(), wanted, current).empty()) { - Warn(std::format("{} could not be written ({}), so it was left as it was", agents.string(), error)); + if (WriteChanged(writing.Get(), merged, current).empty()) { + Warn(std::format("{} could not be written ({}), so its dependency notes were not updated", agents.string(), error)); } else { - Warn(std::format("{} could not be written ({}) and may now be half written; the next build writes it again", agents.string(), error)); + Warn(std::format("{} could not be written ({}) and may now end in part of the section; the next build reports it if so", agents.string(), error)); } return false; } - // A file that appears beside project.cpp, or changes there, unasked, - // says where it came from. + // A build that edits a file the user commits says so. if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) { Progress::Clear(); if (notes.empty()) { - std::println("Wrote {} from {}", agents.string(), TemplateFileName); + std::println("Removed the dependency notes from {}", agents.string()); } else { - std::println("Wrote {} from {} and the notes of {} {}", agents.string(), TemplateFileName, notes.size(), notes.size() == 1 ? "dependency" : "dependencies"); + std::println("Updated the dependency notes in {} ({} {})", agents.string(), notes.size(), notes.size() == 1 ? "dependency" : "dependencies"); } } return true; diff --git a/implementations/Crafter.Build-Clang.cpp b/implementations/Crafter.Build-Clang.cpp index 6dbbc0d..e0d8329 100644 --- a/implementations/Crafter.Build-Clang.cpp +++ b/implementations/Crafter.Build-Clang.cpp @@ -16,524 +16,260 @@ import :Script; import :Agents; import :Progress; import :Asset; -import :Flatpak; -import :Jobs; namespace fs = std::filesystem; using namespace Crafter; namespace { - // A JSON value: what clang-scan-deps writes of a source, and what Build() - // keeps of that. The members of an object are its `items`, each with - // its `key`. - struct Json { - enum class Kind { Null, Boolean, Number, String, Array, Object }; - Kind kind = Kind::Null; - bool boolean = false; - // A string's value, or a number as it is written. - std::string text; - std::vector items; - std::string key; - - // The member of an object named `name`; nullptr when the object has - // none, and for a value that is no object. - const Json* Member(std::string_view name) const { - if (kind != Kind::Object) return nullptr; - for (const Json& item : items) { - if (item.key == name) return &item; - } - return nullptr; - } - }; - - // Reads the one JSON value (RFC 8259) a text holds. There is no JSON - // library in the tree, and what clang-scan-deps writes is JSON. - class JsonReader { - public: - explicit JsonReader(std::string_view text) : text(text) {} - - // The value, with nothing after it but white space; nullopt for a - // text that holds anything else. - std::optional Read() { - Json value; - if (!Value(value, 0)) return std::nullopt; - SkipSpace(); - if (at != text.size()) return std::nullopt; - return value; - } - - private: - // Deeper than anything clang-scan-deps writes, and shallow enough - // that a text which is not its output cannot exhaust the stack. - static constexpr std::size_t MaxDepth = 64; - - bool Value(Json& value, std::size_t depth) { - SkipSpace(); - if (at == text.size() || depth > MaxDepth) return false; - if (text[at] == '{') return Object(value, depth); - if (text[at] == '[') return Array(value, depth); - if (text[at] == '"') { - value.kind = Json::Kind::String; - return String(value.text); - } - if (Word("true")) { - value.kind = Json::Kind::Boolean; - value.boolean = true; + // Map one `import X;` name onto either a module this Configuration owns or + // one exported by a Configuration reachable through its dependency DAG, + // appending the matching staleness edge. False means nothing in reach + // provides X — either it's supplied from outside the graph (`std`) or the + // dependency isn't wired up *yet*, which is why callers remember the name. + bool ResolveImportName(Configuration& cfg, const std::string& importName, std::vector& localDeps, std::vector>& externalDeps) { + for(const std::unique_ptr& interface : cfg.interfaces) { + if(interface->name == importName) { + localDeps.push_back(interface.get()); return true; } - if (Word("false")) { - value.kind = Json::Kind::Boolean; - return true; - } - if (Word("null")) return true; - return Number(value); } - bool Object(Json& value, std::size_t depth) { - value.kind = Json::Kind::Object; - ++at; - SkipSpace(); - if (Take('}')) return true; - do { - SkipSpace(); - Json member; - if (!String(member.key)) return false; - SkipSpace(); - if (!Take(':') || !Value(member, depth + 1)) return false; - value.items.push_back(std::move(member)); - SkipSpace(); - } while (Take(',')); - return Take('}'); - } - - bool Array(Json& value, std::size_t depth) { - value.kind = Json::Kind::Array; - ++at; - SkipSpace(); - if (Take(']')) return true; - do { - Json element; - if (!Value(element, depth + 1)) return false; - value.items.push_back(std::move(element)); - SkipSpace(); - } while (Take(',')); - return Take(']'); - } - - // The string that starts at the cursor, its escapes undone, into - // `out`. - bool String(std::string& out) { - if (!Take('"')) return false; - while (at < text.size()) { - const char c = text[at++]; - if (c == '"') return true; - // A control character is only ever escaped. - if (static_cast(c) < 0x20) return false; - if (c != '\\') { - out.push_back(c); - continue; - } - if (at == text.size()) return false; - switch (text[at++]) { - case '"': out.push_back('"'); break; - case '\\': out.push_back('\\'); break; - case '/': out.push_back('/'); break; - case 'b': out.push_back('\b'); break; - case 'f': out.push_back('\f'); break; - case 'n': out.push_back('\n'); break; - case 'r': out.push_back('\r'); break; - case 't': out.push_back('\t'); break; - case 'u': { - std::uint32_t code = 0; - if (!Hex(code)) return false; - // A character past the first 65,536 is written as - // two escapes, a high surrogate and then a low one. - if (code >= 0xD800 && code <= 0xDBFF) { - std::uint32_t low = 0; - if (!Take('\\') || !Take('u') || !Hex(low) || low < 0xDC00 || low > 0xDFFF) return false; - code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00); - } else if (code >= 0xDC00 && code <= 0xDFFF) { - return false; - } - AppendUtf8(out, code); - break; - } - default: return false; + std::unordered_set seen; + std::function walk = [&](Configuration* depCfg) -> bool { + if (!seen.insert(depCfg).second) return false; + for(const std::unique_ptr& depInterface : depCfg->interfaces) { + if(depInterface->name == importName) { + fs::path depPcmPath = std::format("{}.pcm", (depCfg->PcmDir() / depInterface->path.filename()).string()); + externalDeps.emplace_back(depInterface.get(), std::move(depPcmPath)); + return true; } } - return false; - } - - // The four hexadecimal digits at the cursor, as the number they - // spell, into `code`. - bool Hex(std::uint32_t& code) { - if (text.size() - at < 4) return false; - for (const std::size_t end = at + 4; at < end; ++at) { - const char c = text[at]; - std::uint32_t digit = 0; - if (c >= '0' && c <= '9') { - digit = static_cast(c - '0'); - } else if (c >= 'a' && c <= 'f') { - digit = static_cast(c - 'a' + 10); - } else if (c >= 'A' && c <= 'F') { - digit = static_cast(c - 'A' + 10); - } else { - return false; - } - code = code * 16 + digit; - } - return true; - } - - static void AppendUtf8(std::string& out, std::uint32_t code) { - if (code < 0x80) { - out.push_back(static_cast(code)); - } else if (code < 0x800) { - out.push_back(static_cast(0xC0 | (code >> 6))); - out.push_back(static_cast(0x80 | (code & 0x3F))); - } else if (code < 0x10000) { - out.push_back(static_cast(0xE0 | (code >> 12))); - out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); - out.push_back(static_cast(0x80 | (code & 0x3F))); - } else { - out.push_back(static_cast(0xF0 | (code >> 18))); - out.push_back(static_cast(0x80 | ((code >> 12) & 0x3F))); - out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); - out.push_back(static_cast(0x80 | (code & 0x3F))); - } - } - - // The number at the cursor, kept as it is written: no number that - // clang-scan-deps writes is read. - bool Number(Json& value) { - const std::size_t start = at; - Take('-'); - if (!Digits()) return false; - if (Take('.') && !Digits()) return false; - if (Take('e') || Take('E')) { - if (!Take('+')) Take('-'); - if (!Digits()) return false; - } - value.kind = Json::Kind::Number; - value.text = std::string(text.substr(start, at - start)); - return true; - } - - bool Digits() { - const std::size_t start = at; - while (at < text.size() && text[at] >= '0' && text[at] <= '9') ++at; - return at > start; - } - - bool Word(std::string_view word) { - if (!text.substr(at).starts_with(word)) return false; - at += word.size(); - return true; - } - - bool Take(char c) { - if (at == text.size() || text[at] != c) return false; - ++at; - return true; - } - - void SkipSpace() { - while (at < text.size() && (text[at] == ' ' || text[at] == '\t' || text[at] == '\n' || text[at] == '\r')) ++at; - } - - std::string_view text; - std::size_t at = 0; - }; - - // What one source declares and imports, as clang-scan-deps read it. - struct ScannedUnit { - // The unit of a module it is by its declaration: `X` for the primary - // interface of module X, `X:P` for X's partition P. Empty for a - // source that is neither, as an implementation unit of X written - // `module X;` is, which imports X instead. - std::string provides; - // The modules and partitions it imports, each by its whole name: an - // `import :P;` in a unit of X is `X:P`. - std::vector imports; - }; - - // The unit `document` describes, as clang-scan-deps describes a single - // source in its P1689 format; nullopt for a document of any other shape. - std::optional ReadP1689(const Json& document) { - const Json* rules = document.Member("rules"); - if (rules == nullptr || rules->kind != Json::Kind::Array || rules->items.size() != 1) return std::nullopt; - const Json& rule = rules->items.front(); - // The logical name of each entry of the rule's array `name`, which - // need not be there; false when it is there and is not such an - // array. - const auto names = [&rule](std::string_view name, std::vector& out) { - const Json* entries = rule.Member(name); - if (entries == nullptr) return true; - if (entries->kind != Json::Kind::Array) return false; - for (const Json& entry : entries->items) { - const Json* logical = entry.Member("logical-name"); - if (logical == nullptr || logical->kind != Json::Kind::String) return false; - out.push_back(logical->text); - } - return true; - }; - std::vector provided; - ScannedUnit unit; - if (!names("provides", provided) || provided.size() > 1 || !names("requires", unit.imports)) return std::nullopt; - if (!provided.empty()) unit.provides = std::move(provided.front()); - return unit; - } - - std::optional ReadWholeFile(const fs::path& file) { - std::ifstream in(file, std::ios::binary); - if (!in) return std::nullopt; - std::stringstream buffer; - buffer << in.rdbuf(); - return std::move(buffer).str(); - } - - // The dependency file of the scan Build() keeps at `scan`, beside it: the - // source and every file it included, as a rule for `scan`. - fs::path ScanDepfile(const fs::path& scan) { - return fs::path(scan) += ".d"; - } - - // The scan of a source that Build() keeps at `scan`, when it holds for - // `command`: it was taken for that command, which clang-scan-deps was - // given as ScannedAs makes it, after the source and every file the - // source included were last written (NewestPrerequisite of its - // dependency file). nullopt when it does not, and when it cannot be - // read; the source is then scanned again. - std::optional CurrentScan(const fs::path& scan, std::string_view command) { - std::error_code ec; - const fs::file_time_type written = fs::last_write_time(scan, ec); - if (ec || NewestPrerequisite(ScanDepfile(scan)) >= written) return std::nullopt; - const std::optional text = ReadWholeFile(scan); - if (!text) return std::nullopt; - const std::optional kept = JsonReader(*text).Read(); - if (!kept) return std::nullopt; - const Json* scannedWith = kept->Member("command"); - const Json* p1689 = kept->Member("p1689"); - if (scannedWith == nullptr || scannedWith->kind != Json::Kind::String || scannedWith->text != command || p1689 == nullptr) return std::nullopt; - return ReadP1689(*p1689); - } - - // A unit's name split at its colon: {"X", ""} for the module X, - // {"X", "P"} for X's partition P. - std::pair SplitUnitName(std::string_view name) { - const std::size_t colon = name.find(':'); - if (colon == std::string_view::npos) return {name, {}}; - return {name.substr(0, colon), name.substr(colon + 1)}; - } - - Module* FindModule(std::span> modules, std::string_view name) { - for (const std::unique_ptr& candidate : modules) { - if (candidate->name == name) return candidate.get(); - } - return nullptr; - } - - // The configuration whose build the pass ran for the directory a - // dependency is built into, and so the one that holds the modules of - // that build (BuildResult::built): the dependency itself, or another - // configuration of its directory. - using BuiltConfiguration = std::function; - - // Adds the staleness edge of an import of the module `name` by a unit of - // a configuration whose own modules are `local` and which is built on - // `dependencies`: to the module among `local`, else to the first found - // among the modules of the dependencies and of what they are built on, - // each as `builtIn` gives it, with the BMI that one's build writes, - // unless the unit has that edge already. A module none of them has, - // `std` or one from outside the build, gets no edge. The dependencies - // have been built when this is called, and so have read their sources: - // their modules are known. - void AddImport(std::span> local, std::span dependencies, const BuiltConfiguration& builtIn, std::string_view name, std::vector& localDeps, std::vector>& externalDeps) { - if (Module* own = FindModule(local, name)) { - if (!std::ranges::contains(localDeps, own)) localDeps.push_back(own); - return; - } - std::unordered_set seen; - std::function walk = [&](const Configuration& listed) -> bool { - const Configuration& depCfg = builtIn(listed); - if (!seen.insert(&depCfg).second) return false; - if (Module* found = FindModule(depCfg.interfaces, name)) { - if (!std::ranges::contains(externalDeps, found, &std::pair::first)) { - externalDeps.emplace_back(found, std::format("{}.pcm", (depCfg.PcmDir() / found->path.filename()).string())); - } - return true; - } - for (const Configuration* sub : depCfg.dependencies) { - if (walk(*sub)) return true; + for(Configuration* sub : depCfg->dependencies) { + if (walk(sub)) return true; } return false; }; - for (const Configuration* depCfg : dependencies) { - if (walk(*depCfg)) return; + + for(Configuration* depCfg : cfg.dependencies) { + if (walk(depCfg)) return true; + } + return false; + } +} + +void Configuration::ResolvePendingImports() { + // Same resolution the scan used, and against both dependency kinds — a + // second GetInterfacesAndImplementations call can add interfaces that an + // earlier batch's import was looking for, so a pending name may land on a + // local module and not just an external one. + auto sweep = [this](std::vector& pending, std::vector& localDeps, std::vector>& externalDeps) { + std::erase_if(pending, [&](const std::string& name) { + return ResolveImportName(*this, name, localDeps, externalDeps); + }); + }; + for(const std::unique_ptr& interface : interfaces) { + sweep(interface->pendingImports, interface->moduleDependencies, interface->externalModuleDependencies); + for(const std::unique_ptr& partition : interface->partitions) { + sweep(partition->pendingImports, partition->moduleDependencies, partition->externalModuleDependencies); } } - - // The modules and units of a configuration as the scans of its sources - // describe them, before Build() gives them to the configuration. - struct ModuleGraph { - std::vector> interfaces; - std::vector implementations; - }; - - // Makes the modules and units of `config` from `interfaceScans` and - // `implementationScans`, the scans of its interfaceSources and of its - // implementationSources in the order they are listed in, with its - // dependencies as `builtIn` gives them. Returns why it could not, empty - // when it could. - std::string MakeModuleGraph(const Configuration& config, std::span interfaceScans, std::span implementationScans, const BuiltConfiguration& builtIn, ModuleGraph& graph) { - // A unit is named by its source without the extension. - const auto stem = [](const fs::path& source) { - fs::path stemmed = source; - stemmed.replace_extension(); - return stemmed; - }; - // The unit each interface source is: its module, and for a - // partition the partition as well. - std::vector moduleOf(interfaceScans.size(), nullptr); - std::vector partitionOf(interfaceScans.size(), nullptr); - // The primary interfaces first, so that a partition finds its module - // in whatever order the two are listed. - for (std::size_t i = 0; i < interfaceScans.size(); ++i) { - const auto [moduleName, partitionName] = SplitUnitName(interfaceScans[i].provides); - if (moduleName.empty()) return std::format("No module declaration found in {}", config.interfaceSources[i].string()); - if (!partitionName.empty()) continue; - graph.interfaces.push_back(std::make_unique(std::string(moduleName), stem(config.interfaceSources[i]))); - moduleOf[i] = graph.interfaces.back().get(); - } - for (std::size_t i = 0; i < interfaceScans.size(); ++i) { - const auto [moduleName, partitionName] = SplitUnitName(interfaceScans[i].provides); - if (partitionName.empty()) continue; - Module* owner = FindModule(graph.interfaces, moduleName); - if (owner == nullptr) return std::format("Module {} not found, referenced in {}", moduleName, config.interfaceSources[i].string()); - owner->partitions.push_back(std::make_unique(std::string(partitionName), stem(config.interfaceSources[i]))); - moduleOf[i] = owner; - partitionOf[i] = owner->partitions.back().get(); - } - - // The partition an import of `X:P` names: a partition of the module - // X among this configuration's interface sources. X is the importing - // unit's own module, since only its partitions can be imported. - // nullptr when there is none. - const auto partitionNamed = [&graph](std::string_view moduleName, std::string_view partitionName) -> ModulePartition* { - const Module* owner = FindModule(graph.interfaces, moduleName); - if (owner == nullptr) return nullptr; - for (const std::unique_ptr& partition : owner->partitions) { - if (partition->name == partitionName) return partition.get(); - } - return nullptr; - }; - - for (std::size_t i = 0; i < interfaceScans.size(); ++i) { - ModulePartition* partition = partitionOf[i]; - for (const std::string& name : interfaceScans[i].imports) { - const auto [moduleName, partitionName] = SplitUnitName(name); - if (partitionName.empty()) { - if (partition != nullptr) { - AddImport(graph.interfaces, config.dependencies, builtIn, name, partition->moduleDependencies, partition->externalModuleDependencies); - } else { - AddImport(graph.interfaces, config.dependencies, builtIn, name, moduleOf[i]->moduleDependencies, moduleOf[i]->externalModuleDependencies); - } - continue; - } - ModulePartition* imported = partitionNamed(moduleName, partitionName); - if (imported == nullptr) return std::format("imported partition {}:{} not found, referenced in {}", moduleName, partitionName, config.interfaceSources[i].string()); - // A primary interface needs no edge to its own partitions: it - // is checked and built after every one of them (Module::Check, - // Module::Schedule). - if (partition != nullptr && !std::ranges::contains(partition->partitionDependencies, imported)) partition->partitionDependencies.push_back(imported); - } - } - - for (std::size_t i = 0; i < implementationScans.size(); ++i) { - const fs::path& source = config.implementationSources[i]; - Implementation& implementation = graph.implementations.emplace_back(stem(source)); - // A source that is a unit of a module by its declaration, as an - // implementation partition (`module X:P;`) is, belongs to a - // module of this configuration. - if (const std::string_view moduleName = SplitUnitName(implementationScans[i].provides).first; !moduleName.empty() && FindModule(graph.interfaces, moduleName) == nullptr) { - return std::format("Module {} not found, referenced in {}", moduleName, source.string()); - } - for (const std::string& name : implementationScans[i].imports) { - const auto [moduleName, partitionName] = SplitUnitName(name); - if (partitionName.empty()) { - AddImport(graph.interfaces, config.dependencies, builtIn, name, implementation.moduleDependencies, implementation.externalModuleDependencies); - continue; - } - ModulePartition* imported = partitionNamed(moduleName, partitionName); - if (imported == nullptr) return std::format("imported partition {}:{} not found, referenced in {}", moduleName, partitionName, source.string()); - if (!std::ranges::contains(implementation.partitionDependencies, imported)) implementation.partitionDependencies.push_back(imported); - } - } - return ""; + for(Implementation& implementation : implementations) { + sweep(implementation.pendingImports, implementation.moduleDependencies, implementation.externalModuleDependencies); } } void Configuration::GetInterfacesAndImplementations(std::span interfaces, std::span implementations) { - // Absolute now, so that a path stays the same file when the working - // directory changes, as it does around the load of a GitProject. - for (const fs::path& listed : interfaces) { - fs::path source = fs::absolute(path / listed).lexically_normal(); - source += ".cppm"; - interfaceSources.push_back(std::move(source)); - } - for (const fs::path& listed : implementations) { - fs::path source = fs::absolute(path / listed).lexically_normal(); - source += ".cpp"; - implementationSources.push_back(std::move(source)); - } -} + auto resolveImport = [this](const std::string& importName, std::vector& localDeps, std::vector>& externalDeps, std::vector& pending) { + if (!ResolveImportName(*this, importName, localDeps, externalDeps)) { + pending.push_back(importName); + } + }; -std::string Crafter::StdPcmFlags(const Configuration& config, const Toolchain& toolchain) { - if (config.target == "x86_64-w64-mingw32") { - // -femulated-tls keeps PCM TLS access matching libstdc++'s emutls - // definitions; a mismatch surfaces as undefined std::__once_callable. - return std::format(" --target={} -march={} -mtune={} -femulated-tls -O3 -std=c++26 -Wno-reserved-identifier -Wno-reserved-module-identifier", config.target, config.march, config.mtune); + std::vector> tempModulePaths = std::vector>(interfaces.size()); + for(std::uint16_t i = 0; i < interfaces.size(); i++){ + // Resolve to absolute now so the stored path survives cwd changes + // (matters for GitProject deps loaded from a different working dir). + fs::path file = fs::absolute(path / interfaces[i]).lexically_normal(); + file += ".cppm"; + std::ifstream t(file); + std::stringstream buffer; + buffer << t.rdbuf(); + std::string fileContent = buffer.str(); + fileContent = std::regex_replace(fileContent, std::regex(R"(//[^\n]*)"), ""); + fileContent = std::regex_replace(fileContent, std::regex(R"(/\*.*?\*/)"), ""); + tempModulePaths[i] = {file, fileContent, nullptr, nullptr}; } - const bool isWasm = config.target.starts_with("wasm32"); - const std::string sysroot = config.ResolvedSysroot(toolchain); - const std::string sysrootFlag = sysroot.empty() ? std::string() : std::format(" --sysroot={}", sysroot); - // wasm32 rejects -march, and the std module has to be compiled the way - // the units importing it are, a variant pass's flags (e.g. - // -mrelaxed-simd) included, or the BMI is not feature-compatible. - std::string archFlags = isWasm ? WasmCompileFlags(config) : std::format(" -march={} -mtune={}", config.march, config.mtune); - // non-wasm cross builds: the driver ranks the host toolchain's own - // libc++ headers (/../include/c++/v1) above --sysroot, so the - // PCM would mix host libc++ with the foreign libc. Force the sysroot's - // copy. - if (!isWasm && !sysroot.empty()) { - archFlags += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1", sysroot); - } - return std::format(" --target={} -std=c++26{}{} -O3 -Wno-reserved-identifier -Wno-reserved-module-identifier", config.target, sysrootFlag, archFlags); -} -std::string Crafter::StdPcmKey(const Configuration& config, const Toolchain& toolchain) { - // A PCM is only valid for the clang that wrote it and the flags it was - // written with, so a compiler bump starts a cold directory instead of - // handing the new clang a PCM it will crash on, and so does any flag. - // With only some of them in the name, configurations that differed in - // the rest took turns rebuilding one std PCM in place: -mtune=generic - // against project.cpp's -mtune=native on every run, two sysroots, or two - // releases sharing a cache, as the Flatpak's branches do, each time under - // the PCMs built against the previous one, which clang crashes on rather - // than rejecting. - std::string compiled = StdPcmFlags(config, toolchain); - // The base command's part: the toolchain's key covers the compiler and - // libc++, and for the mingw target what clang finds mingw-w64 through is - // the prefix, given whole or through a view (MingwSysroot), named here by - // the prefix rather than by the view's own path. - if (config.target == "x86_64-w64-mingw32" && !toolchain.mingwPrefix.empty()) { - compiled += std::format("|mingw:{}|{}", toolchain.mingwPrefix.string(), toolchain.mingwPrefixIsSystem ? "view" : "whole"); + // Primary interface units first, so the partition pass below can find their + // parent Module. They stay in tempModulePaths — a primary unit's own + // `import X;` lines are layout dependencies exactly like a partition's, and + // dropping the entry here is what left them unrecorded (issue #26). Marked + // by a null partition slot with the Module slot filled in. + for(std::tuple& file : tempModulePaths) { + std::smatch match; + if (std::regex_search(std::get<1>(file), match, std::regex(R"(export module ([a-zA-Z0-9_\.\-]+);)"))) { + fs::path pthCpy = std::get<0>(file); + pthCpy.replace_extension(""); + this->interfaces.push_back(std::make_unique(std::move(match[1].str()), std::move(pthCpy))); + std::get<3>(file) = this->interfaces.back().get(); + } + } + + for(std::uint16_t i = 0; i < tempModulePaths.size(); i++) { + std::smatch match; + if (std::get<3>(tempModulePaths[i]) != nullptr) { + continue; + } + if (std::regex_search(std::get<1>(tempModulePaths[i]), match, std::regex(R"(export module ([a-zA-Z_0-9\.\-]+):([a-zA-Z_0-9\.\-]+);)"))) { + for(const std::unique_ptr& modulee : this->interfaces) { + if(modulee->name == match[1]) { + std::string name = match[2].str(); + fs::path pthCpy = std::get<0>(tempModulePaths[i]); + pthCpy.replace_extension(""); + std::unique_ptr partition = std::make_unique(std::move(name), std::move(pthCpy)); + std::get<2>(tempModulePaths[i]) = partition.get(); + modulee->partitions.push_back(std::move(partition)); + std::get<3>(tempModulePaths[i]) = modulee.get(); + goto next; + } + } + throw std::runtime_error(std::format("Module {} not found, referenced in {}", match[1].str(), std::get<0>(tempModulePaths[i]).string())); + } else { + throw std::runtime_error(std::format("No module declaration found in {}", std::get<0>(tempModulePaths[i]).string())); + } + next:; + } + + for(std::tuple& file : tempModulePaths) { + ModulePartition* partition = std::get<2>(file); + Module* parentModule = std::get<3>(file); + const std::string& fileContent = std::get<1>(file); + + // Primary interface unit: record only its module imports. Its + // `[export] import :Part;` lines need no edge — Module::Check walks + // every partition it owns and Module::Compile builds them all before + // precompiling itself, so partitions are covered wholesale. + if (partition == nullptr) { + std::regex primaryPattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); + std::sregex_iterator primaryCurrent(fileContent.begin(), fileContent.end(), primaryPattern); + std::sregex_iterator primaryLast; + while (primaryCurrent != primaryLast) { + std::smatch match = *primaryCurrent; + resolveImport(match[1].str(), parentModule->moduleDependencies, parentModule->externalModuleDependencies, parentModule->pendingImports); + ++primaryCurrent; + } + continue; + } + + std::regex partitionPattern(R"(import :([a-zA-Z_\-0-9\.]+);)"); + std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), partitionPattern); + std::sregex_iterator lastMatch; + while (currentMatch != lastMatch) { + std::smatch match = *currentMatch; + for(std::unique_ptr& sibling : parentModule->partitions) { + if(sibling->name == match[1]) { + partition->partitionDependencies.push_back(sibling.get()); + goto next2; + } + } + throw std::runtime_error(std::format("imported partition {}:{} not found, referenced in {}", parentModule->name, match[1].str(), std::get<0>(file).string())); + next2: ++currentMatch; + } + + std::regex modulePattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); + std::sregex_iterator modCurrent(fileContent.begin(), fileContent.end(), modulePattern); + while (modCurrent != lastMatch) { + std::smatch match = *modCurrent; + resolveImport(match[1].str(), partition->moduleDependencies, partition->externalModuleDependencies, partition->pendingImports); + ++modCurrent; + } + } + + for(const fs::path& tempFile : implementations) { + fs::path file = fs::absolute(path / tempFile).lexically_normal(); + file += ".cpp"; + std::ifstream t(file); + std::stringstream buffer; + buffer << t.rdbuf(); + std::string fileContent = buffer.str(); + fileContent = std::regex_replace(fileContent, std::regex(R"(//[^\n]*)"), ""); + fileContent = std::regex_replace(fileContent, std::regex(R"(/\*.*?\*/)"), ""); + std::smatch match; + fs::path fileCopy = file; + fileCopy.replace_extension(""); + Implementation& implementation = this->implementations.emplace_back(std::move(fileCopy)); + if (std::regex_search(fileContent, match, std::regex(R"(module ([a-zA-Z0-9_\.\-]+)(:[a-zA-Z0-9_\.\-]+)?\s*;)"))) { + const bool isPartitionImpl = match[2].length() > 0; + for(const std::unique_ptr& interface : this->interfaces) { + if(interface->name == match[1]) { + if (!isPartitionImpl) { + implementation.moduleDependencies.push_back(interface.get()); + } + std::regex partitionPattern(R"(import :([a-zA-Z_\-0-9\.]+);)"); + std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), partitionPattern); + std::sregex_iterator lastMatch; + while (currentMatch != lastMatch) { + std::smatch match2 = *currentMatch; + for(const std::unique_ptr& partition : interface->partitions) { + if(partition->name == match2[1]) { + implementation.partitionDependencies.push_back(partition.get()); + goto next3; + } + } + throw std::runtime_error(std::format("imported partition {}:{} not found, referenced in {}", match[1].str(), match2[1].str(), file.string())); + next3: ++currentMatch; + } + + std::regex modulePattern(R"(import ([a-zA-Z_0-9\.\-]+);)"); + std::sregex_iterator modCurrent(fileContent.begin(), fileContent.end(), modulePattern); + while (modCurrent != lastMatch) { + std::smatch match2 = *modCurrent; + if (match2[1] != match[1]) { + resolveImport(match2[1].str(), implementation.moduleDependencies, implementation.externalModuleDependencies, implementation.pendingImports); + } + ++modCurrent; + } + goto next4; + } + } + throw std::runtime_error(std::format("Module {} not found not found, referenced in {}", match[1].str(), file.string())); + next4:; + } else { + std::regex pattern(R"(import ([a-zA-Z_\-0-9\.]+);)"); + std::sregex_iterator currentMatch(fileContent.begin(), fileContent.end(), pattern); + std::sregex_iterator lastMatch; + while (currentMatch != lastMatch) { + std::smatch match2 = *currentMatch; + resolveImport(match2[1].str(), implementation.moduleDependencies, implementation.externalModuleDependencies, implementation.pendingImports); + ++currentMatch; + } + } } - return std::format("{}-{}-{}-{:08x}", config.target, config.march, toolchain.Key(), static_cast(std::hash{}(compiled))); } fs::path Crafter::StdPcmDir(const Configuration& config) { - return GetCacheDir() / StdPcmKey(config, GetToolchain()); + // The std PCM is cached per target+march+toolchain: a PCM is only valid + // for the exact clang that wrote it, so a compiler bump starts a cold + // directory instead of handing the new clang a PCM it will crash on. A + // wasm variant pass compiles it with extra codegen flags (e.g. + // -mrelaxed-simd) — its BMI must not be shared with the baseline's, or + // the consuming TUs see a target-feature mismatch. Suffix the cache dir + // with the variant flags when present. + std::string stdPcmKey = std::format("{}-{}-{}", config.target, config.march, GetToolchain().Key()); + // The flags every wasm unit gets are compiled into the std PCM as well, + // and the importing units have to match them. Two releases that share a + // cache and a compiler, as the Flatpak's branches do, would otherwise + // take turns rebuilding this one std PCM, each time underneath the PCMs + // built against the previous one, and clang crashes on those rather than + // rejecting them. + if (config.target.starts_with("wasm32")) { + stdPcmKey += std::format("-{:08x}", static_cast(std::hash{}(WasmBaselineFlags))); + } + for (const std::string& f : config.wasmVariantFlags) { + stdPcmKey += "+"; + for (char c : f) stdPcmKey += (c == '/' || c == '\\') ? '_' : c; + } + return GetCacheDir()/stdPcmKey; } std::string Crafter::WasmCompileFlags(const Configuration& config) { @@ -543,7 +279,7 @@ std::string Crafter::WasmCompileFlags(const Configuration& config) { } fs::path Crafter::ExpectedOutput(const Configuration& config) { - const fs::path dir = config.ProgramDir(); + const fs::path dir = config.BinDir(); const bool mingwTarget = config.target == "x86_64-w64-mingw32"; if (config.type == ConfigurationType::Executable) { if (config.target.starts_with("wasm32")) return dir / std::format("{}.wasm", config.outputName); @@ -559,95 +295,6 @@ fs::path Crafter::ExpectedOutput(const Configuration& config) { return mingwTarget ? dir / std::format("{}.dll", config.outputName) : dir / std::format("lib{}.so", config.outputName); } -namespace { - // `path` resolved against the working directory, with no `.` or `..` in - // it and no separator at its end. - fs::path WithoutSeparator(fs::path path) { - path = fs::absolute(path).lexically_normal(); - return path.has_filename() ? path : path.parent_path(); - } - - // What the name of a source's object ends in, by the source's - // extension: one ending for each kind of source, so a .c beside a .cu - // of its name has an object of its own. Empty for an extension Build() - // compiles no source of. - std::string_view ObjectSuffix(std::string_view extension) { - if (extension == ".cpp") return "_impl.o"; - if (extension == ".c") return "_source.o"; - if (extension == ".cu") return "_cuda.o"; - return ""; - } - - // ObjectPath's rule for the sources of one configuration, with what it - // takes from the configuration worked out once for all of them, and the - // same rule for where Build() keeps the scan of each interface and - // implementation source. - class SourceLayout { - public: - SourceLayout(const fs::path& directory, const fs::path& buildDir) : directory(WithoutSeparator(directory)), inside(buildDir / "objects"), outside(buildDir / "objects-outside"), scansInside(buildDir / "scans"), scansOutside(buildDir / "scans-outside") {} - - // The object of the source a configuration lists as `listed`, which - // is its path without its extension, `extension`. - fs::path Object(const fs::path& listed, std::string_view extension) const { - fs::path object = fs::absolute(listed).lexically_normal(); - object += ObjectSuffix(extension); - const fs::path within = Within(object); - return within.empty() ? outside / object.relative_path() : inside / within; - } - - // Where the scan of `source`, given with its extension, is kept: - // named as Object() names an object, under scans/ and - // scans-outside/, by the source's own name with .json after it, as - // in scans/a/Thing.cppm.json, so that a .cppm and a .cpp of one - // name have one each. - fs::path Scan(const fs::path& source) const { - fs::path scan = fs::absolute(source).lexically_normal(); - scan += ".json"; - const fs::path within = Within(scan); - return within.empty() ? scansOutside / scan.relative_path() : scansInside / within; - } - - // That source as the progress line of its compile names it: by its - // path from the configuration's directory, or by its whole path - // when it lies outside that directory. - std::string Shown(const fs::path& listed, std::string_view extension) const { - fs::path source = fs::absolute(listed).lexically_normal(); - source += extension; - return Shown(source); - } - - // The same for a source given with its extension. - std::string Shown(const fs::path& source) const { - const fs::path resolved = fs::absolute(source).lexically_normal(); - const fs::path within = Within(resolved); - return within.empty() ? resolved.string() : within.string(); - } - - private: - // The path of `resolved` from the configuration's directory; empty - // when it does not lie in that directory. - fs::path Within(const fs::path& resolved) const { - const fs::path relative = resolved.lexically_relative(directory); - if (relative.empty() || relative == "." || *relative.begin() == "..") return {}; - return relative; - } - - fs::path directory; - fs::path inside; - fs::path outside; - fs::path scansInside; - fs::path scansOutside; - }; -} - -fs::path Crafter::ObjectPath(const Configuration& config, const fs::path& source) { - const std::string extension = source.extension().string(); - if (ObjectSuffix(extension).empty()) throw std::invalid_argument(std::format("{} is not a .cpp, .c or .cu source", source.string())); - fs::path listed = source; - listed.replace_extension(); - return SourceLayout(config.path, config.BuildDir()).Object(listed, extension); -} - CompileCommand Crafter::GetCompileCommand(const Configuration& config) { CompileCommand out; out.stdPcmDir = StdPcmDir(config); @@ -664,8 +311,8 @@ CompileCommand Crafter::GetCompileCommand(const Configuration& config) { : std::format(" -march={} -mtune={}", config.march, config.mtune); out.command = std::format("{} --target={}{} -std=c++26 -D CRAFTER_BUILD_CONFIGURATION_TARGET=\\\"{}\\\" -D CRAFTER_BUILD_CONFIGURATION_TARGET_{} -fprebuilt-module-path={} -fprebuilt-module-path={}", GetBaseCommand(config), config.target, archFlags, editedTarget, editedTarget, out.stdPcmDir.string(), out.pcmDir.string()); - if (const std::string sysroot = config.ResolvedSysroot(GetToolchain()); !sysroot.empty()) { - out.command += std::format(" --sysroot={}", sysroot); + if (!config.sysroot.empty()) { + out.command += std::format(" --sysroot={}", config.sysroot); // Same reason as in BuildStdPcm: the driver ranks the host // toolchain's own libc++ headers (/../include/c++/v1) above // --sysroot. A unit that only does `import std;` never notices, but @@ -679,7 +326,7 @@ CompileCommand Crafter::GetCompileCommand(const Configuration& config) { // option in compileFlags) on sysroot builds. Not for mingw, which // uses libstdc++ and has no libc++ in its sysroot. if (!isWasm && config.target != "x86_64-w64-mingw32") { - out.command += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1 -Wno-unused-command-line-argument", sysroot); + out.command += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1 -Wno-unused-command-line-argument", config.sysroot); } } if (isWasm) { @@ -711,28 +358,12 @@ CompileCommand Crafter::GetCompileCommand(const Configuration& config) { // -I propagation that's valid for both C and C++ compiles. Module-only // bits (-fprebuilt-module-path) stay on `command` only. { - // bin/ and build/ hold what builds write for the configuration whose - // path holds them: crafter-build's own outputs (BinDir(), BuildDir()) - // and whatever else a build leaves there, a CMake build tree or a - // flatpak-builder /app tree among it, whose include/ holds another - // library's or toolchain's headers and never the dependency's own. - // The walk leaves out every directory of those names, not only the - // graph's: a dependency's tree holds the outputs of configurations - // outside the graph too, a program in a directory below it or a - // project of its own beside it, as Crafter.Graphics' examples are. - // Walked, they would have every compile built on the dependency take - // those headers before the system's, and what compiled depend on - // which builds had run. std::unordered_set seen; std::function addFlags = [&](Configuration* dep) { if (!seen.insert(dep).second) return; - for (auto it = fs::recursive_directory_iterator(dep->path); it != fs::recursive_directory_iterator(); ++it) { - if (!it->is_directory()) continue; - const fs::path name = it->path().filename(); - if (name == "bin" || name == "build") { - it.disable_recursion_pending(); - } else if (name == "include") { - out.includeFlags += std::format(" -I{}", it->path().string()); + for (const auto& entry : fs::recursive_directory_iterator(dep->path)) { + if (entry.is_directory() && entry.path().filename() == "include") { + out.includeFlags += std::format(" -I{}", entry.path().string()); } } out.includeFlags += std::format(" -I{}", dep->path.string()); @@ -807,21 +438,6 @@ CompileCommand Crafter::GetCompileCommand(const Configuration& config) { } namespace { - // Two of `configurations` that would be built into one directory, as - // the error that names them; empty when no two would. Built side by - // side they are two builds writing the same files, and a pass that has - // built one of them hands it to whatever is built on the other. - std::string SameDirectoryError(std::span configurations) { - std::unordered_map builtInto; - for (const Configuration* cfg : configurations) { - const auto [known, added] = builtInto.try_emplace(fs::absolute(cfg->PcmDir()).lexically_normal(), cfg); - if (!added && known->second != cfg) { - return std::format("two configurations named {} would both be built into {}: give each a name of its own", cfg->name, known->first.string()); - } - } - return ""; - } - // The outcome of `work` for `key` in this build pass. The first caller // runs it; every other caller, whether at the same time or later, waits // for that run and gets its result or its exception. The keys are the @@ -852,13 +468,8 @@ namespace { // that it was the build they had been compiled against. The program then // linked code compiled against two layouts of the same types, and ran // (issue #41). Empty when the dependencies agree, otherwise the error, - // naming the path to each of the two builds. Asked once Build() has read - // the sources of `config`: the modules of a configuration are what the - // build that read its sources found (Configuration::interfaces), and - // those of each dependency are known once it is built. A dependency is - // taken as `builtIn` gives it, so two configurations that the pass - // builds into one directory are one build of their modules, not two. - std::string DuplicateModuleError(const Configuration& config, const BuiltConfiguration& builtIn) { + // naming the path to each of the two builds. + std::string DuplicateModuleError(const Configuration& config) { struct Owner { const Configuration* cfg; std::string chain; @@ -869,8 +480,7 @@ namespace { std::unordered_map owners; std::unordered_set visited; std::string error; - std::function walk = [&](const Configuration& listed, const std::string& chain) { - const Configuration& c = &listed == &config ? config : builtIn(listed); + std::function walk = [&](const Configuration& c, const std::string& chain) { if (!error.empty() || !visited.insert(&c).second) return; for (const std::unique_ptr& iface : c.interfaces) { const auto [it, inserted] = owners.emplace(iface->name, Owner{ &c, chain }); @@ -884,66 +494,6 @@ namespace { return error; } - // Interface units of `config` that are each built after the next, round - // to the first again: partitions that import each other, a partition that - // imports its own module, sibling modules that import each other. Empty - // when there are none, otherwise the error naming the round. No order - // builds such units. Schedule() works the order out before it adds a - // unit's jobs, by following the imports, and would follow a round of - // them without end. When each unit had a thread that waited for the - // units it imports, such a build hung with no compiler running. - std::string ImportCycleError(const Configuration& config) { - struct Unit { - std::string name; - std::vector builtAfter; - bool entered = false; - bool left = false; - }; - // By address: a module and a partition are different types, and a - // unit's imports name either. Walked in the order the units were - // declared, so the same project gets the same message every time. - std::unordered_map units; - std::vector declared; - for (const std::unique_ptr& module : config.interfaces) { - declared.push_back(module.get()); - Unit& primary = units[module.get()]; - primary.name = module->name; - for (const Module* imported : module->moduleDependencies) primary.builtAfter.push_back(imported); - for (const std::unique_ptr& partition : module->partitions) { - // The primary interface is built after every partition of - // its module, whether it imports that one or not. - primary.builtAfter.push_back(partition.get()); - declared.push_back(partition.get()); - Unit& unit = units[partition.get()]; - unit.name = std::format("{}:{}", module->name, partition->name); - for (const ModulePartition* imported : partition->partitionDependencies) unit.builtAfter.push_back(imported); - for (const Module* imported : partition->moduleDependencies) unit.builtAfter.push_back(imported); - } - } - std::vector chain; - std::string round; - std::function visit = [&](Unit& unit) { - if (!round.empty() || unit.left) return; - if (unit.entered) { - // Back at a unit this walk is still inside of: the round is - // the chain from where it was entered. - for (auto it = std::ranges::find(chain, &unit); it != chain.end(); ++it) round += std::format("{} -> ", (*it)->name); - round += unit.name; - return; - } - unit.entered = true; - chain.push_back(&unit); - for (const void* before : unit.builtAfter) { - if (const auto found = units.find(before); found != units.end()) visit(found->second); - } - chain.pop_back(); - unit.left = true; - }; - for (const void* unit : declared) visit(units.at(unit)); - if (round.empty()) return ""; - return std::format("{}: these interface units are each built after the next, so none can be built first: {}. A unit is built after the modules and partitions it imports, and a module's primary interface after all of its partitions.", config.name, round); - } - // What a wasm32 configuration cannot be built with now that every unit // has C++ exceptions, and what its sysroot has to have for that; empty // for any other target and when nothing is wrong. Each would otherwise @@ -972,7 +522,7 @@ namespace { if (config.type == ConfigurationType::LibraryDynamic) { return std::format("{}: wasm32 shared libraries are not supported: the exception-enabled libc++ they would link has static archives only", config.name); } - const fs::path sysroot = config.ResolvedSysroot(GetToolchain()); + const fs::path sysroot = config.sysroot; if (!fs::is_directory(sysroot)) { return std::format("no WASI sysroot at {}: the Flatpak bundles one, and CRAFTER_BUILD_WASI_SYSROOT selects another", sysroot.string()); } @@ -991,262 +541,6 @@ namespace { } return ""; } - - // Why `config` cannot be the Flatpak it asks for; empty when it can be, - // or does not ask. Checked before anything is built, like WasmBuildError: - // each of these would otherwise surface as an app that does not start - // once installed, or not at all on the machine it was meant for. - std::string FlatpakBuildError(const Configuration& config) { - if (config.ResolvedPackaging() != Packaging::Flatpak) return ""; - if (config.target == "x86_64-w64-mingw32") return std::format("{}: a Windows executable is not packaged as a Flatpak; it stays an .exe", config.name); - if (config.target.starts_with("wasm32")) return std::format("{}: a wasm build is not packaged as a Flatpak; it stays a .wasm", config.name); - const Toolchain& tc = GetToolchain(); - if (tc.flatpakBranch.empty()) { - return std::format("{}: only the Flatpak crafter-build packages a Flatpak: a native one links the program against the host's glibc and libc++, which no Flatpak runtime matches", config.name); - } - if (!config.sysroot.empty()) { - return std::format("{}: a build against a sysroot ({}) links that sysroot's libraries, its C library among them, and not those of the runtime the app runs on", config.name, config.sysroot); - } - if (NormalizeTarget(config.target) != std::format("{}-linux-gnu", tc.flatpakArch)) { - if (config.target.ends_with("-linux-musl")) return std::format("{}: {} links musl, which no Flatpak runtime provides", config.name, config.target); - return std::format("{}: {} is not packaged as a Flatpak: the runtime crafter-build runs on, and the libc++ it would bundle, are {}", config.name, config.target, tc.flatpakArch); - } - // The libc++ a Flatpak carries is the toolchain's own, built against - // the runtime's glibc. One from CRAFTER_BUILD_LIBCXX_DIR is what the - // program would be compiled and linked against instead, and nothing - // says which glibc it needs: bundled, it may not load on the - // runtime; not bundled, the program loads a libc++ it was not built - // against. - if (!tc.libcxxDir.empty()) { - return std::format("{}: a build against CRAFTER_BUILD_LIBCXX_DIR ({}) links that libc++, and a Flatpak carries the toolchain's own, built against the runtime's glibc: unset it to package a Flatpak", config.name, tc.libcxxDir.string()); - } - return ""; - } - - // What an asset is compressed to, by the extension Crafter.Asset reads: - // the formats stb_image loads (behind TextureAsset::LoadPNG) to .ctex, - // .obj to .cmesh; nullopt for anything else. The one rule for an - // executable's own assets and the ones its dependencies forward to it. - std::optional CompressedAssetName(const fs::path& src) { - std::string ext = src.extension().string(); - for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); - if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { - return fs::path(src.filename()).replace_extension(".ctex"); - } - if (ext == ".obj") return fs::path(src.filename()).replace_extension(".cmesh"); - return std::nullopt; - } - - std::string AppIdOf(const Configuration& config) { - return config.flatpak.appId.empty() ? DefaultFlatpakAppId(config.outputName) : config.flatpak.appId; - } - - // The sandbox's permissions as the executable gets them: a dependency's - // dependencies before it, each once, and the executable's own last, so - // it has the last word. - std::vector PermissionsOf(const Configuration& config) { - std::vector permissions; - std::unordered_set seen; - std::function walk = [&](const Configuration* c) { - if (!seen.insert(c).second) return; - for (const Configuration* dep : c->dependencies) walk(dep); - for (const std::string& permission : c->flatpak.permissions) permissions.push_back({permission, c->name}); - }; - for (const Configuration* dep : config.dependencies) walk(dep); - for (const std::string& permission : config.flatpak.permissions) permissions.push_back({permission, config.name}); - return permissions; - } - - // The writer's record: one per bin dir, as there is one bin dir per - // BuildDir(). VariantId() does not hold outputName, and under a name of - // its own the record of a program renamed in place was not found, so - // the old program stayed in files/bin as one it wrote. - fs::path FlatpakRecordPath(const Configuration& config) { - return config.BuildDir() / "flatpak-record"; - } - - // Gathers what WriteFlatpakFiles needs from `config`, the link that just - // ran and the top-level names Build()'s copies placed in files/bin, and - // has it lay out files/. - std::string WriteFlatpak(const Configuration& config, const BuildResult& linked, const std::set& placed) { - const Toolchain& tc = GetToolchain(); - FlatpakFiles d; - d.root = config.BinDir(); - d.record = FlatpakRecordPath(config); - d.appId = AppIdOf(config); - d.command = ExpectedOutput(config).filename().string(); - d.desktopFile = config.flatpak.desktopFile; - d.metainfo = config.flatpak.metainfo; - d.icons = config.flatpak.icons; - d.share = config.flatpak.share; - d.appDir = FlatpakAppDir(config); - d.clangxx = tc.clangxx; - d.readelf = tc.llvmReadelf; - for (const std::string& dir : linked.runPaths) d.libraryDirs.emplace_back(dir); - // Last, the toolchain's own lib dir, which the link searches as well - // (LibcxxSearchFlags): a library it takes from there, libclang or - // libedit of crafter-build's /app/lib, is no runtime's. -r would not - // show it missing, since crafter-build's sandbox has /app/lib on the - // loader's path, but the installed app would not start. - if (const fs::path toolchainLib = tc.LibcxxLibDir(); !toolchainLib.empty()) d.libraryDirs.push_back(toolchainLib); - d.programEntries = placed; - return WriteFlatpakFiles(d); - } - - // The name a file is written under before MoveIntoPlace gives it its - // own: beside its place, so that the move is a rename, and no other - // write's, in this process or in another. A build writes files that a - // step of another crafter-build may be reading at that moment: a - // project loaded with GitProject is built in its clone in the cache, - // which every project that names the same source shares, and nothing - // keeps two crafter-builds from building it at once. The name is made - // of random bits and not of the process's id: a crafter-build that - // runs as a Flatpak has the process ids of its own sandbox, and two of - // them the same ones. - fs::path WrittenBeside(const fs::path& file) { - std::random_device random; - return fs::path(file) += std::format(".{:08x}{:08x}.tmp", random(), random()); - } - - // Moves `written` to `file`. The rename puts it there in one step: what - // opens `file` finds the file of before or this one, never none and - // never part of one, and what has the file of before open goes on - // reading that one. Returns what went wrong, with `written` removed; - // empty when nothing did. - std::string MoveIntoPlace(const fs::path& written, const fs::path& file) { - std::error_code ec; - fs::rename(written, file, ec); - if (!ec) return ""; - std::string failed = std::format("cannot move {} to {}: {}", written.string(), file.string(), ec.message()); - fs::remove(written, ec); - return failed; - } - - // `argument` as one argument in a response file, the file of further - // arguments a command names with @. clang and llvm-ar split such a file - // at whitespace, keep what stands in quotes together, and take a - // backslash to quote the character after it, inside quotes as well. - // That last is why this is not ShellQuote: the shell keeps a backslash - // in single quotes as it is. - std::string ResponseFileArgument(std::string_view argument) { - std::string quoted = "\""; - for (const char c : argument) { - if (c == '"' || c == '\\') quoted.push_back('\\'); - quoted.push_back(c); - } - quoted.push_back('"'); - return quoted; - } - - // `command`, a compile command of GetCompileCommand's, with its first - // word, the toolchain's clangxx, made - // Toolchain::InstalledClangxx(command), the compiler where clang started - // with that command takes itself to be. clang-scan-deps runs a clang - // driver of its own over the command after its --, and that driver looks - // for clang's own headers, and in a build for the host whose command names - // no libc++ directory for libc++'s too, from the directory of the - // command's first word, found on PATH where it is a bare name, without - // following a link to where the compiler is, whatever the command says of - // canonical prefixes: with a clangxx reached through a link from another - // directory, as CRAFTER_BUILD_LLVM_DIR may name one, a source that - // includes a header of the C++ standard library failed its scan where - // those headers were not to be found from the link's directory, though its - // compile, which takes itself to be where the link leads unless the - // command's last prefix flag is -no-canonical-prefixes, found the header. - // A command that does not start with clangxx is left as it is. - std::string ScannedAs(std::string_view command) { - const Toolchain& tc = GetToolchain(); - const std::string compiler = tc.clangxx.string(); - if (!command.starts_with(compiler)) return std::string(command); - return std::format("{}{}", ShellQuote(tc.InstalledClangxx(command).string()), command.substr(compiler.size())); - } - - // Has `scanner`, clang-scan-deps, read `source` as `command` compiles it, - // and keeps what it found at `scan` for CurrentScan: a JSON object of the - // command and of the P1689 description the scanner wrote, with the - // dependency file of what the source included beside it. Both are - // written beside their places and moved into them (WrittenBeside), as - // another crafter-build may be reading them. Returns what went wrong, - // empty when nothing did, and then leaves what it found in `found`. - std::string ScanSource(const fs::path& scanner, std::string_view command, const fs::path& source, const fs::path& scan, ScannedUnit& found) { - std::error_code ec; - fs::create_directories(scan.parent_path()); - const fs::path description = WrittenBeside(scan); - const fs::path depfile = WrittenBeside(ScanDepfile(scan)); - // -w: what the preprocessor warns of, the compile of the source - // reports. The command's own output is named `scan`, so that the - // dependency file is the rule for the scan. - const std::string failed = RunBuildCommand(std::format("{} -format=p1689 -o {} -- {} -w {} -c -MD -MF {} -o {}", ShellQuote(scanner.string()), ShellQuote(description.string()), ScannedAs(command), ShellQuote(source.string()), ShellQuote(depfile.string()), ShellQuote(scan.string()))); - const std::optional written = ReadWholeFile(description); - fs::remove(description, ec); - if (!failed.empty()) { - fs::remove(depfile, ec); - return failed; - } - const std::optional document = written ? JsonReader(*written).Read() : std::nullopt; - std::optional unit = document ? ReadP1689(*document) : std::nullopt; - if (!unit) { - fs::remove(depfile, ec); - return std::format("clang-scan-deps wrote no description of {} that crafter-build can read: {}", source.string(), written.value_or("")); - } - const fs::path kept = WrittenBeside(scan); - std::ofstream out(kept, std::ios::binary | std::ios::trunc); - out << std::format("{{\"command\": {}, \"p1689\": {}}}\n", JsonQuote(command), *written); - out.close(); - if (out.fail()) { - fs::remove(kept, ec); - fs::remove(depfile, ec); - return std::format("cannot write {}, the scan of {}", kept.string(), source.string()); - } - // The dependency file first. Should the second move fail, the scan - // of before is left beside the dependency file of now, which lists - // what the source includes now; the other way round, the scan of - // now would be left beside the dependency file of before, which may - // miss a header the source includes now, and an edit of that header - // would not have the source scanned again. - if (std::string moved = MoveIntoPlace(depfile, ScanDepfile(scan)); !moved.empty()) { - fs::remove(kept, ec); - return moved; - } - if (std::string moved = MoveIntoPlace(kept, scan); !moved.empty()) return moved; - found = std::move(*unit); - return ""; - } - - // Reads what each interface and implementation source of `config` - // declares and imports, as `command`, the command they are compiled - // with, compiles them (ScanSource), and gives the configuration the - // modules and units that makes. A - // source whose scan is current (CurrentScan) is not read again; the - // others are scanned at once, each a job on the workers of the process. - // Returns why it could not, empty when it could; the configuration then - // keeps the modules and units it had. Its dependencies are taken as - // `builtIn` gives them. - std::string ReadSources(Configuration& config, std::string_view command, const SourceLayout& layout, const BuiltConfiguration& builtIn) { - std::vector sources = config.interfaceSources; - sources.insert(sources.end(), config.implementationSources.begin(), config.implementationSources.end()); - std::vector scans(sources.size()); - { - JobGroup scanning; - for (std::size_t i = 0; i < sources.size(); ++i) { - fs::path scan = layout.Scan(sources[i]); - if (std::optional current = CurrentScan(scan, command)) { - scans[i] = std::move(*current); - continue; - } - scanning.Add(std::format("Scanning {}", layout.Shown(sources[i])), [&scans, i, scanner = GetToolchain().clangScanDeps, command = std::string(command), source = sources[i], scan = std::move(scan)] { - return ScanSource(scanner, command, source, scan, scans[i]); - }); - } - if (std::string failed = scanning.Wait(); !failed.empty()) return failed; - } - const std::span scanned(scans); - ModuleGraph graph; - if (std::string error = MakeModuleGraph(config, scanned.first(config.interfaceSources.size()), scanned.subspan(config.interfaceSources.size()), builtIn, graph); !error.empty()) return error; - config.interfaces = std::move(graph.interfaces); - config.implementations = std::move(graph.implementations); - return ""; - } } BuildResult Crafter::Build(Configuration& config, std::unordered_map>& depResults, std::mutex& depMutex) { @@ -1255,54 +549,66 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapchecked = false; + iface->compiled.store(false); + for (auto& part : iface->partitions) { + part->checked = false; + part->compiled.store(false); + } + } + + // Sources were scanned when they were declared, which for most callers is + // before `dependencies` exists — AddTest resolves tests//main.cpp and + // only then hands back a builder whose .Dependencies() supplies the library. + // Any `import ;` in such a TU resolved to nothing and so carried + // no staleness edge, which meant a member added to a dependency's interface + // rebuilt the library, relinked the consumer, and silently kept the + // consumer's object compiled against the *old* class layout (issue #27). + // Re-resolving here — the last point before mtimes are compared, with the + // DAG fully wired — closes that window for every caller rather than for the + // ones that remember to declare in the right order. + config.ResolvePendingImports(); + + // Auto-detect the WASI sysroot before any compile step runs so BuildStdPcm + // and the main compile command see the same value. Covers all wasm32-* + // triples (wasi, wasip1, wasip2, ...); the sysroot's per-triple subdirs + // handle the differences. + if (config.sysroot.empty() && config.target.starts_with("wasm32")) { + config.sysroot = GetToolchain().wasiSysroot.string(); + } + // As early as the duplicate-module check, so a refused build leaves no + // directory behind and starts no thread, but after the sysroot is known. if (std::string refused = WasmBuildError(config); !refused.empty()) { return {std::move(refused), false, {}}; } fs::path buildDir = config.BuildDir(); - // Where the object of each .cpp, .c and .cu of this configuration goes, - // what its compile is called (ObjectPath), and where the scan of each - // .cppm and .cpp is kept. - const SourceLayout layout(config.path, buildDir); - // Everything this configuration produces lands here: a library's archive - // and module PCMs, an executable and the files it reads at run time. - fs::path outputDir = config.ProgramDir(); - // The top-level names this build places in outputDir, which a Flatpak's - // writer keeps in files/bin and an earlier build's it removes. Each copy - // below records its own destination as it decides it: the name that - // follows outputDir in it, or, for a directory copied into outputDir - // itself ("data/", "data/."), the names of what that directory holds. - std::set placed = {ExpectedOutput(config).filename().string()}; - const fs::path outputRoot = WithoutSeparator(outputDir); - const auto place = [&](const fs::path& destination, const fs::path& source) { - const fs::path normal = WithoutSeparator(destination); - if (normal != outputRoot) { - placed.insert(normal.lexically_relative(outputRoot).begin()->string()); - return; - } - std::error_code ec; - for (const fs::directory_entry& child : fs::directory_iterator(source, ec)) placed.insert(child.path().filename().string()); - }; - // A build that fails has copied into files/bin all the same, so what it - // placed joins the writer's record on every way out of Build(): the next - // write removes what no build places any more, rather than take it for - // a file the program wrote. After a write, the record holds these names - // already. - struct PlacedOnExit { - const Configuration& config; - const std::set& names; - ~PlacedOnExit() { - if (config.ResolvedPackaging() == Packaging::Flatpak) RecordFlatpakPlaced(FlatpakRecordPath(config), names); - } - }; - const PlacedOnExit placedOnExit{config, placed}; + fs::path outputDir = config.BinDir(); if (!fs::exists(buildDir)) { fs::create_directories(buildDir); @@ -1317,7 +623,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map shaderIncludeDirs; @@ -1337,23 +643,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map threads; + threads.reserve(config.shaders.size() + 1 + config.interfaces.size() + config.implementations.size()); + std::string buildError; + std::atomic buildCancelled{false}; // Two entries with the same output name would compile in parallel into // one file: whichever finished last won, the build reported success, and // Check() then called both up to date. The usual way in is one source @@ -1364,18 +658,27 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapsecond->path.string(), shader.path.string(), existing->first)); + buildError = std::format("shaders {} and {} both compile to {}: give one of them a distinct Shader::variant", existing->second->path.string(), shader.path.string(), existing->first); + buildCancelled.store(true); break; } } for (const Shader& shader : config.shaders) { - if (jobs.Failed()) break; - place(outputDir / shader.OutputName(), {}); + if (buildCancelled.load(std::memory_order_relaxed)) break; if (shader.Check(outputDir, buildDir, shaderIncludeDirs)) continue; - // A source registered more than once shows up once per variant; - // name the variant so the lines can be told apart. - jobs.Add(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant), [&shader, &outputDir, &buildDir, &shaderIncludeDirs] { - return shader.Compile(outputDir, buildDir, shaderIncludeDirs); + threads.emplace_back([&shader, &outputDir, &buildDir, &shaderIncludeDirs, &buildError, &buildCancelled]() { + // A source registered more than once shows up once per variant; + // name the variant so the lines can be told apart. + Progress::Task task(shader.variant.empty() ? std::format("Compiling shader {}", shader.path.filename().string()) : std::format("Compiling shader {} ({})", shader.path.filename().string(), shader.variant)); + if (buildCancelled.load(std::memory_order_relaxed)) return; + + std::string result = shader.Compile(outputDir, buildDir, shaderIncludeDirs); + if (result.empty()) return; + + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); + } }); } @@ -1387,19 +690,33 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map std::optional { + std::string ext = src.extension().string(); + for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); + // stb_image (used by CompressAsset → TextureAsset::LoadPNG) handles + // png/tga/jpg/bmp; all map to .ctex. + if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { + return fs::path(src.filename()).replace_extension(".ctex"); + } + if (ext == ".obj") return fs::path(src.filename()).replace_extension(".cmesh"); + return std::nullopt; + }; auto submitCompress = [&](fs::path sourcePath, fs::path outRelative) { - place(outputDir / outRelative, {}); fs::path out = outputDir / outRelative; if (fs::exists(out) && fs::exists(sourcePath) && fs::last_write_time(sourcePath) <= fs::last_write_time(out)) return; - // Named before the job takes the path: the arguments of one call - // are evaluated in no particular order. - std::string label = std::format("Compressing asset {}", sourcePath.filename().string()); - jobs.Add(std::move(label), [sourcePath = std::move(sourcePath), out = std::move(out)] { + threads.emplace_back([sourcePath = std::move(sourcePath), out = std::move(out), &buildError, &buildCancelled]() { + Progress::Task task(std::format("Compressing asset {}", sourcePath.filename().string())); + if (buildCancelled.load(std::memory_order_relaxed)) return; std::error_code ec; fs::create_directories(out.parent_path(), ec); - return CompressAsset(sourcePath, out); + std::string result = CompressAsset(sourcePath, out); + if (result.empty()) return; + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); + } }); }; std::vector> assetPassthroughs; @@ -1409,68 +726,81 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map compName = CompressedAssetName(entry.path())) { + if (std::optional compName = compressedName(entry.path())) { submitCompress(entry.path(), topName / rel.parent_path() / *compName); } else { - place(outputDir / topName / rel, {}); assetPassthroughs.emplace_back(entry.path(), topName / rel); } } } else { - std::optional outName = CompressedAssetName(asset); + std::optional outName = compressedName(asset); if (!outName) { - jobs.Fail(std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string())); + buildCancelled.store(true); + buildError = std::format("{}: unsupported asset extension (expected .png/.tga/.jpg/.bmp/.obj, or a directory)", asset.string()); break; } submitCompress(asset, *outName); } } if (!assetPassthroughs.empty()) { - // What a copy throws is the job's error (JobGroup::Add), here and - // for cfg.files below. - jobs.Add("Copying asset passthrough files", [passthroughs = std::move(assetPassthroughs), &outputDir]() -> std::string { - for (const auto& [src, rel] : passthroughs) { - fs::path dst = outputDir / rel; - fs::create_directories(dst.parent_path()); - if (!fs::exists(dst)) { - fs::copy_file(src, dst); - } else if (fs::last_write_time(src) > fs::last_write_time(dst)) { - fs::copy_file(src, dst, fs::copy_options::overwrite_existing); + threads.emplace_back([passthroughs = std::move(assetPassthroughs), &outputDir, &buildCancelled, &buildError]() { + Progress::Task task("Copying asset passthrough files"); + if (buildCancelled.load(std::memory_order_relaxed)) return; + try { + for (const auto& [src, rel] : passthroughs) { + fs::path dst = outputDir / rel; + fs::create_directories(dst.parent_path()); + if (!fs::exists(dst)) { + fs::copy_file(src, dst); + } else if (fs::last_write_time(src) > fs::last_write_time(dst)) { + fs::copy_file(src, dst, fs::copy_options::overwrite_existing); + } + } + } catch (const std::exception& e) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = e.what(); } } - return {}; }); } - for (const fs::path& additionalFile : config.files) place(outputDir / additionalFile.filename(), additionalFile); - jobs.Add(std::format("Copying files for {}", config.name), [&config, &outputDir]() -> std::string { - for (const fs::path& additionalFile : config.files) { - fs::path destination = outputDir / additionalFile.filename(); - if (fs::is_directory(additionalFile)) { - for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) { - const fs::path& sourcePath = entry.path(); - fs::path relativePath = fs::relative(sourcePath, additionalFile); - fs::path destPath = destination / relativePath; - if (entry.is_directory()) { - if (!fs::exists(destPath)) fs::create_directories(destPath); - } else if (entry.is_regular_file()) { - fs::create_directories(destPath.parent_path()); - if (!fs::exists(destPath)) { - fs::copy_file(sourcePath, destPath); - } else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) { - fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing); + threads.emplace_back([&config, &outputDir, &buildCancelled, &buildError]() { + Progress::Task task(std::format("Copying files for {}", config.name)); + if (buildCancelled.load(std::memory_order_relaxed)) return; + try { + for (const fs::path& additionalFile : config.files) { + fs::path destination = outputDir / additionalFile.filename(); + if (fs::is_directory(additionalFile)) { + for (const auto& entry : fs::recursive_directory_iterator(additionalFile)) { + const fs::path& sourcePath = entry.path(); + fs::path relativePath = fs::relative(sourcePath, additionalFile); + fs::path destPath = destination / relativePath; + if (entry.is_directory()) { + if (!fs::exists(destPath)) fs::create_directories(destPath); + } else if (entry.is_regular_file()) { + fs::create_directories(destPath.parent_path()); + if (!fs::exists(destPath)) { + fs::copy_file(sourcePath, destPath); + } else if (fs::last_write_time(sourcePath) > fs::last_write_time(destPath)) { + fs::copy_file(sourcePath, destPath, fs::copy_options::overwrite_existing); + } } } - } - } else { - if (!fs::exists(destination)) { - fs::copy_file(additionalFile, destination); - } else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) { - fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing); + } else { + if (!fs::exists(destination)) { + fs::copy_file(additionalFile, destination); + } else if (fs::last_write_time(additionalFile) > fs::last_write_time(destination)) { + fs::copy_file(additionalFile, destination, fs::copy_options::overwrite_existing); + } } } + } catch(std::exception& e) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = e.what(); + } } - return {}; }); std::vector externalResults(config.externalDependencies.size()); @@ -1480,7 +810,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map objects; + std::string files; std::set libSet; - std::set runtimeSet; std::set publicFlagSet; - std::set runPathSet; std::mutex fileMutex; std::vector depThreads; depThreads.reserve(config.dependencies.size()); @@ -1560,22 +890,28 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map built = OncePerPass(depResults, depMutex, dep->PcmDir(), [&] { return Build(*dep, depResults, depMutex); }); const BuildResult& result = built.get(); fileMutex.lock(); for (const std::string& lib : result.libs) libSet.insert(lib); - for (const std::string& lib : result.runtimeLibs) runtimeSet.insert(lib); for (const std::string& f : result.publicCompileFlags) publicFlagSet.insert(f); - for (const std::string& dir : result.runPaths) runPathSet.insert(dir); fileMutex.unlock(); - if (!result.result.empty()) jobs.Fail(result.result); + if (!result.result.empty()) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = result.result; + } + } if (result.repack) { repack = true; } } catch (const std::exception& e) { - jobs.Fail(std::format("dep build for {} threw: {}", dep->path.string(), e.what())); + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::format("dep build for {} threw: {}", dep->path.string(), e.what()); + } } }); } @@ -1590,11 +926,11 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { - // The job makes the directory of its object, which is one for - // the source's own directory: the compiler makes none. - // - // The source, the dependency file and the object are quoted - // for the shell, as the CUDA compile below quotes its own. The - // object of a source outside the configuration's directory is - // named by that source's whole path, and so holds directories - // this command did not name while an object lay in the build - // directory itself: the working directory's, where the source - // is listed relative to it. A build from a directory with a - // space in its name would have stopped here. - jobs.Add(std::format("Compiling {}", layout.Shown(cFile, ".c")), [directory = object.parent_path(), command = std::format("{8} {0} --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7} -o {9}", ShellQuote(srcPath), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, ShellQuote(std::format("{}.d", objPath)), GetToolchain().clang.string(), ShellQuote(objPath))] { - fs::create_directories(directory); - return RunBuildCommand(command); + threads.emplace_back([&cFile, &buildDir, &buildError, &buildCancelled, &config, &includeFlags, &defineFlags, &userFlags, &cArchFlags, <oCompileFlags]() { + Progress::Task task(std::format("Compiling {}.c", cFile.filename().string())); + if (buildCancelled.load(std::memory_order_relaxed)) return; + + std::string result = RunBuildCommand(std::format("{8} {0}.c --target={1}{2} -O3{3} -c{4}{5}{6} -MD -MF {7}_source.o.d -o {7}_source.o", cFile.string(), config.target, cArchFlags, ltoCompileFlags, includeFlags, defineFlags, userFlags, (buildDir / cFile.filename()).string(), GetToolchain().clang.string())); + if (result.empty()) return; + + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); + } }); } } for (const fs::path& cFile : config.cuda) { - const fs::path object = layout.Object(cFile, ".cu"); - objects.push_back(object); - const std::string objPath = object.string(); + files += std::format(" {}_source.o ", (buildDir / cFile.filename()).string()); + const std::string objPath = std::format("{}_source.o", (buildDir / cFile.filename()).string()); const std::string srcPath = std::format("{}.cu", cFile.string()); - // nvcc writes the depfile clang writes for a C source (-MD -MF): the - // .cu and every header it read, the toolkit's and the system's among - // them, as a Make rule NewestPrerequisite reads as it reads clang's, - // although nvcc puts a space before the colon. Without it, a .cu - // whose header changed kept its old object. cfg.cudaArch needs no - // check: it is part of VariantId, so another one builds in another - // directory. - if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath)) || NewestPrerequisite(std::format("{}.d", objPath)) > fs::last_write_time(objPath)) { - const Toolchain& toolchain = GetToolchain(); - if (toolchain.nvcc.empty()) { - jobs.Fail(std::format("cannot compile {}: {}", layout.Shown(cFile, ".cu"), toolchain.nvccError)); - break; - } - jobs.Add(std::format("Compiling {}", layout.Shown(cFile, ".cu")), [directory = object.parent_path(), command = std::format("{} {} -c -MD -MF {} -o {} -O3 -arch={}", ShellQuote(toolchain.nvcc.string()), ShellQuote(srcPath), ShellQuote(std::format("{}.d", objPath)), ShellQuote(objPath), ShellQuote(config.cudaArch))] { - fs::create_directories(directory); - return RunBuildCommand(command); + // Still .cu-mtime only: the header tracking the C and C++ paths get + // comes from asking the compiler for a depfile, and nvcc's -MD/-MF are + // untested here (no CUDA toolkit in CI), so a .cu that only sees a + // changed header does not rebuild yet. + if (!fs::exists(objPath) || (fs::exists(srcPath) && fs::last_write_time(srcPath) > fs::last_write_time(objPath))) { + threads.emplace_back([&cFile, &buildDir, &buildError, &buildCancelled]() { + Progress::Task task(std::format("Compiling {}.cu", cFile.filename().string())); + if (buildCancelled.load(std::memory_order_relaxed)) return; + + std::string result = RunBuildCommand(std::format("nvcc {}.cu -c -o {}_source.o -O3 -arch=sm_89", cFile.string(), (buildDir / cFile.filename()).string())); + if (result.empty()) return; + + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); + } }); } } @@ -1663,8 +994,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map seen; std::function forwardDepArtifacts = [&](Configuration* dep) { if (!seen.insert(dep).second) return; - fs::path depBinDir = dep->ProgramDir(); + fs::path depBinDir = dep->BinDir(); for (const Shader& shader : dep->shaders) { fs::path src = depBinDir / shader.OutputName(); if (!fs::exists(src)) continue; - place(outputDir / src.filename(), src); copyTree(src, outputDir / src.filename()); } for (const fs::path& additionalFile : dep->files) { fs::path src = depBinDir / additionalFile.filename(); if (!fs::exists(src)) continue; - place(outputDir / additionalFile.filename(), src); copyTree(src, outputDir / additionalFile.filename()); } for (const fs::path& asset : dep->assets) { @@ -1728,23 +1058,28 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map srcName = CompressedAssetName(asset); - if (!srcName) continue; - fs::path src = depBinDir / *srcName; + std::string ext = asset.extension().string(); + for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); + fs::path srcName = asset.filename(); + if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { + srcName.replace_extension(".ctex"); + } else if (ext == ".obj") { + srcName.replace_extension(".cmesh"); + } else { + continue; + } + fs::path src = depBinDir / srcName; if (!fs::exists(src)) continue; - place(outputDir / *srcName, src); - copyTree(src, outputDir / *srcName); + copyTree(src, outputDir / srcName); } for (Configuration* sub : dep->dependencies) forwardDepArtifacts(sub); }; for (Configuration* dep : config.dependencies) forwardDepArtifacts(dep); } catch (const fs::filesystem_error& e) { - jobs.Fail(e.what()); - jobs.Wait(); + for(std::thread& thread : threads) thread.join(); return {e.what(), false, {}}; } } @@ -1753,31 +1088,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map externalFloor) externalFloor = ext.latestArtifact; } - // What the interface and implementation sources declare and import, read - // only now: clang-scan-deps preprocesses each with the command it is - // compiled with, which is complete from here on, with the include paths - // of the dependencies and external dependencies just built, whose - // headers a source may include. Their modules, which the imports are - // looked up among, are known by now too, as each dependency's Build() - // has read its own sources. A Build() makes the modules and units of its - // own configuration alone: those of a dependency are its own Build()'s - // to make, and the builds of other configurations built on it may be - // reading them at this moment. - // - // A dependency's modules are those of the build the pass ran for its - // directory, which need not have been the dependency's own: OncePerPass - // builds a directory once, for whichever configuration of it asked - // first, and a configuration it did not build has no modules (see - // BuildResult::built). Every dependency has its result in the pass by - // now. - const BuiltConfiguration builtIn = [&depResults, &depMutex](const Configuration& dependency) -> const Configuration& { - std::shared_future built; - { - std::lock_guard lock(depMutex); - if (const auto found = depResults.find(dependency.PcmDir()); found != depResults.end()) built = found->second; - } - if (built.valid() && built.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { - // A build that threw has failed this one already, before it got - // here, and is taken as the dependency's own. - try { - if (const Configuration* ran = built.get().built) return *ran; - } catch (...) { - } - } - return dependency; - }; - if (std::string error = ReadSources(config, command, layout, builtIn); !error.empty()) { - jobs.Fail(std::move(error)); - return {jobs.Wait(), false, {}}; - } - buildResult.built = &config; - // Both before any .cppm or .cpp of the configuration is compiled, and - // only now that its modules are known. Its C and CUDA sources, whose - // compiles started beside the dependencies' builds, may have been. - if (std::string duplicate = DuplicateModuleError(config, builtIn); !duplicate.empty()) { - jobs.Fail(std::move(duplicate)); - return {jobs.Wait(), false, {}}; - } - if (std::string cycle = ImportCycleError(config); !cycle.empty()) { - jobs.Fail(std::move(cycle)); - return {jobs.Wait(), false, {}}; - } - - // Check every interface before scheduling any of them. Schedule() puts a - // unit after the stale units it imports and reads their needsRecompiling - // for that, which a unit's own Check need not have set: a partition's - // returns at the first stale import it finds. + // Check every interface before compiling any of them. Module::Compile waits + // on the `compiled` flag of each sibling module it imports, and that flag is + // set either by a Compile that runs or by the Check that decides none is + // needed — so a Check still pending while another module's thread is already + // waiting would block on a flag nothing goes on to raise. + std::vector staleInterfaces; for(std::unique_ptr& interface : config.interfaces) { if(interface->Check(pcmDir, externalFloor)) { + staleInterfaces.push_back(interface.get()); buildResult.repack = true; } - objects.push_back(buildDir / std::format("{}.o", interface->path.filename().string())); + files += std::format(" {}/{}.o", buildDir.string(), interface->path.filename().string()); for(std::unique_ptr& part : interface->partitions) { - objects.push_back(buildDir / std::format("{}.o", part->path.filename().string())); + files += std::format(" {}/{}.o", buildDir.string(), part->path.filename().string()); } } - // Every interface, and with each its partitions, not only the stale - // ones: a unit whose BMI is up to date can still be without the object - // made from it, which Schedule() then adds alone. No repack for that - // here: the link below runs again for an object newer than its output. - for(std::unique_ptr& interface : config.interfaces) { - interface->Schedule(jobs, command, pcmDir, buildDir); + for(Module* mod : staleInterfaces) { + threads.emplace_back([mod, &command, &pcmDir, &buildDir, &buildCancelled, &buildError]() { + Progress::Task task(std::format("Compiling interface {}", mod->path.filename().string())); + try { + mod->Compile(command, pcmDir, buildDir, buildCancelled, buildError); + } catch (const std::exception& e) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::format("Module::Compile threw: {}", e.what()); + } + } + }); } for(Implementation& implementation : config.implementations) { - const fs::path object = layout.Object(implementation.path, ".cpp"); - if(implementation.Check(object, pcmDir, externalFloor)) { + if(implementation.Check(buildDir, pcmDir, externalFloor)) { buildResult.repack = true; - implementation.Schedule(jobs, command, pcmDir, buildDir, object, layout.Shown(implementation.path, ".cpp")); + Implementation* impl = &implementation; + threads.emplace_back([impl, &command, &buildDir, &buildCancelled, &buildError]() { + Progress::Task task(std::format("Compiling {}.cpp", impl->path.filename().string())); + try { + impl->Compile(command, buildDir, buildCancelled, buildError); + } catch (const std::exception& e) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::format("Implementation::Compile threw: {}", e.what()); + } + } + }); } - objects.push_back(object); + files += std::format(" {}/{}_impl.o", buildDir.string(), implementation.path.filename().string()); } - if (std::string failed = jobs.Wait(); !failed.empty()) { - return {std::move(failed), false, {}}; + for(std::thread& thread : threads) { + thread.join(); + } + + if(buildCancelled.load()) { + return {buildError, false, {}}; } std::string linkExtras; for(const std::string& flag : buildResult.libs) { linkExtras += std::format(" {}", flag); } - for (const std::string& lib : buildResult.runtimeLibs) linkExtras += std::format(" {}", lib); - // The program loads its shared dependencies from where they were built, - // the external cache among them. ExternalOutputs leaves the mingw target - // without any: PE resolves DLLs another way. A Flatpak has none of those - // directories once installed, and nothing outside its own /app and the - // runtime: WriteFlatpak copies what the program needs from them into - // files/lib, beside files/bin, and that is the one place it looks, under - // -r as well as installed. - const bool flatpak = config.ResolvedPackaging() == Packaging::Flatpak; - if (flatpak) { - linkExtras += " -Wl,-rpath,'$ORIGIN/../lib'"; - } else { - for (const std::string& dir : buildResult.runPaths) linkExtras += RunPathFlags(dir); - } // Link-only LTO/section flags (empty in Debug and for wasm). Every exe/lib // link below ends with linkExtras, so this reaches them all; the static-lib // archive path uses ar instead and is handled separately. linkExtras += ltoLinkFlags; // Host links use the toolchain's own libc++. When the toolchain lives // outside /usr (a bundled one) the binary needs an rpath to find - // libc++.so.1 at run time; a Flatpak finds the copy in its files/lib - // through the run path above instead, as it does anything else this -L - // lets the link take from that directory. mingw links libstdc++ and - // every sysroot build (wasm included) brings its own libc++. - if (config.target != "x86_64-w64-mingw32" && config.ResolvedSysroot(GetToolchain()).empty()) { - linkExtras += flatpak ? GetToolchain().LibcxxSearchFlags() : GetToolchain().LibcxxLinkFlags(); + // libc++.so.1 at run time. mingw links libstdc++ and every sysroot build + // (wasm included) brings its own libc++. + if (config.target != "x86_64-w64-mingw32" && config.sysroot.empty()) { + linkExtras += GetToolchain().LibcxxLinkFlags(); } // mingw uses libstdc++; C++26 std::print/format extras live in libstdc++exp. // libstdc++ on mingw uses winpthreads for std::atomic_wait / @@ -1973,54 +1242,58 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map consumerMtime) { + auto t = fs::last_write_time(obj, ec); + return !ec && t > consumerMtime; + }; + for (const std::unique_ptr& iface : config.interfaces) { + if (objNewer(buildDir / std::format("{}.o", iface->path.filename().string()))) { buildResult.repack = true; break; } + bool partHit = false; + for (const std::unique_ptr& part : iface->partitions) { + if (objNewer(buildDir / std::format("{}.o", part->path.filename().string()))) { + partHit = true; + break; + } + } + if (partHit) { buildResult.repack = true; break; } + } + if (!buildResult.repack) { + for (const Implementation& impl : config.implementations) { + if (objNewer(buildDir / std::format("{}_impl.o", impl.path.filename().string()))) { + buildResult.repack = true; + break; + } + } + } + // C and CUDA objects are archive members too, and their compile + // loop above is the only thing that knows it rebuilt one — it + // sets no repack flag, so without this a .c edit recompiled the + // object and then linked nothing. + if (!buildResult.repack) { + auto sourceObjNewer = [&](const std::vector& sources) { + for (const fs::path& source : sources) { + if (objNewer(buildDir / std::format("{}_source.o", source.filename().string()))) return true; + } + return false; + }; + if (sourceObjNewer(config.cFiles) || sourceObjNewer(config.cuda)) { + buildResult.repack = true; + } } } } } - // The step reads its objects from a file the command names with @, one - // to a line: a response file, which clang and llvm-ar both take - // arguments from. Written into the command itself, the objects' paths - // made it longer with every source, and the command is one argument to - // the shell that runs it, which Linux holds to 32 pages, 131,072 bytes - // where a page is 4 KiB. With objects whose paths came to more, no - // shell started and the build ended with "popen() failed!". - const fs::path objectList = buildDir / std::format("{}.objects", config.outputName); - std::string listed; - for (const fs::path& object : objects) listed += std::format("{}\n", ResponseFileArgument(object.string())); - const std::string files = std::format(" {}", ShellQuote(std::format("@{}", objectList.string()))); - - // The archive step of a static library, as it writes the archive to - // `archive`. ThinLTO emits LLVM bitcode objects; plain `ar` writes an - // archive index that omits their symbols, so a consumer's lld link - // can't pull the needed members. llvm-ar writes a bitcode-aware index - // and handles plain ELF and COFF objects just as well, so every build - // uses it. - const auto archiveCommand = [&](const fs::path& archive) { - return std::format("{} rcs {} {}", GetToolchain().llvmAr.string(), archive.string(), files); - }; - - // The command the link step runs, or the archive step with the archive - // itself for the name it is written under (see where the step runs), - // kept beside the objects once the step has succeeded. A different one - // relinks even with no object newer than the output: a link flag - // changed in project.cpp, or a dependency's library moved, as an - // ExternalDependency's does when its options change and it is built - // into a new cache directory. + // The exact command the link (or archive) step runs, kept beside the + // objects once it has succeeded. A different one relinks even with no + // object newer than the output: a link flag changed in project.cpp, or a + // dependency's library moved, as an ExternalDependency's does when its + // options change and it is built into a new cache directory. std::string linkCommand; if (config.type == ConfigurationType::Executable) { if (config.target.starts_with("wasm32")) { @@ -2029,7 +1302,12 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map(recorded)), std::istreambuf_iterator()); - if (previous != linked) buildResult.repack = true; + if (previous != linkCommand) buildResult.repack = true; } if(buildResult.repack) { @@ -2090,60 +1362,9 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map graph; @@ -2199,7 +1406,7 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_mapwasmVariantFlags = variant.flags; - fs::path variantBin = config.ProgramDir(); + fs::path variantBin = config.BinDir(); std::unordered_map> variantDeps; std::mutex variantMutex; @@ -2226,354 +1433,6 @@ BuildResult Crafter::Build(Configuration& config, std::unordered_map roots; - // For each of `roots`, the others it is built after, by their places - // in `roots`. - std::vector> waitsFor; - // The places in `roots`, each after the ones it waits for. - std::vector order; - // Whether a wasm executable that declares variants is among them or - // among what they are built on, so that they are built one after the - // other. - bool rewrites = false; - // Why the list is not built, as BuildAll returns it; empty when it - // is. - std::string refused; - }; - - BuildPlan PlanBuild(std::span configurations) { - BuildPlan plan; - for (Configuration* cfg : configurations) { - if (!std::ranges::contains(plan.roots, cfg)) plan.roots.push_back(cfg); - } - const std::span roots = plan.roots; - const std::size_t count = roots.size(); - const auto directory = [](const Configuration& cfg) { return fs::absolute(cfg.PcmDir()).lexically_normal(); }; - - // The directory each of them is built into, and the directories of - // everything it is built on. A wasm executable that declares - // variants builds everything it is built on once more for each of - // them, and says which variant by rewriting those configurations in - // place (the end of Build()). A library that two of these share - // would change under whichever is still building its baseline, so - // with such a configuration anywhere among them they are built one - // after the other. - std::vector builtInto(count); - std::vector> builtOn(count); - for (std::size_t index = 0; index < count; ++index) { - builtInto[index] = directory(*roots[index]); - std::unordered_set seen = { roots[index] }; - std::vector pending = { roots[index] }; - while (!pending.empty()) { - const Configuration& cfg = *pending.back(); - pending.pop_back(); - if (cfg.type == ConfigurationType::Executable && cfg.target.starts_with("wasm32") && !cfg.wasmVariants.empty()) plan.rewrites = true; - for (const Configuration* dep : cfg.dependencies) { - if (!seen.insert(dep).second) continue; - builtOn[index].insert(directory(*dep)); - pending.push_back(dep); - } - } - } - - plan.refused = SameDirectoryError(roots); - if (!plan.refused.empty()) return plan; - - // One that another is built on, which is to say that something the - // other is built on is built into its directory, is built before - // the other starts: the other then finds it built, in the record of - // the pass, instead of building it a second time beside this build - // of it. - plan.waitsFor.resize(count); - for (std::size_t index = 0; index < count; ++index) { - for (std::size_t other = 0; other < count; ++other) { - if (other != index && builtOn[index].contains(builtInto[other])) plan.waitsFor[index].push_back(other); - } - } - // One that is itself built on something of its own directory makes - // two builds for that directory, its dependency's and its own, and - // the record of the pass holds one result for a directory: another - // of them that looks there for what it is built on would be given - // one of the two, whichever it had asked for. By itself, or with no - // other of them built on that directory, it builds as it does for - // Build(). - for (std::size_t index = 0; index < count; ++index) { - if (!builtOn[index].contains(builtInto[index])) continue; - for (std::size_t other = 0; other < count; ++other) { - if (other == index || !builtOn[other].contains(builtInto[index])) continue; - plan.refused = std::format("{} and a configuration it is built on would both be built into {}, where {} looks for what it is built on: give each a name of its own", roots[index]->name, builtInto[index].string(), roots[other]->name); - return plan; - } - } - std::vector ordered(count, false); - for (bool placed = true; placed;) { - placed = false; - for (std::size_t index = 0; index < count; ++index) { - if (ordered[index] || !std::ranges::all_of(plan.waitsFor[index], [&](std::size_t other) { return ordered[other]; })) continue; - ordered[index] = true; - plan.order.push_back(index); - placed = true; - } - } - if (plan.order.size() != count) { - std::string names; - for (std::size_t index = 0; index < count; ++index) { - if (ordered[index]) continue; - if (!names.empty()) names += ", "; - names += roots[index]->name; - } - plan.refused = std::format("{}: each of these is built on something that would be built into the directory of another of them, so none of them can be built first", names); - } - return plan; - } -} - -std::string Crafter::BuildAll(std::span configurations, std::unordered_map>& depResults, std::mutex& depMutex) { - const BuildPlan plan = PlanBuild(configurations); - if (!plan.refused.empty()) return plan.refused; - const std::size_t count = plan.roots.size(); - - std::vector errors(count); - const auto build = [&](std::size_t index) { - Configuration& cfg = *plan.roots[index]; - // By Build() itself, as a project's one configuration always was, - // and only then put into the record of the pass, where a - // configuration that depends on this one looks for it, with what - // the build returned or threw. Recorded while it is still being - // built, it would be handed to a dependency of its own that is - // built into the same directory, which would wait for the build - // that is waiting for it. Such a dependency has left its own result - // under that directory by now, and this one's takes its place: no - // other of them is built on that directory, or the set was refused. - std::promise built; - try { - BuildResult result = Build(cfg, depResults, depMutex); - errors[index] = result.result; - built.set_value(std::move(result)); - } catch (const std::exception& e) { - errors[index] = std::format("build of {} threw: {}", cfg.name, e.what()); - built.set_exception(std::current_exception()); - } catch (...) { - errors[index] = std::format("build of {} threw something that is not a std::exception", cfg.name); - built.set_exception(std::current_exception()); - } - const std::lock_guard lock(depMutex); - depResults.insert_or_assign(cfg.PcmDir(), built.get_future().share()); - }; - - if (plan.rewrites) { - for (const std::size_t index : plan.order) build(index); - } else { - std::vector> finishes(count); - std::vector> finished; - finished.reserve(count); - for (std::promise& finish : finishes) finished.push_back(finish.get_future().share()); - const auto buildInTurn = [&](std::size_t index) { - for (const std::size_t other : plan.waitsFor[index]) finished[other].wait(); - build(index); - finishes[index].set_value(); - }; - // The first on this thread, so a project of one configuration is - // built where it always was. - std::vector others; - others.reserve(count); - for (std::size_t index = 1; index < count; ++index) others.emplace_back(buildInTurn, index); - if (count > 0) buildInTurn(0); - } - - std::string failed; - for (auto error = errors.begin(); error != errors.end(); ++error) { - if (error->empty() || std::ranges::contains(errors.begin(), error, *error)) continue; - if (!failed.empty()) failed += '\n'; - failed += *error; - } - return failed; -} - -namespace { - FlatpakExport ExportOf(const Configuration& config) { - FlatpakExport app; - app.files = fs::absolute(config.BinDir() / "files").lexically_normal(); - app.appId = AppIdOf(config); - app.work = fs::absolute(FlatpakAppDir(config)).lexically_normal(); - app.command = ExpectedOutput(config).filename().string(); - app.runtime = config.flatpak.runtime; - app.arch = GetToolchain().flatpakArch; - app.branch = GetToolchain().flatpakBranch; - app.permissions = PermissionsOf(config); - for (const fs::path& module : config.flatpak.modules) app.modules.push_back(fs::absolute(module).lexically_normal()); - return app; - } - - // Why `verb` cannot export `config`, from the loaded Configuration and - // the host alone, so that Run() refuses before anything is built; empty - // when it can. - std::string ExportRefusal(const Configuration& config, std::string_view verb) { - if (config.ResolvedPackaging() != Packaging::Flatpak) { - return std::format("crafter-build {}: {} is not packaged as a Flatpak; set cfg.packaging = Packaging::Flatpak in project.cpp, or, where it calls ApplyStandardArgs, pass --packaging=flatpak", verb, config.name); - } - if (const std::string why = HostFlatpakUnavailable(config.path); !why.empty()) return std::format("crafter-build {}: {}", verb, why); - return ""; - } - - // ExportRefusal, or a build that is not there to export. - std::string CannotExport(const Configuration& config, std::string_view verb) { - if (const std::string refused = ExportRefusal(config, verb); !refused.empty()) return refused; - if (!fs::exists(ExpectedOutput(config))) return std::format("crafter-build {}: {} is not built yet", verb, config.name); - return ""; - } - - // The names of `configurations`, as a message lists them. - std::string NamesOf(std::span configurations) { - std::string names; - for (const Configuration* cfg : configurations) { - if (!names.empty()) names += ", "; - names += cfg->name; - } - return names; - } - - // What install or bundle exports of the configurations a project file - // returns: the only one, or of several the one packaged as a Flatpak. - struct ExportChoice { - // Null when none of several is packaged, or more than one is. - const Configuration* config = nullptr; - // Why `config` cannot be exported, or why there is none; empty when - // it can be. - std::string refused; - }; - - ExportChoice ChooseExport(std::span configurations, std::string_view verb) { - std::vector packaged; - for (const Configuration* cfg : configurations) { - if (cfg->ResolvedPackaging() == Packaging::Flatpak) packaged.push_back(cfg); - } - if (packaged.size() > 1) { - return { nullptr, std::format("crafter-build {0}: {1} are each packaged as a Flatpak, and {0} exports one app", verb, NamesOf(packaged)) }; - } - if (packaged.empty() && configurations.size() > 1) { - return { nullptr, std::format("crafter-build {0}: none of {1} is packaged as a Flatpak; set cfg.packaging = Packaging::Flatpak in project.cpp on the one to {0}", verb, NamesOf(configurations)) }; - } - const Configuration* const config = packaged.empty() ? configurations.front() : packaged.front(); - return { config, ExportRefusal(*config, verb) }; - } - - // A repo's path as the file:// URL of a remote: percent-encoded, since - // `remote-modify --url=` stores what it is given as it is. - std::string FileUrl(const fs::path& path) { - std::string url = "file://"; - for (const char c : path.string()) { - const bool plain = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || std::string_view("/-._~").contains(c); - if (plain) url.push_back(c); - else url += std::format("%{:02X}", static_cast(c)); - } - return url; - } - - // Every variant of an app exports into its one repo, FlatpakAppDir(), so - // another crafter-build exporting a variant between an export and the - // install or bundle made from it would have that install or bundle the - // other's program. Both hold this lock from the export on. - FileLock AppDirLock(const fs::path& work) { - std::error_code ec; - fs::create_directories(work, ec); - return FileLock(work / ".lock"); - } -} - -std::string Crafter::InstallFlatpakApp(const Configuration& config) { - if (const std::string refused = CannotExport(config, "install"); !refused.empty()) return refused; - const FlatpakExport app = ExportOf(config); - const FileLock lock = AppDirLock(app.work); - if (const std::string failed = ExportFlatpak(app); !failed.empty()) return failed; - // A remote of its own, re-pointed at this project's repo each time: the - // same app-id built in another checkout would otherwise go on updating - // from that one's, and --if-not-exists would keep it silently. - const std::string remote = std::format("crafter-build-{}", app.appId); - const std::string url = ShellQuote(FileUrl(app.work / "repo")); - // The remote is the installation's, shared by every checkout that builds - // this app-id, so re-pointing it and installing from it hold a lock of - // their own: another checkout's install would otherwise re-point it - // between this one's remote-modify and install. Every crafter-build that - // installs there has to take the same lock, native or in the Flatpak, - // with whatever XDG_CACHE_HOME it runs, so the lock follows the - // installation and not the cache: a private one, FLATPAK_USER_DIR, holds - // it, one lock for all of them where the sandbox shares that directory - // with the host, and for the user's own, which flatpak hides from - // crafter-build's sandbox behind a tmpfs of the sandbox's own, it is in - // ~/.cache by HOME. - const fs::path base = [] { - if (const char* userDir = std::getenv("FLATPAK_USER_DIR"); userDir && *userDir) return fs::path(userDir); - if (const char* home = std::getenv("HOME"); home && *home) return fs::path(home) / ".cache"; - return fs::path(); - }(); - if (base.empty()) return "crafter-build install: neither FLATPAK_USER_DIR nor HOME is set, and the lock on the user's remote is found by one of them"; - const fs::path locks = base / "crafter.build" / "flatpak-remotes"; - std::error_code ec; - fs::create_directories(locks, ec); - const FileLock remoteLock(locks / std::format("{}.lock", remote)); - if (RunHostFlatpak(std::format("remote-add --user --if-not-exists --no-gpg-verify {} {}", ShellQuote(remote), url)) != 0) return std::format("crafter-build install: adding the remote {} failed", remote); - if (RunHostFlatpak(std::format("remote-modify --user --url={} {}", url, ShellQuote(remote))) != 0) return std::format("crafter-build install: pointing the remote {} at the repo failed", remote); - if (RunHostFlatpak(std::format("install --user --noninteractive --or-update {} {}", ShellQuote(remote), ShellQuote(app.appId))) != 0) return std::format("crafter-build install: installing {} failed", app.appId); - if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) { - std::println("\nInstalled {0}: `flatpak run {0}` starts it.\nThe remote {1} points into build/, which `crafter-build clean` deletes; remove both with\n flatpak uninstall --user {0}\n flatpak remote-delete --user {1}", app.appId, remote); - } - return ""; -} - -namespace { - // CUDA sources compiled for native, code for the GPUs of the machine - // that builds and no PTX, in `config`'s program: its own, and those of - // every library Build hands its link, which it does through an - // executable dependency too. That executable's own objects are run by - // path and stay out of the bundle; `linked` is false for them alone, - // and it follows from a configuration's type, so `seen` holds either - // way. - bool HasNativeCuda(const Configuration& config, std::unordered_set& seen, bool linked = true) { - if (!seen.insert(&config).second) return false; - if (linked && !config.cuda.empty() && config.cudaArch == "native") return true; - return std::ranges::any_of(config.dependencies, [&seen](const Configuration* dep) { return HasNativeCuda(*dep, seen, dep->type != ConfigurationType::Executable); }); - } -} - -std::string Crafter::BundleFlatpakApp(const Configuration& config) { - if (const std::string refused = CannotExport(config, "bundle"); !refused.empty()) return refused; - const FlatpakExport app = ExportOf(config); - const FileLock lock = AppDirLock(app.work); - if (const std::string failed = ExportFlatpak(app); !failed.empty()) return failed; - const fs::path bundle = fs::absolute(FlatpakBundlePath(config)).lexically_normal(); - // The runtime's repository goes into the bundle, so a machine without - // the Platform fetches it from Flathub on install instead of refusing. - if (RunHostFlatpak(std::format("build-bundle --runtime-repo=https://dl.flathub.org/repo/flathub.flatpakrepo {} {} {}", ShellQuote((app.work / "repo").string()), ShellQuote(bundle.string()), ShellQuote(app.appId))) != 0) { - return std::format("crafter-build bundle: flatpak build-bundle failed for {}", app.appId); - } - if (config.march == "native") { - Progress::Diagnostic(std::format("{} is built with -march=native, so it may stop with SIGILL on a CPU older than this one; for others, build with --march=x86-64-v3", bundle.string())); - } - if (std::unordered_set seen; HasNativeCuda(config, seen)) { - Progress::Diagnostic(std::format("{} holds CUDA code built with --cuda-arch=native, for this machine's GPUs and with no PTX, so it may not run on another machine's GPU; for others, build with --cuda-arch=all-major", bundle.string())); - } - if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("\nBundled {} as {}: `flatpak install --user {}` installs it.", app.appId, bundle.string(), bundle.filename().string()); - return ""; -} - -fs::path Crafter::FlatpakBundlePath(const Configuration& config) { - return config.BinDir().parent_path() / std::format("{}.flatpak", config.VariantId()); -} - -fs::path Crafter::FlatpakAppDir(const Configuration& config) { - return config.BuildDir().parent_path() / "flatpak-apps" / AppIdOf(config); -} - -std::string Crafter::FlatpakManifest(const Configuration& config) { - return FlatpakManifestText(ExportOf(config)); -} - void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) { fs::path runtimeDir = GetCrafterBuildHome() / "wasi-runtime"; fs::path runtimeJs = runtimeDir / "runtime.js"; @@ -2631,10 +1490,21 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) { // wasm side. Basename collisions across subdirs aren't supported on // the wasi runtime today; if two assets share a basename, the last // one preloaded wins. Avoid collisions in the source tree. - // The name Build() writes an asset under, by the rule its own copy uses, - // so the manifest cannot list a file the build never wrote. - auto compressedRel = [](const fs::path& rel) -> fs::path { - if (const std::optional name = CompressedAssetName(rel)) return rel.parent_path() / *name; + auto compressedExt = [](const fs::path& src) -> std::optional { + std::string ext = src.extension().string(); + for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); + if (ext == ".png" || ext == ".tga" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp") { + return std::string(".ctex"); + } + if (ext == ".obj") return std::string(".cmesh"); + return std::nullopt; + }; + auto compressedRel = [&](const fs::path& rel) -> fs::path { + if (auto ext = compressedExt(rel)) { + fs::path out = rel; + out.replace_extension(*ext); + return out; + } return rel; }; std::vector assetFiles; @@ -2656,9 +1526,8 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) { } // cfg.assets — mirror the bin-dir layout the build emits: a // directory entry becomes /, single - // files land flat at the bin root. What CompressedAssetName maps - // is compressed in place; everything else passes through under its - // original name. + // files land flat at the bin root. .png/.obj are compressed in + // place; everything else passes through under its original name. for (const fs::path& a : c->assets) { if (fs::is_directory(a)) { const fs::path topName = a.filename(); @@ -2699,6 +1568,14 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) { // driver); the baseline maps to outputName.wasm. Even with no declared // variants we still emit a one-entry manifest so the runtime has a // single, uniform code path. + auto jsonEscape = [](std::string_view s) { + std::string out; + for (char c : s) { + if (c == '"' || c == '\\') out += '\\'; + out += c; + } + return out; + }; fs::path variantsPath = htmlOutDir / "variants.json"; { std::ofstream v(variantsPath); @@ -2712,12 +1589,12 @@ void Crafter::EnableWasiBrowserRuntime(Configuration& cfg) { : std::format("{}.{}.wasm", cfg.outputName, label); std::vector probes = ownProbes; probes.insert(probes.end(), WasmBaselineProbes.begin(), WasmBaselineProbes.end()); - v << "{\"label\":" << JsonQuote(label) - << ",\"url\":" << JsonQuote(url) + v << "{\"label\":\"" << jsonEscape(label) << "\"" + << ",\"url\":\"" << jsonEscape(url) << "\"" << ",\"probes\":["; for (std::size_t i = 0; i < probes.size(); ++i) { if (i) v << ","; - v << JsonQuote(probes[i]); + v << "\"" << jsonEscape(probes[i]) << "\""; } v << "]}"; }; @@ -2805,9 +1682,6 @@ ArgQuery Crafter::ApplyStandardArgs(Configuration& cfg, std::span Crafter::CleanProject(const fs::path& projectFile) { static void PrintVersion() { std::println("crafter-build {}", CrafterBuildVersion()); const Toolchain& tc = GetToolchain(); - // nvcc only when there is one: most projects have no CUDA sources, and the - // build that has some says where it looked. The static runtime beside it - // as well, which says whether one is linked. Found apart from the - // compiler, so printed whether or not that was resolved. - const auto cuda = [&tc]() { - if (!tc.nvcc.empty()) std::println("nvcc {}", tc.nvcc.string()); - if (!tc.cudaRuntime.empty()) std::println("cudart {}", tc.cudaRuntime.string()); - }; if (!tc.error.empty()) { std::println("compiler: {}", tc.error); - cuda(); return; } std::println("compiler {} ({})", tc.clangVersion, tc.clangxx.string()); @@ -2894,7 +1751,6 @@ static void PrintVersion() { std::println("libc++ {}{}", LibcxxVersionString(tc.libcxxVersion), also.empty() ? std::string() : std::format(" (std module sources for sysroots also for{})", also.substr(1))); } std::println("host {}", tc.hostTriple); - cuda(); } static void PrintHelp(std::string_view argv0) { @@ -2905,8 +1761,6 @@ R"(Usage: {0} lint [lint-options] [globs...] Run the project's lint rules over its sources {0} format [format-options] [globs...] Apply the project's transform rules (rewrites files) {0} run [script [args...]] Run a script the project defines, or list them - {0} install [options] Build a project packaged as a Flatpak and install it for this user - {0} bundle [options] Build a project packaged as a Flatpak into a .flatpak file {0} clean Delete the project's bin/ and build/ trees {0} help | -h | --help Show this help {0} --version Print the version and the compiler in use @@ -2914,24 +1768,11 @@ R"(Usage: Loads ./project.cpp (override with --project=), compiles it to a shared object, and invokes its CrafterBuildProject() to obtain a Configuration that drives the build. Outputs land at bin/--/, intermediates -at build/--/. A project of several configurations -defines CrafterBuildConfigurations() instead, which returns them all and gets -the same args, and every one of them is built. - -A build runs at most as many of its steps at once as the machine has hardware -threads: the compiles of its sources, its shaders and assets, and its links -and archives, counted together for the project and the dependencies it is -built on. An external dependency's CMake build is not among them, nor are the -tests `test` runs. A step counts as one whatever threads it starts for itself, -as a link and the compression of an asset do. +at build/--/. Build options: - -r Run the produced executable after a successful build: - one for the host in its own directory, a wasm32 one - under wasmtime or wasmer, or one built for the - browser served over HTTP from its directory. - Libraries cannot be run, and of several - configurations one has to be the only executable. + -r Run the produced executable after a successful build + (host targets only; libraries cannot be run). -v, --verbose Verbose progress output. -q, --quiet Suppress progress output. --project= Path to the project file (default: ./project.cpp). @@ -2942,20 +1783,11 @@ Build options: Test options (after the `test` subcommand): --list Enumerate matching tests without running them. - --jobs= Tests built and run at once (default: one per - hardware thread). The steps of their builds share - the one limit a build has. + --jobs= Parallel job count (default: hardware_concurrency). --timeout= Per-test timeout override. --runner= Override the test runner for this run. Specs: local cmd: (e.g. cmd:wine) - --compositor= The headless Wayland compositor each test that sets - Test::wayland runs with, a command run through sh - that listens on a wayland- socket in the - XDG_RUNTIME_DIR it is given. Default: weston - --backend=headless --renderer=gl --no-config - --idle-time=0. `host` runs those tests on this - session's own display. --target= Filter to tests whose cfg.target matches. Default: sweep across every distinct target declared by the project's tests plus the host triple. @@ -3002,88 +1834,47 @@ Run (after the `run` subcommand): crafter-build was started from. Only the scripts of the project being run are available, never a dependency's. -Install and bundle (after the `install` or `bundle` subcommand): - Both need the project's executable packaged as a Flatpak (cfg.packaging = - Packaging::Flatpak, or --packaging=flatpak where project.cpp calls - ApplyStandardArgs), and refuse before building when it is not, or when the - host's flatpak cannot be reached. They build the project, have the host's - flatpak build-finish make the app of its files/ with the permissions, which - it refuses where it does not know one, and export it into the project's - repo, build/flatpak-apps//repo, with flatpak build-export, or have - flatpak-builder do both when cfg.flatpak.modules names modules. install - installs it for this user from the remote crafter-build-; bundle - writes it into a single .flatpak file beside its bin directory, for - `flatpak install --user`, naming Flathub's repository for the runtime. Both - run the host's flatpak, inside crafter-build's Flatpak through - flatpak-spawn --host, and refuse a project whose bin/ and build/ the host - does not see where crafter-build does, as in the sandbox's own /tmp, /var, - /usr, /etc and /app, which they ask the host before building. Of several - configurations they export the one that is packaged as a Flatpak, and - refuse before building when none is, or more than one. - Clean (after the `clean` subcommand): Removes bin/ and build/ next to the project file. Does not load project.cpp, so it works when the project itself no longer compiles. Every target, variant - and dependency artifact under those trees goes with it, and so does the repo - an app from `install` is installed from: remove the app and its remote - first, as install says how. + and dependency artifact under those trees goes with it. AGENTS.md: - When an AGENTS.template.md sits beside the project file, a build and a test - run write AGENTS.md from it, with a section holding the AGENTS.consumer.md - each dependency ships beside its project.cpp, and only when the text changes. - Commit the template and keep AGENTS.md out of version control. An AGENTS.md - no build wrote is never replaced, and without a template AGENTS.md is left - alone. cfg.dependencyNotes picks the dependencies: Transitive (the default), - Direct, or None. + When an AGENTS.md sits beside the project file, a build and a test run keep a + section in it holding the AGENTS.consumer.md each dependency ships beside its + project.cpp, and write the file only when that section changes. An AGENTS.md + is never created. cfg.dependencyNotes picks the dependencies: Transitive (the + default), Direct, or None, which removes the section. Project args: - Any flag not consumed above is forwarded verbatim to the project file's - entry point as part of its `args` span. Project-specific flags (e.g. - --target=, custom feature toggles) live there. ApplyStandardArgs reads - --debug, --target=, --march=, --mtune=, --cuda-arch=, --sysroot=, --lib, - --shared and --packaging=none|flatpak, the last for the project - crafter-build was pointed at only. Flags it does not itself interpret are - folded into the variant hash, so switching one lands in its own bin/ and - build/ directory instead of overwriting the other setting's. + Any flag not consumed above is forwarded verbatim to CrafterBuildProject as + part of its `args` span. Project-specific flags (e.g. --target=, custom + feature toggles) live there. Flags ApplyStandardArgs does not itself + interpret are folded into the variant hash, so switching one lands in its own + bin/ and build/ directory instead of overwriting the other setting's. Environment: CRAFTER_BUILD_MARCH Override -march (default: native). CRAFTER_BUILD_MTUNE Override -mtune (default: native). - CRAFTER_BUILD_CUDA_ARCH Override nvcc's -arch for cfg.cuda - (default: native). - CUDA_PATH CUDA toolkit whose bin/nvcc compiles - cfg.cuda. Default: /opt/cuda, then - /usr/local/cuda (in the Flatpak, the - host's), then nvcc on PATH. CRAFTER_BUILD_RUNNER_ Default test runner for a target triple. Replace '-' and '.' with '_' in the triple. CLI --runner= overrides this. - CRAFTER_BUILD_COMPOSITOR Default headless Wayland compositor for - tests that set Test::wayland, as for - --compositor=, which overrides it. CRAFTER_BUILD_LLVM_DIR LLVM prefix to use instead of a toolchain installed beside crafter-build or PATH. CRAFTER_BUILD_LIBCXX_DIR libc++ install to compile and link against instead of the compiler's own. CRAFTER_BUILD_LIBCLANG Exact libclang to load for lint. CRAFTER_BUILD_WASI_SYSROOT WASI sysroot for wasm32 targets. - CRAFTER_BUILD_FLATPAK_INFO File to read the runtime a Flatpak is - packaged for from, in place of - /.flatpak-info; for tests. CRAFTER_MINGW_DIR mingw-w64 prefix (holding x86_64-w64-mingw32/ - and lib/gcc/). Default: the mingw gcc on - PATH; in the Flatpak, the host's /usr when - it has mingw-w64. Of a prefix that holds a - Linux system too, such as /usr, clang sees - only those directories. + and lib/gcc/), passed as --sysroot. Default: + the mingw gcc on PATH; in the Flatpak, the + host's /usr when it has mingw-w64. CRAFTER_BUILD_HOME Directory holding the module sources. Exit status: 0 success / all non-skipped tests passed / lint clean / format applied 1 build failure, one or more tests failed, lint findings, no rules defined, - format write errors, `format --check` found files that would change, or - `install` or `bundle` was refused or its export, install or bundle failed + format write errors, or `format --check` found files that would change `run` exits with the status its script returned, and with 1 when there is no such script, when the script throws, or when it returns a value outside 0..255 )", argv0); @@ -3097,12 +1888,11 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { std::vector projectArgs; projectArgs.reserve(argc); - // What this invocation does: the first verb on the command line, a - // build without one. A verb word after it is an operand of that one - // (`test lint` runs the tests that match "lint", `run test` runs the - // script called test) or a project arg, never a second verb. - enum class Verb { Build, Test, Lint, Format, Clean, Run, Install, Bundle }; - Verb verb = Verb::Build; + bool runTests = false; + bool runLint = false; + bool runFormat = false; + bool runClean = false; + bool runScript = false; bool runAfterBuild = false; RunTestsOptions testOpts; RunLintOptions lintOpts; @@ -3122,15 +1912,15 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { // variant hash and so the directory the project builds into. if (scriptOpts.named) { scriptOpts.args.emplace_back(arg); - } else if (verb == Verb::Run && (operandsOnly || !arg.starts_with("-"))) { + } else if (runScript && (operandsOnly || !arg.starts_with("-"))) { // The first word after `run`, even one that is a verb // elsewhere. Options before it keep their usual meaning. scriptOpts.name = arg; scriptOpts.named = true; } else if (operandsOnly) { - if (verb == Verb::Test) { + if (runTests) { testOpts.globs.emplace_back(arg); - } else if (verb == Verb::Lint || verb == Verb::Format) { + } else if (runLint || runFormat) { lintOpts.globs.emplace_back(arg); } else { projectArgs.push_back(arg); @@ -3147,27 +1937,23 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { // project.cpp as an unknown argument. PrintVersion(); return 0; - } else if (arg == "-h" || arg == "--help" || (verb != Verb::Test && verb != Verb::Lint && verb != Verb::Format && arg == "help")) { + } else if (arg == "-h" || arg == "--help" || (!runTests && !runLint && !runFormat && arg == "help")) { PrintHelp(argv0); return 0; - } else if (verb == Verb::Build && arg == "test") { - verb = Verb::Test; - } else if (verb == Verb::Build && arg == "lint") { - verb = Verb::Lint; - } else if (verb == Verb::Build && arg == "clean") { - verb = Verb::Clean; - } else if (verb == Verb::Build && arg == "format") { - verb = Verb::Format; + } else if (!runLint && !runFormat && !runClean && arg == "test") { + runTests = true; + } else if (!runTests && !runFormat && !runClean && arg == "lint") { + runLint = true; + } else if (!runTests && !runLint && !runFormat && arg == "clean") { + runClean = true; + } else if (!runTests && !runLint && !runClean && arg == "format") { + runFormat = true; lintOpts.mode = LintMode::Apply; - } else if (verb == Verb::Build && arg == "run") { - verb = Verb::Run; - } else if (verb == Verb::Build && arg == "install") { - verb = Verb::Install; - } else if (verb == Verb::Build && arg == "bundle") { - verb = Verb::Bundle; - } else if (verb == Verb::Run && arg == "--list") { + } else if (!runTests && !runLint && !runFormat && !runClean && arg == "run") { + runScript = true; + } else if (runScript && arg == "--list") { scriptOpts.listOnly = true; - } else if (verb == Verb::Format && arg == "--check") { + } else if (runFormat && arg == "--check") { lintOpts.mode = LintMode::Check; } else if (arg == "-r") { runAfterBuild = true; @@ -3177,23 +1963,21 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { verbosity = Progress::Verbosity::Quiet; } else if (arg.starts_with("--project=")) { projectFile = arg.substr(std::string_view("--project=").size()); - } else if (verb == Verb::Test && arg.starts_with("--jobs=")) { + } else if (runTests && arg.starts_with("--jobs=")) { testOpts.jobs = std::stoi(std::string(arg.substr(std::string_view("--jobs=").size()))); - } else if (verb == Verb::Test && arg.starts_with("--timeout=")) { + } else if (runTests && arg.starts_with("--timeout=")) { testOpts.timeoutOverride = std::chrono::seconds(std::stoi(std::string(arg.substr(std::string_view("--timeout=").size())))); - } else if (verb == Verb::Test && arg == "--list") { + } else if (runTests && arg == "--list") { testOpts.listOnly = true; - } else if (verb == Verb::Test && arg.starts_with("--runner=")) { + } else if (runTests && arg.starts_with("--runner=")) { testOpts.runnerOverride = std::string(arg.substr(std::string_view("--runner=").size())); - } else if (verb == Verb::Test && arg.starts_with("--compositor=")) { - testOpts.compositorOverride = std::string(arg.substr(std::string_view("--compositor=").size())); - } else if (verb == Verb::Test && !arg.starts_with("-")) { + } else if (runTests && !arg.starts_with("-")) { testOpts.globs.emplace_back(arg); - } else if ((verb == Verb::Lint || verb == Verb::Format) && arg == "--list") { + } else if ((runLint || runFormat) && arg == "--list") { lintOpts.listOnly = true; - } else if ((verb == Verb::Lint || verb == Verb::Format) && arg == "--no-ast") { + } else if ((runLint || runFormat) && arg == "--no-ast") { lintOpts.noAst = true; - } else if ((verb == Verb::Lint || verb == Verb::Format) && !arg.starts_with("-")) { + } else if ((runLint || runFormat) && !arg.starts_with("-")) { lintOpts.globs.emplace_back(arg); } else { projectArgs.push_back(arg); @@ -3216,8 +2000,8 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { return 1; } - // Ahead of the load on purpose — see CleanProject. - if (verb == Verb::Clean) { + // Ahead of LoadProject on purpose — see CleanProject. + if (runClean) { std::vector removed = CleanProject(projectFile); if (removed.empty()) { std::println("Nothing to clean"); @@ -3227,111 +2011,57 @@ std::int32_t Crafter::Run(std::int32_t argc, char** argv) { return 0; } - // What the project file describes: one configuration, or several - // that are all built. - const std::vector configurations = LoadConfigurations(projectFile, projectArgs); - // The ones the file made itself: every one but those that another - // project's file returned to GitProject or LocalProject. One of - // those, returned here in turn, is built with the rest, and -r, - // install and bundle count it among them, but its tests and its - // scripts stay that project's: `run` still reaches no script but - // those of the project crafter-build was pointed at. - std::vector own; - for (Configuration* cfg : configurations) { - if (!LoadedProjectOf(*cfg)) own.push_back(cfg); - } - SetParentProject(configurations); + Configuration config = LoadProject(projectFile, projectArgs); + SetParentProject(&config); - if (verb == Verb::Run) { + if (runScript) { scriptOpts.projectFile = fs::absolute(projectFile).lexically_normal(); - return RunScript(own, scriptOpts); + return RunScript(config, scriptOpts); } - if (verb == Verb::Lint || verb == Verb::Format) { + if (runLint || runFormat) { // lexically_normal: fs::absolute keeps a "./" component, which // would leak into displayed paths and the project-root derivation. lintOpts.projectFile = fs::absolute(projectFile).lexically_normal(); - LintSummary lintSummary = RunLint(configurations, lintOpts); - if (verb == Verb::Lint) return lintSummary.Clean() ? 0 : 1; + LintSummary lintSummary = RunLint(config, lintOpts); + if (!runFormat) return lintSummary.Clean() ? 0 : 1; if (lintSummary.noRulesDefined || lintSummary.errors > 0) return 1; // Apply: formatting files is success (gofmt convention). // Check: a would-change file is the CI failure signal. return lintOpts.mode == LintMode::Check && !lintSummary.changedFiles.empty() ? 1 : 0; } - // What install and bundle cannot export they refuse here, before - // anything is built: a project that is not packaged as a Flatpak, or - // a host flatpak out of reach, is known from the loaded project, and - // so is which of several configurations is the app. - ExportChoice exported; - if (verb == Verb::Install || verb == Verb::Bundle) { - exported = ChooseExport(configurations, verb == Verb::Install ? "install" : "bundle"); - if (!exported.refused.empty()) { - std::println(std::cerr, "{}", exported.refused); - return 1; - } - } - - // What the list itself rules out is refused here too, before any of - // it is built and before AGENTS.md is written: two returned - // configurations of one directory for every verb that builds, and - // for the verbs that build the configurations themselves whatever - // else BuildAll refuses a list for. `test` builds its tests with - // Build() and never comes to BuildAll, which makes these refusals - // again for whoever calls it. - if (const std::string refused = verb == Verb::Test ? SameDirectoryError(configurations) : PlanBuild(configurations).refused; !refused.empty()) { - Progress::Clear(); - std::println(std::cerr, "{}", refused); - return 1; - } - // Builds and test runs only: lint and `format --check` promise to // write nothing, `format` rewrites the project's sources and nothing // else, `run` is for chores and `test --list` only lists. Here, // before compiling, because loading has just fetched every // dependency, so the notes are current, and an agent fixing a build // that fails needs them. - if (!testOpts.listOnly) UpdateAgentsMd(configurations, projectFile); + if (!testOpts.listOnly) UpdateAgentsMd(config, projectFile); - if (verb == Verb::Test) { - TestSummary summary = RunTests(own, testOpts, projectArgs); + if (runTests) { + TestSummary summary = RunTests(config, testOpts, projectArgs); return summary.AllPassed() ? 0 : 1; } std::unordered_map> depResults; std::mutex depMutex; - if (const std::string failed = BuildAll(configurations, depResults, depMutex); !failed.empty()) { + BuildResult result = Build(config, depResults, depMutex); + + if (!result.result.empty()) { Progress::Clear(); - std::println(std::cerr, "{}", failed); + std::println(std::cerr, "{}", result.result); return 1; } Progress::Finalize(); - if (verb == Verb::Install || verb == Verb::Bundle) { - const std::string failed = verb == Verb::Install ? InstallFlatpakApp(*exported.config) : BundleFlatpakApp(*exported.config); - if (failed.empty()) return 0; - std::println(std::cerr, "{}", failed); - return 1; - } - if (runAfterBuild) { - std::vector executables; - for (const Configuration* cfg : configurations) { - if (cfg->type == ConfigurationType::Executable) executables.push_back(cfg); - } - if (executables.empty()) { + if (config.type != ConfigurationType::Executable) { std::println(std::cerr, "-r: cannot run a library"); return 1; } - // Everything is built by now, as without -r. Which one to run - // would be a guess. - if (executables.size() > 1) { - std::println(std::cerr, "-r: {} are executables, and -r runs one", NamesOf(executables)); - return 1; - } - const Configuration& config = *executables.front(); - fs::path dir = config.ProgramDir(); + fs::path dir = config.BinDir(); fs::path artifact = fs::absolute(ExpectedOutput(config)); fs::path absDir = fs::absolute(dir); diff --git a/implementations/Crafter.Build-External.cpp b/implementations/Crafter.Build-External.cpp index 8469828..9faf8dc 100644 --- a/implementations/Crafter.Build-External.cpp +++ b/implementations/Crafter.Build-External.cpp @@ -149,7 +149,7 @@ std::string BuildInjectedCMakeFlags(const fs::path& cmakeBuildDir, std::string_v // The libstdc++ and the mingw-w64 install the project's own compiles // use (GetBaseCommand). out += " -DCMAKE_CXX_FLAGS=-stdlib=libstdc++"; - if (const fs::path& sysroot = MingwSysroot(); !sysroot.empty()) out += std::format(" -DCMAKE_SYSROOT={}", ShellQuote(sysroot.string())); + if (!tc.mingwSysroot.empty()) out += std::format(" -DCMAKE_SYSROOT={}", ShellQuote(tc.mingwSysroot.string())); } fs::path absBuildDir = fs::absolute(cmakeBuildDir); out += std::format(" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY={}", ShellQuote(absBuildDir.string())); @@ -179,19 +179,6 @@ std::string ConfigureCMake(const fs::path& cloneDir, const fs::path& cmakeBuildD if (!needsConfigure) return ""; - // A build directory configured with other inputs starts over instead of - // being reconfigured. CMake reconfigures in place without recompiling - // what an old compiler or --sysroot compiled (the Makefiles generator - // writes --sysroot into build.make, which make does not compare) and - // keeps the check results the old configure cached. A mingw external - // built against the host's /usr as the sysroot (issue #43) kept its - // objects reading __libc_single_threaded after the fix that way. The - // directory keeps its name, which projects point generated headers at. - if (fs::exists(cmakeBuildDir / "CMakeCache.txt")) { - std::error_code ec; - fs::remove_all(cmakeBuildDir, ec); - if (ec) return std::format("cannot clear {} for a fresh configure: {}", cmakeBuildDir.string(), ec.message()); - } if (!fs::exists(cmakeBuildDir)) fs::create_directories(cmakeBuildDir); std::string cmd = std::format("cmake -S {} -B {}{}", ShellQuote(fs::absolute(cloneDir).string()), ShellQuote(fs::absolute(cmakeBuildDir).string()), injected); @@ -293,21 +280,21 @@ ExternalBuildResult Crafter::ExternalOutputs(const ExternalDependency& dep, std: const fs::path cmakeBuildDir = ExternalBuildDir(dep, target); if (dep.builder != ExternalBuilder::CMake || cmakeBuildDir.empty()) return result; - // Each search path is both a -L (link time) and a run path (the - // loader's), so the program picks its shared dependencies up from the - // cache without any LD_LIBRARY_PATH gymnastics; static ones (.a) need - // the run path not at all and are not hurt by it. The PE/COFF target - // (mingw) resolves DLLs through PATH or the program's own directory - // rather than a run path, and lld warns if it is given one. + // Each search path gets both a -L (link-time) and a -Wl,-rpath + // (runtime-loader). The rpath stays embedded in the produced + // binary so it picks up shared deps from the cache without any + // LD_LIBRARY_PATH gymnastics. Static deps (.a) ignore the rpath + // harmlessly. The PE/COFF target (mingw) resolves DLLs via PATH or + // adjacency rather than rpath, so lld warns if we pass it. const bool isPe = target == "x86_64-w64-mingw32"; std::string buildDirAbs = fs::absolute(cmakeBuildDir).string(); result.linkFlags.push_back(std::format("-L{}", buildDirAbs)); - if (!isPe) result.runPaths.push_back(buildDirAbs); + if (!isPe) result.linkFlags.push_back(std::format("-Wl,-rpath,{}", buildDirAbs)); for (const fs::path& libDir : dep.libDirs) { fs::path full = libDir.is_absolute() ? libDir : cmakeBuildDir / libDir; std::string fullAbs = fs::absolute(full).string(); result.linkFlags.push_back(std::format("-L{}", fullAbs)); - if (!isPe) result.runPaths.push_back(fullAbs); + if (!isPe) result.linkFlags.push_back(std::format("-Wl,-rpath,{}", fullAbs)); } for (const std::string& lib : dep.libs) { result.linkFlags.push_back(std::format("-l{}", lib)); @@ -336,33 +323,29 @@ ExternalBuildResult Crafter::ExternalOutputs(const ExternalDependency& dep, std: namespace { std::mutex ProjectCacheMutex; - // What each project file loaded here returned, in the file's order, by - // spec and args. An entry is never changed or removed once it is in. - std::unordered_map> ProjectCache; - // Keyed by the Configurations ProjectCache holds, which live as long as - // the process does (see LoadConfigurations), so the pointers never - // dangle. Guarded by ProjectCacheMutex as well. + std::unordered_map> ProjectCache; + // Keyed by the Configurations ProjectCache owns, which live as long as + // the process does, so the pointers never dangle. Guarded by + // ProjectCacheMutex as well. std::unordered_map LoadedProjects; - // The configurations a loaded project keeps to itself, with the project: - // what the configurations its file returned led to when the file was - // loaded and the file did not return. A configuration leads to what it - // is built on and to the configurations of its tests, and each of those - // leads on in the same way. Taken down at that moment, since a consumer - // may add to the `dependencies` of a configuration it was given, and - // what it adds is its own. Guarded by ProjectCacheMutex as well. - std::unordered_map KeptConfigurations; - // What the cache holds under `fullHash`, or nullptr. - const std::vector* CachedProject(const std::string& fullHash) { - const std::lock_guard lock(ProjectCacheMutex); - const auto it = ProjectCache.find(fullHash); - return it == ProjectCache.end() ? nullptr : &it->second; - } - - // cfg.path and every other relative path collection of `cfg`, made - // absolute against `depRoot`, so Build() can run from any cwd without - // misresolving them. - void RebaseOnto(Configuration& cfg, const fs::path& depRoot) { + // Run the dep's project.cpp from its own directory so its relative paths + // (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep + // root, then rebase cfg.path and all other relative path collections to + // absolute so Build() can run from any cwd without misresolving them. + // The mutex is NOT held across LoadProject — the dep may itself call + // GitProject/LocalProject, and a non-recursive lock would deadlock. + Configuration LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span args) { + fs::path savedCwd = fs::current_path(); + Configuration cfg; + fs::current_path(depRoot); + try { + cfg = LoadProject(projectPath, args); + } catch (...) { + fs::current_path(savedCwd); + throw; + } + fs::current_path(savedCwd); cfg.path = fs::absolute(depRoot / cfg.path).lexically_normal(); auto abs = [&](const fs::path& p) -> fs::path { return p.is_absolute() ? p : fs::absolute(depRoot / p).lexically_normal(); @@ -372,91 +355,22 @@ namespace { for (fs::path& p : cfg.files) p = abs(p); for (fs::path& p : cfg.buildFiles) p = abs(p); for (Shader& s : cfg.shaders) s.path = abs(s.path); - // A dependency that packages its own executable as a Flatpak names - // the files it is installed with as it names its cfg.files. An - // empty one is none, and stays empty. - if (!cfg.flatpak.desktopFile.empty()) cfg.flatpak.desktopFile = abs(cfg.flatpak.desktopFile); - if (!cfg.flatpak.metainfo.empty()) cfg.flatpak.metainfo = abs(cfg.flatpak.metainfo); - for (fs::path& p : cfg.flatpak.icons) p = abs(p); - for (fs::path& p : cfg.flatpak.modules) p = abs(p); - for (auto& entry : cfg.flatpak.share) { - if (!entry.source.empty()) entry.source = abs(entry.source); - } + return cfg; } - // Run the dep's project.cpp from its own directory so its relative paths - // (cfg.path = "./", interfaces/, lib/, ...) resolve against the dep - // root, then rebase every configuration it returns onto that root. - // The mutex is NOT held across the load — the dep may itself call - // GitProject/LocalProject, and a non-recursive lock would deadlock. - std::vector LoadProjectFromRoot(const fs::path& projectPath, const fs::path& depRoot, std::span args) { - fs::path savedCwd = fs::current_path(); - std::vector configurations; - fs::current_path(depRoot); - try { - configurations = LoadConfigurations(projectPath, args); - } catch (...) { - fs::current_path(savedCwd); - throw; - } - fs::current_path(savedCwd); - for (Configuration* cfg : configurations) { - // One the file loaded from another project file and returns - // itself was rebased onto that project's root when it was - // loaded, and other consumers may be reading it by now. - if (!LoadedProjectOf(*cfg)) RebaseOnto(*cfg, depRoot); - } - return configurations; - } - - // Into ProjectCache under `fullHash`, with `loaded` recorded beside each - // configuration that is not another project's already, and beside what - // those are built on and the file kept to itself. When another thread - // stored the same spec first, what it stored wins. - const std::vector& StoreProject(std::string fullHash, std::vector configurations, const LoadedProject& loaded) { - const std::lock_guard lock(ProjectCacheMutex); + // Into ProjectCache under `fullHash`, with `loaded` recorded beside it. + // When another thread stored the same spec first, its Configuration + // wins and `cfg` is dropped. + Configuration* StoreProject(std::string fullHash, Configuration cfg, LoadedProject loaded) { + std::lock_guard lock(ProjectCacheMutex); if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { - return it->second; + return it->second.get(); } - // What this file returned, and then what each of those leads to: - // what it is built on and the configurations of its tests. One that - // another project's file returned is that project's, and so is what - // is found from there. - std::vector pending; - const auto leadsTo = [&pending](const Configuration& cfg) { - pending.insert(pending.end(), cfg.dependencies.begin(), cfg.dependencies.end()); - for (const Test& test : cfg.tests) pending.push_back(&test.config); - }; - for (const Configuration* cfg : configurations) { - if (LoadedProjects.try_emplace(cfg, loaded).second) leadsTo(*cfg); - } - while (!pending.empty()) { - const Configuration* kept = pending.back(); - pending.pop_back(); - if (!kept || LoadedProjects.contains(kept) || !KeptConfigurations.try_emplace(kept, loaded).second) continue; - leadsTo(*kept); - } - return ProjectCache.emplace(std::move(fullHash), std::move(configurations)).first->second; - } - - // The one of `configurations` a spec asks for by `name`: the first for - // an empty name. `what` names the spec in the error for a name that none - // has, or that two have. - Configuration* PickConfiguration(std::span configurations, std::string_view name, std::string_view what) { - if (name.empty()) return configurations.front(); - Configuration* picked = nullptr; - for (Configuration* cfg : configurations) { - if (cfg->name != name) continue; - if (picked) throw std::runtime_error(std::format("{}: two of its configurations are named '{}', so the name picks neither", what, name)); - picked = cfg; - } - if (picked) return picked; - std::string names; - for (const Configuration* cfg : configurations) { - if (!names.empty()) names += ", "; - names += cfg->name; - } - throw std::runtime_error(std::format("{}: no configuration named '{}' (it has: {})", what, name, names)); + auto stored = std::make_unique(std::move(cfg)); + Configuration* ptr = stored.get(); + ProjectCache.emplace(std::move(fullHash), std::move(stored)); + LoadedProjects.emplace(ptr, std::move(loaded)); + return ptr; } // `url` as it names a repository: without user info, which is where a @@ -478,11 +392,10 @@ namespace { Configuration* Crafter::GitProject(const GitProjectSpec& spec) { // Two hashes: the clone is shared across specs that point at the same // source revision (forwarded args don't change what gets cloned, just - // how the dep's project.cpp interprets them at runtime), while what the - // file returned is keyed by the args as well, so each (args) - // permutation gets its own Configuration objects, and host tooling ones - // apart from the target's even for the same args. Which configuration - // the spec picks is in neither: it chooses among what one load returned. + // how the dep's project.cpp interprets them at runtime), while the + // in-memory Configuration is keyed by the full spec so each (args) + // permutation gets its own Configuration object, and host tooling one + // apart from the target's even for the same args. std::string srcKey = std::format("git|{}|{}|{}|{}", spec.source.url, spec.source.branch, spec.source.commit, spec.projectFile.string()); std::string srcHash = std::format("{:016x}", std::hash{}(srcKey)); @@ -492,10 +405,12 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) { fullKey += a; } std::string fullHash = std::format("{:016x}", std::hash{}(fullKey)); - const std::string what = std::format("GitProject({})", spec.source.url); - if (const std::vector* cached = CachedProject(fullHash)) { - return PickConfiguration(*cached, spec.configuration, what); + { + std::lock_guard lock(ProjectCacheMutex); + if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { + return it->second.get(); + } } std::string name = DeriveName(spec.source); @@ -523,15 +438,15 @@ Configuration* Crafter::GitProject(const GitProjectSpec& spec) { } std::vector argViews(spec.args.begin(), spec.args.end()); - std::vector configurations = LoadProjectFromRoot(projectPath, cloneDir, argViews); + Configuration cfg = LoadProjectFromRoot(projectPath, cloneDir, argViews); const fs::path projectInRepo = spec.projectFile.lexically_normal(); const fs::path below = projectInRepo.parent_path(); - return PickConfiguration(StoreProject(std::move(fullHash), std::move(configurations), { + return StoreProject(std::move(fullHash), std::move(cfg), { .projectFile = projectPath.lexically_normal(), .name = below.empty() ? name : std::format("{}/{}", name, below.generic_string()), .identity = std::format("git|{}|{}", RepositoryKey(spec.source.url), projectInRepo.generic_string()), - }), spec.configuration, what); + }); } fs::path Crafter::GitFetch(const GitSource& source) { @@ -574,21 +489,23 @@ Configuration* Crafter::LocalProject(const LocalProjectSpec& spec) { fullKey += a; } std::string fullHash = std::format("{:016x}", std::hash{}(fullKey)); - const std::string what = std::format("LocalProject({})", canonical.string()); - if (const std::vector* cached = CachedProject(fullHash)) { - return PickConfiguration(*cached, spec.configuration, what); + { + std::lock_guard lock(ProjectCacheMutex); + if (auto it = ProjectCache.find(fullHash); it != ProjectCache.end()) { + return it->second.get(); + } } fs::path depRoot = canonical.parent_path(); std::vector argViews(spec.args.begin(), spec.args.end()); - std::vector configurations = LoadProjectFromRoot(canonical, depRoot, argViews); + Configuration cfg = LoadProjectFromRoot(canonical, depRoot, argViews); - return PickConfiguration(StoreProject(std::move(fullHash), std::move(configurations), { + return StoreProject(std::move(fullHash), std::move(cfg), { .projectFile = canonical, .name = depRoot.filename().string(), .identity = std::format("local|{}", canonical.string()), - }), spec.configuration, what); + }); } std::optional Crafter::LoadedProjectOf(const Configuration& cfg) { @@ -596,9 +513,3 @@ std::optional Crafter::LoadedProjectOf(const Configuration& cfg) if (auto it = LoadedProjects.find(&cfg); it != LoadedProjects.end()) return it->second; return std::nullopt; } - -std::optional Crafter::KeptBy(const Configuration& cfg) { - const std::lock_guard lock(ProjectCacheMutex); - if (const auto it = KeptConfigurations.find(&cfg); it != KeptConfigurations.end()) return it->second; - return std::nullopt; -} diff --git a/implementations/Crafter.Build-Flatpak.cpp b/implementations/Crafter.Build-Flatpak.cpp deleted file mode 100644 index 00228ed..0000000 --- a/implementations/Crafter.Build-Flatpak.cpp +++ /dev/null @@ -1,583 +0,0 @@ -// SPDX-License-Identifier: LGPL-3.0-only -// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® - -module Crafter.Build:Flatpak_impl; -import :Flatpak; -import :Platform; -import :Progress; -import std; -namespace fs = std::filesystem; -using namespace Crafter; - -namespace { - // flatpak's own rule for the characters of a name's segments: a dash is - // allowed in the last segment only, a digit anywhere but first. - bool NameStart(char c, bool lastSegment) { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (lastSegment && c == '-'); - } - - bool NameChar(char c, bool lastSegment) { - return NameStart(c, lastSegment) || (c >= '0' && c <= '9'); - } - - std::string_view Trim(std::string_view s) { - while (!s.empty() && (s.front() == ' ' || s.front() == '\t' || s.front() == '\n' || s.front() == '\r')) s.remove_prefix(1); - while (!s.empty() && (s.back() == ' ' || s.back() == '\t' || s.back() == '\n' || s.back() == '\r')) s.remove_suffix(1); - return s; - } - - std::vector Split(std::string_view s, char separator) { - std::vector parts; - for (std::size_t begin = 0;;) { - const std::size_t end = s.find(separator, begin); - parts.push_back(s.substr(begin, end == std::string_view::npos ? std::string_view::npos : end - begin)); - if (end == std::string_view::npos) return parts; - begin = end + 1; - } - } - - // ---- the files ---- - - std::string ReadAll(const fs::path& path) { - std::ifstream in(path, std::ios::binary); - if (!in) throw std::runtime_error(std::format("could not read {}", path.string())); - return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); - } - - // Whether `b` is a regular file holding exactly what `a` does: by size, - // then a block at a time, so comparing costs the same memory whatever - // the files' size. Reading both whole held twice the largest file on - // every build that had nothing to copy, and failed where that did not - // fit. - bool SameContent(const fs::path& a, const fs::path& b) { - std::error_code ec; - if (!fs::is_regular_file(b, ec) || fs::is_symlink(b, ec)) return false; - if (fs::file_size(a) != fs::file_size(b, ec) || ec) return false; - std::ifstream left(a, std::ios::binary); - if (!left) throw std::runtime_error(std::format("could not read {}", a.string())); - std::ifstream right(b, std::ios::binary); - if (!right) return false; - constexpr std::size_t Block = 64 * 1024; - std::vector x(Block); - std::vector y(Block); - while (left && right) { - left.read(x.data(), static_cast(Block)); - right.read(y.data(), static_cast(Block)); - if (left.gcount() != right.gcount() || !std::equal(x.begin(), x.begin() + left.gcount(), y.begin())) return false; - } - return left.eof() && right.eof(); - } - - // Writes `content` to `path` unless the file already holds exactly that, - // so an unchanged build leaves its mtime alone. - void WriteIfDifferent(const fs::path& path, std::string_view content) { - std::error_code ec; - if (fs::is_regular_file(path, ec) && !fs::is_symlink(path, ec) && fs::file_size(path, ec) == content.size() && ReadAll(path) == content) return; - fs::create_directories(path.parent_path()); - fs::remove(path, ec); - std::ofstream out(path, std::ios::binary | std::ios::trunc); - out.write(content.data(), static_cast(content.size())); - if (!out) throw std::runtime_error(std::format("could not write {}", path.string())); - } - - // Makes `dir` hold exactly `wanted`, relative path to the file copied - // there, and nothing else: every other file goes, and the directories - // left empty. A copy is made only when its content differs, and anything - // in the way is replaced rather than written through, a link included. - // Returns the relative paths it copied. - std::set SyncOwned(const fs::path& dir, const std::map& wanted) { - std::set copied; - std::error_code ec; - if (fs::exists(dir, ec)) { - std::vector files; - std::vector dirs; - for (const fs::directory_entry& entry : fs::recursive_directory_iterator(dir)) { - if (entry.is_directory() && !entry.is_symlink()) dirs.push_back(entry.path()); - else if (!wanted.contains(entry.path().lexically_relative(dir))) files.push_back(entry.path()); - } - for (const fs::path& file : files) fs::remove(file); - // Deepest first, so a parent is empty by the time it is looked at. - std::ranges::sort(dirs, std::greater{}); - for (const fs::path& d : dirs) { - if (fs::is_empty(d)) fs::remove(d); - } - } - for (const auto& [relative, source] : wanted) { - const fs::path target = dir / relative; - if (!fs::exists(source)) throw std::runtime_error(std::format("{} does not exist", source.string())); - if (SameContent(source, target)) continue; - fs::create_directories(target.parent_path()); - if (fs::is_directory(target, ec) && !fs::is_symlink(target, ec)) fs::remove_all(target); - else fs::remove(target, ec); - fs::copy_file(source, target); - copied.insert(relative); - } - return copied; - } - - // Whether `path` is `ancestor` or lies inside it, element by element. - bool Within(const fs::path& path, const fs::path& ancestor) { - return std::mismatch(ancestor.begin(), ancestor.end(), path.begin(), path.end()).first == ancestor.end(); - } - - // Whether `outer` is `inner` or holds it, as written or where their - // links lead: a project whose bin/ is a link elsewhere holds its files/ - // as written, and not once the link is followed. - bool Holds(const fs::path& outer, const fs::path& inner) { - std::error_code ec; - if (Within(fs::absolute(inner, ec).lexically_normal(), fs::absolute(outer, ec).lexically_normal())) return true; - const fs::path realOuter = fs::weakly_canonical(outer, ec); - if (ec || realOuter.empty()) return false; - const fs::path realInner = fs::weakly_canonical(inner, ec); - if (ec || realInner.empty()) return false; - return Within(realInner, realOuter); - } - - // Adds `relative` to the files a directory is to hold, copied from - // `source`, unless that would put two files at one path, or a file where - // another needs a directory: one share entry over another, or two icons - // of one size. SyncOwned would otherwise copy whichever came last, or - // fail halfway with a filesystem error. - std::string Place(std::map& files, const fs::path& relative, const fs::path& source) { - if (auto it = files.find(relative); it != files.end()) { - return std::format("{} and {} both go to share/{}", it->second.string(), source.string(), relative.string()); - } - // What lies inside a path sorts right after it, element by element. - if (auto it = files.upper_bound(relative); it != files.end() && Within(it->first, relative)) { - return std::format("{} would make share/{} a file, where {} needs it to be a directory", source.string(), relative.string(), it->second.string()); - } - for (fs::path parent = relative.parent_path(); !parent.empty(); parent = parent.parent_path()) { - if (auto it = files.find(parent); it != files.end()) { - return std::format("{} needs share/{} to be a directory, where {} makes it a file", source.string(), parent.string(), it->second.string()); - } - } - files.emplace(relative, source); - return ""; - } - - // Where an icon goes under share/: an .svg as scalable, a .png in the - // directory of its own size, read from its header. - fs::path IconPath(const fs::path& icon, std::string_view appId) { - std::string ext = icon.extension().string(); - for (char& c : ext) c = static_cast(std::tolower(static_cast(c))); - if (ext == ".svg") return fs::path("icons") / "hicolor" / "scalable" / "apps" / std::format("{}.svg", appId); - if (ext != ".png") throw std::runtime_error(std::format("{}: an icon has to be an .svg or a .png", icon.string())); - const std::string header = ReadAll(icon).substr(0, 24); - if (header.size() < 24 || !header.starts_with("\x89PNG\r\n\x1a\n") || header.substr(12, 4) != "IHDR") { - throw std::runtime_error(std::format("{}: not a PNG file", icon.string())); - } - const auto bigEndian = [&](std::size_t at) { - std::uint32_t value = 0; - for (std::size_t i = 0; i < 4; ++i) value = (value << 8) | static_cast(header[at + i]); - return value; - }; - const std::uint32_t width = bigEndian(16); - const std::uint32_t height = bigEndian(20); - if (width != height) throw std::runtime_error(std::format("{}: an icon has to be square, this one is {}x{}", icon.string(), width, height)); - return fs::path("icons") / "hicolor" / std::format("{}x{}", width, width) / "apps" / std::format("{}.png", appId); - } - - // The Icon= of a desktop entry's [Desktop Entry] group; empty without one. - std::string DesktopIcon(const fs::path& desktopFile) { - bool inEntry = false; - for (const std::string_view line : Split(ReadAll(desktopFile), '\n')) { - const std::string_view t = Trim(line); - if (t.starts_with("[")) { - inEntry = t == "[Desktop Entry]"; - continue; - } - if (!inEntry) continue; - // The key and the value either side of the first '=', without - // the space the Desktop Entry spec lets surround it: `Icon = - // other` is Icon=other to desktop-file-validate and to flatpak. - const std::size_t eq = t.find('='); - if (eq != std::string_view::npos && Trim(t.substr(0, eq)) == "Icon") return std::string(Trim(t.substr(eq + 1))); - } - return ""; - } - - // ---- the libraries ---- - - // The libraries clang links into every C++ program it builds against its - // libc++. They are looked up one by one, never by searching the - // directory they are in: on a distribution that keeps libc++ in - // /usr/lib64, that directory holds libc.so.6 as well. - constexpr std::array LlvmRuntimeLibraries = {"libc++.so.1", "libc++abi.so.1", "libunwind.so.1"}; - - // The toolchain's own copy of `name`, as the link finds it; empty when - // clang has none (Arch's LLVM ships no libunwind.so.1). Asked once per - // name and process. - fs::path ToolchainLibrary(const fs::path& clangxx, std::string_view name) { - static std::mutex Mutex; - static std::map> Found; - std::lock_guard lock(Mutex); - if (auto it = Found.find(name); it != Found.end()) return it->second; - const CommandResult r = RunCommandChecked(std::format("{} -print-file-name={}", ShellQuote(clangxx.string()), name)); - // clang prints the bare name back when it has no such file. - fs::path path = Trim(r.output); - std::error_code ec; - if (r.exitCode != 0 || !path.is_absolute() || !fs::exists(path, ec)) path.clear(); - else path = path.lexically_normal(); - Found.emplace(std::string(name), path); - return path; - } - - std::vector NeededLibraries(const fs::path& readelf, const fs::path& file) { - const CommandResult r = RunCommandChecked(std::format("{} --needed-libs {}", ShellQuote(readelf.string()), ShellQuote(file.string()))); - if (r.exitCode != 0) { - throw std::runtime_error(std::format("{} could not read {}: {}", readelf.filename().string(), file.string(), Trim(r.output))); - } - std::vector names; - bool inList = false; - for (const std::string_view line : Split(r.output, '\n')) { - const std::string_view t = Trim(line); - if (!inList) { - inList = t.starts_with("NeededLibraries ["); - continue; - } - if (t == "]") break; - if (!t.empty()) names.emplace_back(t); - } - return names; - } - - // The files `program` needs that are not the runtime's, with what they - // need in turn: the LLVM runtime libraries, and any NEEDED name found in - // one of `dirs`, the first one holding it winning as for the loader. - std::vector Libraries(const FlatpakFiles& d, const fs::path& program) { - std::vector libraries; - std::set seen; - std::deque pending = {program}; - while (!pending.empty()) { - const fs::path file = std::move(pending.front()); - pending.pop_front(); - for (const std::string& name : NeededLibraries(d.readelf, file)) { - if (!seen.insert(name).second) continue; - fs::path found; - if (std::ranges::contains(LlvmRuntimeLibraries, std::string_view(name))) found = ToolchainLibrary(d.clangxx, name); - std::error_code ec; - for (const fs::path& dir : d.libraryDirs) { - if (!found.empty()) break; - if (fs::exists(dir / name, ec)) found = dir / name; - } - if (found.empty()) continue; - libraries.push_back(found); - pending.push_back(found); - } - } - return libraries; - } - - // ---- the record ---- - - // What a write placed, kept so the next one knows which files in - // files/bin were the build's. - struct Record { - std::set placed; - }; - - Record ReadRecord(const fs::path& file) { - Record record; - std::error_code ec; - if (!fs::exists(file, ec)) return record; - for (const std::string_view line : Split(ReadAll(file), '\n')) { - const std::size_t tab = line.find('\t'); - if (tab == std::string_view::npos) continue; - const std::string_view kind = line.substr(0, tab); - const std::string value(line.substr(tab + 1)); - if (kind == "placed") record.placed.insert(value); - } - return record; - } - - void WriteRecord(const fs::path& file, const Record& record) { - std::string text; - for (const std::string& name : record.placed) text += std::format("placed\t{}\n", name); - WriteIfDifferent(file, text); - } -} - -std::string Crafter::DefaultFlatpakAppId(std::string_view outputName) { - std::string segment; - for (const char c : outputName) segment.push_back(NameChar(c, true) ? c : '_'); - if (segment.empty() || !NameStart(segment.front(), true)) segment.insert(segment.begin(), '_'); - return std::format("local.crafterbuild.{}", segment); -} - -std::string Crafter::FlatpakAppIdError(std::string_view appId) { - if (appId.empty()) return "it is empty"; - if (appId.size() > 255) return "it is longer than 255 characters"; - const std::vector segments = Split(appId, '.'); - if (segments.size() < 3) return "it needs at least three segments, like org.example.App"; - for (std::size_t i = 0; i < segments.size(); ++i) { - const std::string_view segment = segments[i]; - const bool last = i + 1 == segments.size(); - if (segment.empty()) return "it has an empty segment"; - for (std::size_t j = 0; j < segment.size(); ++j) { - const char c = segment[j]; - if (j == 0 ? NameStart(c, last) : NameChar(c, last)) continue; - if (c == '-') return std::format("its segment '{}' has a '-', which only the last segment may have", segment); - if (j == 0 && c >= '0' && c <= '9') return std::format("its segment '{}' starts with a digit", segment); - return std::format("it holds '{}', which an application ID cannot", c); - } - } - return ""; -} - -void Crafter::RecordFlatpakPlaced(const fs::path& record, const std::set& names) { - try { - Record merged = ReadRecord(record); - const std::size_t before = merged.placed.size(); - merged.placed.insert(names.begin(), names.end()); - if (merged.placed.size() == before) return; - std::error_code ec; - fs::create_directories(record.parent_path(), ec); - WriteRecord(record, merged); - } catch (const std::exception&) { - // Not written: the next write takes those names for the program's, - // and says so, which is all a record that cannot be written costs. - } -} - -std::string Crafter::WriteFlatpakFiles(const FlatpakFiles& d) { - if (const std::string bad = FlatpakAppIdError(d.appId); !bad.empty()) { - return std::format("{} is not a Flatpak application ID: {}", d.appId, bad); - } - - try { - const fs::path files = d.root / "files"; - const fs::path program = files / "bin" / d.command; - const Record old = ReadRecord(d.record); - Record now; - - // Worked out on every write, from the program and what each library - // it carries needs in turn, which reads only their dynamic sections: - // a library replaced in place, as by a toolchain update, can need - // others, and only reading it again finds them. -r would not show a - // library missing, as crafter-build's sandbox has its own /app/lib on - // the loader's path; the installed app would not start. - std::map libraries; - for (const fs::path& library : Libraries(d, program)) libraries.emplace(library.filename(), library); - SyncOwned(files / "lib", libraries); - - std::map share; - const fs::path desktopEntry = fs::path("applications") / std::format("{}.desktop", d.appId); - if (!d.desktopFile.empty()) { - if (!fs::exists(d.desktopFile)) return std::format("{}: the desktop file {} does not exist", d.appId, d.desktopFile.string()); - if (const std::string clash = Place(share, desktopEntry, d.desktopFile); !clash.empty()) return std::format("{}: {}", d.appId, clash); - } - if (!d.metainfo.empty()) { - const fs::path metainfo = fs::path("metainfo") / std::format("{}.metainfo.xml", d.appId); - if (const std::string clash = Place(share, metainfo, d.metainfo); !clash.empty()) return std::format("{}: {}", d.appId, clash); - } - for (const fs::path& icon : d.icons) { - const fs::path relative = IconPath(icon, d.appId); - if (const std::string clash = Place(share, relative, icon); !clash.empty()) return std::format("{}: {}", d.appId, clash); - } - // A share entry's file goes where it says, unless the place is - // another file's (Place), a field's included. Whatever it is, a second - // desktop entry or the metainfo of an add-on, say, flatpak checks - // some of what it exports when install or bundle export the app, as - // for any app: an icon that is not a square image, or a D-Bus - // service that is not a key file, stops the export, the app's own - // desktop entry gets a warning where desktop-file-validate rejects it - // or its Icon= is not the app's, and a second desktop entry, a MIME - // package or metainfo goes as it is. The app's own desktop entry and - // the icons the field places are checked here too, at build time. - for (const FlatpakShareEntry& entry : d.share) { - fs::path target = entry.target.lexically_normal(); - if (!target.empty() && !target.has_filename()) target = target.parent_path(); - if (entry.target.is_absolute() || target.empty() || target == "." || *target.begin() == "..") { - return std::format("{}: the share target '{}' of {} has to be a path inside /app/share, relative to it", d.appId, entry.target.string(), entry.source.string()); - } - std::error_code ec; - if (fs::is_directory(entry.source, ec)) { - // A directory that holds what the build writes would be - // copied into itself, growing each time the app is built or - // exported: files/, where share/'s copies land, and the - // app's directory, where install and bundle put another copy - // of files/ and the exported app; the project's own directory - // holds both. One that lies in them is the build's own - // output, which the next build, install or bundle writes - // again, and no file of the project's. - for (const fs::path& output : {files, d.appDir}) { - if (output.empty()) continue; - if (Holds(entry.source, output)) { - return std::format("{}: {} holds {}, which the build writes, so a share entry would copy it into itself, growing each time the app is built or exported: name the files or directories in it instead", d.appId, entry.source.string(), output.string()); - } - if (Holds(output, entry.source)) { - return std::format("{}: {} lies in {}, which the build writes and writes again: a share entry names a file of the project's", d.appId, entry.source.string(), output.string()); - } - } - // Written with a trailing separator, "data/", the directory is - // taken without it, for each file's path inside it. - const fs::path dir = entry.source.has_filename() ? entry.source : entry.source.parent_path(); - for (const fs::directory_entry& file : fs::recursive_directory_iterator(dir)) { - if (!file.is_regular_file()) continue; - if (const std::string clash = Place(share, target / file.path().lexically_relative(dir), file.path()); !clash.empty()) return std::format("{}: {}", d.appId, clash); - } - } else if (fs::is_regular_file(entry.source, ec)) { - if (const std::string clash = Place(share, target, entry.source); !clash.empty()) return std::format("{}: {}", d.appId, clash); - } else { - return std::format("{}: {} does not exist, so it cannot go to share/{}", d.appId, entry.source.string(), target.string()); - } - } - // The app's desktop entry, applications/.desktop, whether - // cfg.flatpak.desktopFile or a share entry placed it: its Icon= has - // to be the app-id, which the app's icons are installed under. - const auto entry = share.find(desktopEntry); - if (entry != share.end()) { - if (const std::string icon = DesktopIcon(entry->second); !icon.empty() && icon != d.appId) { - return std::format("{}: its Icon= is {}, and has to be the app-id, {}, which its icons are installed as", entry->second.string(), icon, d.appId); - } - } - SyncOwned(files / "share", share); - // desktop-file-validate checks the entry here, where it was written, - // on every write that places one, not only one that copies it: a - // write that copied the entry and then failed would leave it - // unchecked for every write after. Where the tool exists: the Sdk has - // it, a development box may not. - if (entry != share.end() && RunCommandChecked("command -v desktop-file-validate").exitCode == 0) { - const CommandResult r = RunCommandChecked(std::format("desktop-file-validate {}", ShellQuote((files / "share" / desktopEntry).string()))); - if (r.exitCode != 0) { - std::error_code ec; - fs::remove(files / "share" / desktopEntry, ec); - return std::format("{} does not pass desktop-file-validate:\n{}", entry->second.string(), Trim(r.output)); - } - } - - // In files/bin, what an earlier write placed and this one does not - // is a stale build output, a removed cfg.files entry or a renamed - // shader. What neither placed the program wrote, under -r, since it - // runs there. - std::vector foreign; - for (const fs::directory_entry& entry : fs::directory_iterator(files / "bin")) { - const std::string name = entry.path().filename().string(); - if (d.programEntries.contains(name)) continue; - if (old.placed.contains(name)) fs::remove_all(entry.path()); - else foreign.push_back(name); - } - now.placed = d.programEntries; - if (!foreign.empty()) { - std::ranges::sort(foreign); - std::string names; - for (const std::string& name : foreign) names += std::format("{}{}", names.empty() ? "" : ", ", name); - Progress::Diagnostic(std::format("{}: {} in {} {} not put there by the build, so the program wrote {}, presumably under -r. {} with the app; installed, /app is read-only and a program cannot write there.", d.appId, names, (files / "bin").string(), foreign.size() == 1 ? "was" : "were", foreign.size() == 1 ? "it" : "them", foreign.size() == 1 ? "It ships" : "They ship")); - } - - WriteRecord(d.record, now); - } catch (const std::exception& e) { - return std::format("{}: {}", d.appId, e.what()); - } - return ""; -} - -std::string Crafter::FlatpakManifestText(const FlatpakExport& app) { - std::string finishArgs; - for (const FlatpakPermission& permission : app.permissions) { - finishArgs += std::format("{}\n {}", finishArgs.empty() ? "" : ",", JsonQuote(permission.argument)); - } - std::string modules; - for (const fs::path& module : app.modules) modules += std::format(" {},\n", JsonQuote(module.string())); - // The program's module is named apart from anything a project would - // call one of its own: module names are flatpak-builder's cache keys. - // "separate-locales": false keeps /app/share/locale in the app. By - // default flatpak-builder moves it into an .Locale extension, - // which an install fetches with the app but a bundle, which holds the - // app alone, leaves out. - return std::format( - "{{\n" - " \"app-id\": {},\n" - " \"runtime\": {},\n" - " \"runtime-version\": {},\n" - " \"sdk\": \"org.freedesktop.Sdk\",\n" - " \"command\": {},\n" - " \"separate-locales\": false,\n" - " \"finish-args\": [{}{}],\n" - " \"modules\": [\n" - "{}" - " {{\n" - " \"name\": \"crafter-build-program\",\n" - " \"buildsystem\": \"simple\",\n" - " \"build-commands\": [ \"cp -a . /app/\" ],\n" - " \"sources\": [ {{ \"type\": \"dir\", \"path\": {} }} ]\n" - " }}\n" - " ]\n" - "}}\n", - JsonQuote(app.appId), - app.runtime == FlatpakRuntime::Sdk ? "\"org.freedesktop.Sdk\"" : "\"org.freedesktop.Platform\"", - JsonQuote(app.branch), - JsonQuote(app.command), - finishArgs, finishArgs.empty() ? "" : "\n ", - modules, - JsonQuote(app.files.string())); -} - -namespace { - // `from` again at `to`: hard links where they can be made, copies where - // they cannot, links as links. flatpak build-finish and build-export - // read files/ and write nothing into it, so a link costs no copy of the - // app's data and leaves the build's files as they are. A link fails - // across filesystems, and on one that has none, vfat or exFAT on a USB - // stick say, with another error; whatever the reason, the copy is made - // instead, and a failure it shares, a full disk say, shows there. - void LinkOrCopyTree(const fs::path& from, const fs::path& to) { - try { - fs::copy(from, to, fs::copy_options::recursive | fs::copy_options::create_hard_links | fs::copy_options::copy_symlinks); - } catch (const fs::filesystem_error&) { - fs::remove_all(to); - fs::copy(from, to, fs::copy_options::recursive | fs::copy_options::copy_symlinks); - } - } -} - -std::string Crafter::ExportFlatpak(const FlatpakExport& app) { - // On every install and bundle: the build does not read them, and - // build-finish names only the argument it refuses, not the - // configuration it came from. - if (!app.permissions.empty()) { - std::string report = std::format("{} has these Flatpak permissions:", app.appId); - for (const FlatpakPermission& permission : app.permissions) report += std::format("\n {} (from {})", permission.argument, permission.source); - Progress::Diagnostic(report); - } - try { - fs::create_directories(app.work); - const fs::path repo = app.work / "repo"; - const fs::path buildDir = app.work / "build-dir"; - if (app.modules.empty()) { - // Made afresh each time: build-finish refuses a directory it - // finished before, and what a finish wrote, such as the export/ - // of a desktop entry the app no longer has, must not reach the - // next one. - fs::remove_all(buildDir); - fs::create_directories(buildDir); - const std::string_view runtime = app.runtime == FlatpakRuntime::Sdk ? "org.freedesktop.Sdk" : "org.freedesktop.Platform"; - WriteIfDifferent(buildDir / "metadata", std::format("[Application]\nname={}\nruntime={}/{}/{}\nsdk=org.freedesktop.Sdk/{}/{}\n", app.appId, runtime, app.arch, app.branch, app.arch, app.branch)); - LinkOrCopyTree(app.files, buildDir / "files"); - // The permissions before --command, so the program stays the - // app's command whatever they hold. - std::string finish = "build-finish"; - for (const FlatpakPermission& permission : app.permissions) finish += std::format(" {}", ShellQuote(permission.argument)); - finish += std::format(" --command={} {}", ShellQuote(app.command), ShellQuote(buildDir.string())); - if (RunHostFlatpak(finish) != 0) { - return std::format("{}: flatpak build-finish failed{}", app.appId, app.permissions.empty() ? "" : "; the permissions it was given are listed above, with where each came from"); - } - if (RunHostFlatpak(std::format("build-export {} {}", ShellQuote(repo.string()), ShellQuote(buildDir.string()))) != 0) { - return std::format("{}: flatpak build-export failed", app.appId); - } - return ""; - } - // Written only when it changes, so flatpak-builder sees the same - // manifest, and reuses what it built from it, until it does. - const fs::path manifest = app.work / std::format("{}.json", app.appId); - WriteIfDifferent(manifest, FlatpakManifestText(app)); - // --force-clean: the build directory is flatpak-builder's scratch, - // made again from its cache each time; the repo keeps what it - // exported. - const std::string arguments = std::format("--force-clean --state-dir={} --repo={} {} {}", ShellQuote((app.work / "state").string()), ShellQuote(repo.string()), ShellQuote(buildDir.string()), ShellQuote(manifest.string())); - if (RunHostFlatpakBuilder(arguments) != 0) return std::format("{}: flatpak-builder failed on {}", app.appId, manifest.string()); - } catch (const std::exception& e) { - return std::format("{}: {}", app.appId, e.what()); - } - return ""; -} diff --git a/implementations/Crafter.Build-Implementation.cpp b/implementations/Crafter.Build-Implementation.cpp index 84bbe18..ca39bac 100644 --- a/implementations/Crafter.Build-Implementation.cpp +++ b/implementations/Crafter.Build-Implementation.cpp @@ -5,7 +5,6 @@ module Crafter.Build:Implementation_impl; import std; import :Implementation; import :Interface; -import :Jobs; import :Platform; namespace fs = std::filesystem; @@ -13,12 +12,12 @@ namespace Crafter { Implementation::Implementation(fs::path&& path) : path(std::move(path)) { } - bool Implementation::Check(const fs::path& object, const fs::path& pcmDir, fs::file_time_type sourceFloor) const { - std::string objPath = object.string(); + bool Implementation::Check(const fs::path& buildDir, const fs::path& pcmDir, fs::file_time_type sourceFloor) const { + std::string objPath = std::format("{}_impl.o", (buildDir/path.filename()).string()); std::string cppPath = std::format("{}.cpp", path.string()); // The depfile clang wrote beside the object lists the headers this TU - // included when the object was compiled: inputs of the object as - // much as the source and the BMIs it imports. + // included; nothing else in the configuration knows about them, since + // the source scanner only reads `import` lines. if(!fs::exists(objPath) || std::max({fs::last_write_time(cppPath), sourceFloor, NewestPrerequisite(std::format("{}.d", objPath))}) >= fs::last_write_time(objPath)) { return true; } @@ -36,26 +35,28 @@ namespace Crafter { } return false; } - void Implementation::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, const fs::path& object, std::string_view shown) const { - std::vector after; + void Implementation::Compile(const std::string_view clang, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError) const { for(ModulePartition* dependency : partitionDependencies) { - if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); + if(!dependency->compiled.load()) { + dependency->compiled.wait(false); + } } for(Module* dependency : moduleDependencies) { - if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); + if(!dependency->compiled.load()) { + dependency->compiled.wait(false); + } + } + + if (buildCancelled.load(std::memory_order_relaxed)) { + return; + } + + // -MD leaves _impl.o.d beside the object for Check to read. + std::string result = RunBuildCommand(std::format("{0} {1}.cpp -c -MD -MF {2}_impl.o.d -o {2}_impl.o", clang, path.string(), (buildDir/path.filename()).string())); + + bool expected = false; + if(!result.empty() && buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); } - // -MD leaves _impl.o.d beside the object for Check to read, and - // -fmodule-file-deps puts the BMIs the unit imported in it with the - // headers. The driver adds that for --precompile only, so a std - // module rebuilt in place, for a mingw-w64 or libc++ update under - // the same compiler, left the objects importing it as they were, and - // the next build only relinked them. - // - // The job makes the directory of its object, which is one for the - // source's own directory (ObjectPath): the compiler makes none. - jobs.Add(std::format("Compiling {}", shown), [directory = object.parent_path(), command = std::format("{0} {1}.cpp -c -MD -MF {2}.d -fmodule-file-deps -o {2}", clang, path.string(), object.string())] { - fs::create_directories(directory); - return RunBuildCommand(command); - }, after); } } diff --git a/implementations/Crafter.Build-Interface.cpp b/implementations/Crafter.Build-Interface.cpp index 14636dd..2fb7b37 100644 --- a/implementations/Crafter.Build-Interface.cpp +++ b/implementations/Crafter.Build-Interface.cpp @@ -4,55 +4,11 @@ module Crafter.Build:Interface_impl; import std; import :Interface; -import :Jobs; import :Platform; namespace fs = std::filesystem; -namespace { - // The job that makes an interface unit's object from its BMI, once the - // jobs in `after` have finished. The command is put together here, as in - // the functions below, so the job owns the one it runs. - void AddObjectJob(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span after) { - jobs.Add(std::format("Compiling {}.cppm", path.filename().string()), [command = std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())] { - return Crafter::RunBuildCommand(command); - }, after); - } - - // The two compiler runs of a stale interface unit, as jobs of `jobs`: its - // BMI once the jobs in `after` have finished, then its object from that - // BMI. Returns the first, the one the units importing this one come - // after: the object is the link's alone to wait for. - Crafter::JobGroup::Job AddInterfaceJobs(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir, std::span after) { - // -MD records every header the preamble pulled in, next to the BMI as - // .pcm.d, so the next Check can see an edit to one of them. - const Crafter::JobGroup::Job precompile = jobs.Add(std::format("Precompiling {}.cppm", path.filename().string()), [command = std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())] { - return Crafter::RunBuildCommand(command); - }, after); - const std::array precompiled = {precompile}; - AddObjectJob(jobs, clang, path, pcmDir, buildDir, precompiled); - return precompile; - } - - // For a unit whose BMI is up to date: the object job alone, when the - // object is missing or older than the BMI it is made from. The two are - // written by two commands, and a build can end between them: by an error - // elsewhere, which keeps the second from starting, by the second failing, - // or by being interrupted. An object written in the same tick of the - // file system's clock as its BMI is taken to be the later of the two, - // which it is whenever the command that writes it ran. - void AddObjectJobIfStale(Crafter::JobGroup& jobs, std::string_view clang, const fs::path& path, const fs::path& pcmDir, const fs::path& buildDir) { - std::error_code ec; - const fs::file_time_type pcmTime = fs::last_write_time(std::format("{}.pcm", (pcmDir/path.filename()).string()), ec); - // No BMI to make it from; Check does not call such a unit up to date. - if (ec) return; - const fs::file_time_type objectTime = fs::last_write_time(std::format("{}.o", (buildDir/path.filename()).string()), ec); - if (!ec && objectTime >= pcmTime) return; - AddObjectJob(jobs, clang, path, pcmDir, buildDir, {}); - } -} - namespace Crafter { - ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {} + ModulePartition::ModulePartition(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {} bool ModulePartition::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) { if(!checked) { @@ -88,6 +44,11 @@ namespace Crafter { } } needsRecompiling = false; + compiled.store(true); + // Nothing waits on `compiled` until the compile threads start, + // which is after every Check has run — but notify anyway so the + // flag is never left set without a wake-up behind it. + compiled.notify_all(); return false; } else { needsRecompiling = true; @@ -98,25 +59,52 @@ namespace Crafter { } } - std::optional ModulePartition::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) { - if (scheduled) return precompileJob; - if (needsRecompiling) { - std::vector after; - for (ModulePartition* dependency : partitionDependencies) { - if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); + void ModulePartition::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError) { + for(ModulePartition* dependency : partitionDependencies) { + if(!dependency->compiled.load()) { + dependency->compiled.wait(false); + } + } + for(Module* dependency : moduleDependencies) { + if(!dependency->compiled.load()) { + dependency->compiled.wait(false); + } + } + + if (buildCancelled.load(std::memory_order_relaxed)) { + compiled.store(true); + compiled.notify_all(); + return; + } + + // -MD records every header the preamble pulled in, next to the BMI as + // .pcm.d, so the next Check can see an edit to one of them. + std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())); + + if (!result.empty()) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); + compiled.store(true); + compiled.notify_all(); + return; + } + } + + compiled.store(true); + compiled.notify_all(); + + result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())); + + if (!result.empty()) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); } - for (Module* dependency : moduleDependencies) { - if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); - } - precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after); - } else { - AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir); } - scheduled = true; - return precompileJob; } - Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)) {} + Module::Module(std::string&& name, fs::path&& path) : name(std::move(name)), path(std::move(path)), compiled(false), checked(false) {} bool Module::Check(const fs::path& pcmDir, fs::file_time_type sourceFloor) { if(!checked) { @@ -128,7 +116,7 @@ namespace Crafter { if(fs::exists(pcmPath) && std::max({fs::last_write_time(cppmPath), sourceFloor, NewestPrerequisite(std::format("{}.d", pcmPath))}) < fs::last_write_time(pcmPath)) { fs::file_time_type pcmTime = fs::last_write_time(pcmPath); // Every partition gets Check()ed even once one is known stale: - // Schedule() drives partition rebuilds off their own + // Compile() drives partition rebuilds off their own // needsRecompiling flags, so short-circuiting here would leave // the later ones unevaluated and silently unbuilt. bool depCheck = false; @@ -161,12 +149,14 @@ namespace Crafter { return true; } else { needsRecompiling = false; + compiled.store(true); + compiled.notify_all(); return false; } } else { // Already known stale, but the dependencies still need - // evaluating: Schedule() below reads their needsRecompiling, - // and an unchecked local module would never get built. + // evaluating: an unchecked local module would never get built, + // and Compile() below waits on its `compiled` flag. for(std::unique_ptr& partition : partitions) { partition->Check(pcmDir, sourceFloor); } @@ -181,29 +171,60 @@ namespace Crafter { } } - std::optional Module::Schedule(JobGroup& jobs, std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir) { - if (scheduled) return precompileJob; - std::vector after; - // All of the module's partitions, not the ones the primary interface - // names: Build() records no edge for its `import :Part;` lines (see - // Module::moduleDependencies). And of a module that is up to date as - // well: this is where its partitions are scheduled, and one of them - // may be without its object. - for (const std::unique_ptr& partition : partitions) { - if (const std::optional job = partition->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); - } - if (needsRecompiling) { - // A sibling module in the same Configuration that this interface - // unit imports has to have its PCM on disk before we precompile - // against it. - for (Module* dependency : moduleDependencies) { - if (const std::optional job = dependency->Schedule(jobs, clang, pcmDir, buildDir)) after.push_back(*job); + void Module::Compile(const std::string_view clang, const fs::path& pcmDir, const fs::path& buildDir, std::atomic& buildCancelled, std::string& buildError) { + // A sibling module in the same Configuration that this interface unit + // imports has to have its PCM on disk before we precompile against it. + // Safe to block here: Build() Checks every interface before it spawns + // any compile thread, so a dependency that needs no rebuild already has + // `compiled` set and this returns immediately. + for(Module* dependency : moduleDependencies) { + if(!dependency->compiled.load()) { + dependency->compiled.wait(false); + } + } + + std::vector threads; + threads.reserve(partitions.size()); + for(std::unique_ptr& part : partitions) { + if(part->needsRecompiling) { + threads.emplace_back(&ModulePartition::Compile, part.get(), clang, pcmDir, buildDir, std::ref(buildCancelled), std::ref(buildError)); + } + } + + for(std::thread& thread : threads){ + thread.join(); + } + + if (buildCancelled.load(std::memory_order_relaxed)) { + compiled.store(true); + compiled.notify_all(); + return; + } + + // -MD records every header the preamble pulled in, next to the BMI as + // .pcm.d, so the next Check can see an edit to one of them. + std::string result = RunBuildCommand(std::format("{0} {1}.cppm --precompile -MD -MF {2}.pcm.d -o {2}.pcm", clang, path.string(), (pcmDir/path.filename()).string())); + + if (!result.empty()) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); + compiled.store(true); + compiled.notify_all(); + return; + } + } + + compiled.store(true); + compiled.notify_all(); + + result = RunBuildCommand(std::format("{} -Wno-unused-command-line-argument {}.pcm -c -o {}.o", clang, (pcmDir/path.filename()).string(), (buildDir/path.filename()).string())); + + if (!result.empty()) { + bool expected = false; + if (buildCancelled.compare_exchange_strong(expected, true)) { + buildError = std::move(result); } - precompileJob = AddInterfaceJobs(jobs, clang, path, pcmDir, buildDir, after); - } else { - AddObjectJobIfStale(jobs, clang, path, pcmDir, buildDir); } - scheduled = true; - return precompileJob; } } diff --git a/implementations/Crafter.Build-Jobs.cpp b/implementations/Crafter.Build-Jobs.cpp deleted file mode 100644 index 82b0835..0000000 --- a/implementations/Crafter.Build-Jobs.cpp +++ /dev/null @@ -1,218 +0,0 @@ -// SPDX-License-Identifier: LGPL-3.0-only -// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® - -module Crafter.Build:Jobs_impl; -import std; -import :Jobs; -import :Progress; - -namespace { - // The pool this thread is a worker of; null on every other thread. - thread_local const Crafter::JobPool* WorkerOf = nullptr; -} - -namespace Crafter { - JobPool::JobPool(std::uint32_t workers) : limit(std::max(workers, 1u)) {} - - JobPool::~JobPool() { - { - std::lock_guard lock(mutex); - stopping = true; - } - wake.notify_all(); - for (std::thread& thread : threads) thread.join(); - } - - JobPool& JobPool::Process() { - static JobPool* const pool = new JobPool(std::thread::hardware_concurrency()); - return *pool; - } - - std::uint32_t JobPool::Workers() const { - return limit; - } - - void JobPool::Submit(std::function job) { - std::lock_guard lock(mutex); - queue.push_back(std::move(job)); - if (queue.size() <= idle || threads.size() >= limit) { - wake.notify_one(); - return; - } - try { - threads.emplace_back([this] { Work(); }); - } catch (...) { - // The system has no thread to give. The workers there are take - // the job when they get to it. With none it would stay queued - // for good, and whoever waits for it with it. - if (!threads.empty()) return; - queue.pop_back(); - throw; - } - } - - void JobPool::Work() { - WorkerOf = this; - std::unique_lock lock(mutex); - for (;;) { - while (queue.empty() && !stopping) { - ++idle; - wake.wait(lock); - --idle; - } - if (queue.empty()) return; - std::function job = std::move(queue.front()); - queue.pop_front(); - lock.unlock(); - job(); - // Before the lock is taken again: what the job captured is - // released without holding up the queue. - job = nullptr; - lock.lock(); - } - } - - void JobPool::Run(const std::function& work) { - if (WorkerOf == this) { - work(); - return; - } - // Shared with the job, not a local of this function: this thread - // goes on as soon as the value is set, which is before set_value has - // returned on the worker. - const std::shared_ptr> done = std::make_shared>(); - std::future finished = done->get_future(); - Submit([&work, done] { - try { - work(); - done->set_value(); - } catch (...) { - done->set_exception(std::current_exception()); - } - }); - finished.get(); - } - - struct JobGroup::Node { - std::string label; - std::function work; - std::unique_ptr task; - // The jobs added after this one that it has yet to release, and how - // many jobs this one still waits for. Both under the group's mutex; - // the members above belong to whoever runs the job. - std::vector dependents; - std::size_t waiting = 0; - bool finished = false; - }; - - JobGroup::JobGroup(JobPool& pool) : pool(pool) { - if (WorkerOf == &pool) throw std::logic_error("a JobGroup cannot be made on a worker of its own pool: it would wait there for jobs that need that worker"); - } - - JobGroup::~JobGroup() { - std::unique_lock lock(mutex); - failed = true; - settled.wait(lock, [this] { return unfinished == 0; }); - } - - JobGroup::Job JobGroup::Add(std::string label, std::function work, std::span after) { - std::unique_ptr made = std::make_unique(); - // Counted from here on, not from when it starts: the total a build - // shows is then what it has queued, and not only what the workers - // have got to. - made->task = std::make_unique(label); - made->label = std::move(label); - made->work = std::move(work); - - std::lock_guard lock(mutex); - // Room for the new job in each list it may join, made before the - // group knows of it: from there to the count below nothing can throw, - // so no job is ever waited on by half of what it comes after. - for (const Job job : after) { - if (job >= nodes.size()) throw std::out_of_range("JobGroup::Add: a job can only come after jobs added before it"); - std::vector& dependents = nodes[job]->dependents; - dependents.reserve(dependents.size() + after.size()); - } - const Job id = nodes.size(); - Node& node = *nodes.emplace_back(std::move(made)); - for (const Job job : after) { - Node& before = *nodes[job]; - if (before.finished) continue; - before.dependents.push_back(&node); - ++node.waiting; - } - ++unfinished; - if (node.waiting != 0) return id; - try { - Start(node); - } catch (...) { - // Not queued (JobPool::Submit), so nothing will ever finish it: - // it is taken back, or Wait() would never return. - node.work = nullptr; - node.task.reset(); - node.finished = true; - if (--unfinished == 0) settled.notify_all(); - throw; - } - return id; - } - - void JobGroup::Start(Node& node) { - pool.Submit([this, &node] { Execute(node); }); - } - - void JobGroup::Execute(Node& node) { - bool skipped = false; - { - std::lock_guard lock(mutex); - skipped = failed; - } - std::string result; - if (!skipped) { - try { - result = node.work(); - } catch (const std::exception& e) { - result = std::format("{}: {}", node.label, e.what()); - } catch (...) { - result = std::format("{}: threw something that isn't a std::exception", node.label); - } - } - // Both before the group hears of it: what the work captured is gone, - // and the step counted as done, by the time Wait() returns. - node.work = nullptr; - node.task.reset(); - - // Nothing of the group is touched once this lock is released: with - // the last job finished, whoever waited may destroy it. - std::lock_guard lock(mutex); - if (!result.empty() && !failed) { - failed = true; - error = std::move(result); - } - node.finished = true; - // Released after a failure as well: they are skipped when they run, - // which is what counts them as finished. - for (Node* dependent : node.dependents) { - if (--dependent->waiting == 0) Start(*dependent); - } - if (--unfinished == 0) settled.notify_all(); - } - - void JobGroup::Fail(std::string why) { - std::lock_guard lock(mutex); - if (failed) return; - failed = true; - error = std::move(why); - } - - bool JobGroup::Failed() const { - std::lock_guard lock(mutex); - return failed; - } - - std::string JobGroup::Wait() { - std::unique_lock lock(mutex); - settled.wait(lock, [this] { return unfinished == 0; }); - return error; - } -} diff --git a/implementations/Crafter.Build-Lint.cpp b/implementations/Crafter.Build-Lint.cpp index f546ea9..357fb33 100644 --- a/implementations/Crafter.Build-Lint.cpp +++ b/implementations/Crafter.Build-Lint.cpp @@ -8,7 +8,6 @@ export module Crafter.Build:Lint_impl; import std; import :Lint; import :Clang; -import :Test; import :Platform; import :Toolchain; import :Progress; @@ -43,7 +42,6 @@ namespace { decltype(&clang_createIndex) createIndex = nullptr; decltype(&clang_disposeIndex) disposeIndex = nullptr; decltype(&clang_parseTranslationUnit) parseTranslationUnit = nullptr; - decltype(&clang_parseTranslationUnit2FullArgv) parseTranslationUnit2FullArgv = nullptr; decltype(&clang_disposeTranslationUnit) disposeTranslationUnit = nullptr; decltype(&clang_getFile) getFile = nullptr; decltype(&clang_getLocationForOffset) getLocationForOffset = nullptr; @@ -134,7 +132,6 @@ namespace { bind(lib.createIndex, "clang_createIndex"); bind(lib.disposeIndex, "clang_disposeIndex"); bind(lib.parseTranslationUnit, "clang_parseTranslationUnit"); - bind(lib.parseTranslationUnit2FullArgv, "clang_parseTranslationUnit2FullArgv"); bind(lib.disposeTranslationUnit, "clang_disposeTranslationUnit"); bind(lib.getFile, "clang_getFile"); bind(lib.getLocationForOffset, "clang_getLocationForOffset"); @@ -707,12 +704,11 @@ namespace { return decls; } - // The resource directory, which holds clang's own headers such as - // stddef.h, as the compiler names it. libclang's driver would otherwise - // derive one from argv[0] for libclang's own release, so with a libclang - // of another release than the compiler, a file that includes a header of - // the C++ standard library would fail on "'stddef.h' file not found". - // Cached like HostTarget, and for the same reason. + // libclang locates its builtin headers relative to its own install path, + // which need not agree with the clang++ on PATH that produced the PCMs. + // When it disagrees the failure is total and unhelpful — every parse dies + // on "'stddef.h' file not found" — so ask the driver and pass it + // explicitly. Cached like HostTarget, and for the same reason. const std::string& ClangResourceDir() { static const std::string Cached = []() -> std::string { CommandResult r = RunCommandChecked(std::format("{} -print-resource-dir", GetToolchain().clangxx.string())); @@ -755,26 +751,7 @@ namespace { // Byte-length preserving, so cursor line/column land on the original. std::string buffer = BlankExportKeywords(content, tokens); std::string path = file.string(); - // In a build for the host whose compile command names no libc++ - // directory (a sysroot or CRAFTER_BUILD_LIBCXX_DIR names one), the - // driver inside libclang looks for libc++'s headers in ../include from - // the directory of argv[0], as the compiler's driver does from its - // own, and then in /usr/local/include and in /usr/include. Left to - // name argv[0] itself, libclang names it plain "clang", in no - // directory, so the first of those was ../include from the working - // directory, and where none of them had a libc++, as in the Flatpak, - // whose compiler keeps its own in /app, no file of such a build that - // includes a header of the C++ standard library could be parsed - // (issue #46). The compile command's own argv[0] would not do either: - // a clang++ from PATH is a bare name, and one reached through a link - // into another directory takes itself to be where the link leads, - // unless the command's last prefix flag is -no-canonical-prefixes. So - // argv[0] is the compiler where clang started with this command takes - // itself to be, in the directory it says it is installed in when run - // with the command's last prefix flag, or, where it names none, - // clangxx as the command has it (Toolchain::InstalledClangxx). - std::vector args = { GetToolchain().InstalledClangxx(compileCommand).string() }; - std::ranges::move(CommandToArgs(compileCommand), std::back_inserter(args)); + std::vector args = CommandToArgs(compileCommand); // Required: libclang will not infer a module interface unit from the // .cppm extension, and silently treats every flag as a linker input if // left to guess. @@ -794,8 +771,8 @@ namespace { result.error = "clang_createIndex failed"; return result; } - CXTranslationUnit tu = nullptr; - if (lc.parseTranslationUnit2FullArgv(index, path.c_str(), argv.data(), static_cast(argv.size()), &unsaved, 1, CXTranslationUnit_None, &tu) != CXError_Success || !tu) { + CXTranslationUnit tu = lc.parseTranslationUnit(index, path.c_str(), argv.data(), static_cast(argv.size()), &unsaved, 1, CXTranslationUnit_None); + if (!tu) { lc.disposeIndex(index); result.error = "clang could not create a translation unit"; return result; @@ -888,28 +865,18 @@ namespace { // whose path lies inside the project root — GitProject / external deps // live under the global cache and are foreign code: they contribute // neither rules nor files. Root-first order so the root's rules win the - // by-name dedup. Of several roots, the configurations a project file - // returns, every root comes first, in the order given, and what they - // depend on after them: walked one root's graph after another, a root - // that an earlier one depends on would come before the roots between - // the two, and its rule would win over theirs. - std::vector CollectLocalConfigs(std::span roots, const fs::path& projectRoot) { + // by-name dedup. + std::vector CollectLocalConfigs(Configuration& root, const fs::path& projectRoot) { std::vector local; std::unordered_set seen; - const auto keep = [&](Configuration* c) { - if (PathInsideRoot(fs::absolute(c->path), projectRoot)) local.push_back(c); - }; - std::function below = [&](Configuration* c) { - for (Configuration* dep : c->dependencies) { - if (!seen.insert(dep).second) continue; - keep(dep); - below(dep); + std::function walk = [&](Configuration* c) { + if (!seen.insert(c).second) return; + if (PathInsideRoot(fs::absolute(c->path), projectRoot)) { + local.push_back(c); } + for (Configuration* dep : c->dependencies) walk(dep); }; - for (Configuration* root : roots) { - if (seen.insert(root).second) keep(root); - } - for (Configuration* root : roots) below(root); + walk(&root); return local; } @@ -925,10 +892,15 @@ namespace { // First owner wins, matching the root-first rule dedup: a source // reachable through two configurations parses with the nearer one. auto own = [&files, &c](fs::path file) { files.emplace(std::move(file), &c); }; - // The sources as they are listed: which module each one is a unit - // of, only a build reads. - for (const fs::path& source : c.interfaceSources) own(source); - for (const fs::path& source : c.implementationSources) own(source); + for (const std::unique_ptr& mod : c.interfaces) { + own(fs::path(std::format("{}.cppm", mod->path.string()))); + for (const std::unique_ptr& part : mod->partitions) { + own(fs::path(std::format("{}.cppm", part->path.string()))); + } + } + for (const Implementation& impl : c.implementations) { + own(fs::path(std::format("{}.cpp", impl.path.string()))); + } // cFiles/cuda resolve against cwd at build time (see Build's compile // loops); mirror that here. for (const fs::path& cf : c.cFiles) { @@ -1096,11 +1068,6 @@ void Configuration::AddAstLintRule(std::string name, std::function one = { &projectCfg }; - return RunLint(std::span(one), opts); -} - -LintSummary Crafter::RunLint(std::span configurations, const RunLintOptions& opts) { LintSummary summary; // libclang backs the lexer every rule reads through, so a failed load is @@ -1113,12 +1080,10 @@ LintSummary Crafter::RunLint(std::span configurations, con } fs::path projectRoot = opts.projectFile.empty() - ? fs::absolute(configurations.empty() ? fs::path() : configurations.front()->path) + ? fs::absolute(projectCfg.path) : opts.projectFile.parent_path(); - std::vector localConfigs = CollectLocalConfigs(configurations, projectRoot); - // The tests' compile commands are worked out as RunTests builds them. - for (Configuration* c : localConfigs) UnpackageTests(*c); + std::vector localConfigs = CollectLocalConfigs(projectCfg, projectRoot); // Collect rules root-first, dedup by name (first registration wins). std::vector rules; @@ -1165,7 +1130,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would. CollectConfigSources(*c, files); for (const Test& t : c->tests) CollectConfigSources(t.config, files); } - // project.cpp is not built by Build() at all — its load compiles it + // project.cpp is not built by Build() at all — LoadProject compiles it // against the host PCM cache with its own flags, so it is owned by nothing // here and gets no compile command. Token rules still cover it. if (!opts.projectFile.empty()) files.emplace(opts.projectFile, nullptr); @@ -1184,10 +1149,6 @@ format` applies it to disk, and `crafter-build lint` reports where it would. // command per configuration — GetCompileCommand walks the dependency tree. const bool anyRuleNeedsAst = std::ranges::any_of(rules, [](const LintRule* r) { return r->needsAst; }); std::unordered_map commands; - // Why a configuration of the build graph has no command: its files - // cannot be parsed, which fails the run. Cleared to nothing, the command - // read as "not a translation unit" and every semantic rule passed them. - std::unordered_map commandErrors; if (anyRuleNeedsAst && !opts.noAst) { for (Configuration* c : localConfigs) { auto ensure = [&](const Configuration& cfg) { @@ -1205,14 +1166,10 @@ format` applies it to disk, and `crafter-build lint` reports where it would. Progress::Task task(std::format("Building std PCM ({}-{})", cfg.target, cfg.march)); fs::create_directories(assembled.stdPcmDir); std::string error = BuildStdPcm(cfg, assembled.stdPcmDir/"std.pcm"); - if (!error.empty()) { - command.clear(); - commandErrors.emplace(&cfg, std::format("building the std module for {}: {}", cfg.target, error)); - } + if (!error.empty()) command.clear(); } - } catch (const std::exception& e) { - command.clear(); - commandErrors.emplace(&cfg, std::format("assembling the compile command for {}: {}", cfg.target, e.what())); + } catch (const std::exception&) { + command.clear(); // surfaced per file as an AST reason } commands.emplace(&cfg, std::move(command)); }; @@ -1223,7 +1180,7 @@ format` applies it to disk, and `crafter-build lint` reports where it would. for (const auto& [file, owner] : files) { std::ifstream in(file, std::ios::binary); - if (!in) continue; // a listed file that is not there is the build's to report + if (!in) continue; // config parse already read it; a vanished file fails the build first std::stringstream buffer; buffer << in.rdbuf(); LintContext ctx; @@ -1243,13 +1200,8 @@ format` applies it to disk, and `crafter-build lint` reports where it would. // decides what is safe to touch. Skip it and make the run fail. if (rule->needsAst) { if (opts.noAst) continue; - if (auto failed = commandErrors.find(owner); failed != commandErrors.end()) { - astFailures.emplace(file, failed->second); - skippedAstRules.insert(rule->name); - continue; - } // No compile command means this file is not a translation unit - // of the build graph — project.cpp, which its load compiles + // of the build graph — project.cpp, which LoadProject compiles // with its own flags, or a header. A semantic rule does not // apply there, the same way a rule self-filters by extension, // so skip it quietly. That is a different thing from a file we diff --git a/implementations/Crafter.Build-Platform.cpp b/implementations/Crafter.Build-Platform.cpp index 58ddefe..ad88ab6 100644 --- a/implementations/Crafter.Build-Platform.cpp +++ b/implementations/Crafter.Build-Platform.cpp @@ -9,8 +9,6 @@ module; #include #include #include -#include -#include #include #include module Crafter.Build:Platform_impl; @@ -20,7 +18,6 @@ import :Toolchain; import :Clang; import :Interface; import :External; -import :Jobs; import :Progress; namespace fs = std::filesystem; using namespace Crafter; @@ -28,7 +25,7 @@ using namespace Crafter; namespace { // Exclusive advisory lock over one PCM cache dir (`/-/`), // held for the duration of a (re)build. Concurrent crafter-build invocations — - // and the threads of a single invocation that build at once — that share a cache + // and the worker threads inside a single invocation — that share a cache // serialize their builds through it: the first builder to acquire the lock // precompiles std.pcm / the Crafter.Build-*.pcm modules while everyone else // blocks, then re-checks freshness and reuses the finished file instead of @@ -279,46 +276,31 @@ bool Crafter::MatchAny(std::span globs, std::string_view name return false; } -namespace { - // RunBuildCommand's command, run on the thread that calls. See the - // declaration in Crafter.Build-Platform.cppm for why this branches on the - // exit code rather than on whether the command said anything. - std::string RunBuildStep(std::string_view cmd) { - Progress::EchoCommand(cmd); - CommandResult r = RunCommandChecked(cmd); - // A mingw build against a system prefix sees mingw-w64 through a view in - // the cache, and clang names every header by the path it found it at. - r.output = MingwViewToPrefix(std::move(r.output)); - - if (r.exitCode == 0) { - // Warnings from a step that succeeded. Show them — until now they were - // invisible on an incremental build and fatal on a cold one. - if (!r.output.empty()) Progress::Diagnostic(r.output); - return ""; - } - - // A compiler killed outright (the OOM killer is the common one) prints - // nothing, so the old "output means failure" rule read it as success and - // let the build carry on with a missing object. Say what happened instead. - if (r.output.empty()) { - return r.crashed - ? std::format("terminated by signal {}: {}", r.signal, cmd) - : std::format("exited with code {}: {}", r.exitCode, cmd); - } - if (r.crashed) { - return std::format("{}\nterminated by signal {}", r.output, r.signal); - } - return r.output; - } -} - +// See the declaration in Crafter.Build-Platform.cppm for why this branches on +// the exit code rather than on whether the command said anything. std::string Crafter::RunBuildCommand(std::string_view cmd) { - // A job is on a worker already and runs the command where it is. A link, - // or the precompile of the std module, comes from the thread of a Build() - // or of a project file's load and waits here for its turn among the jobs. - std::string result; - JobPool::Process().Run([&result, cmd] { result = RunBuildStep(cmd); }); - return result; + Progress::EchoCommand(cmd); + CommandResult r = RunCommandChecked(cmd); + + if (r.exitCode == 0) { + // Warnings from a step that succeeded. Show them — until now they were + // invisible on an incremental build and fatal on a cold one. + if (!r.output.empty()) Progress::Diagnostic(r.output); + return ""; + } + + // A compiler killed outright (the OOM killer is the common one) prints + // nothing, so the old "output means failure" rule read it as success and + // let the build carry on with a missing object. Say what happened instead. + if (r.output.empty()) { + return r.crashed + ? std::format("terminated by signal {}: {}", r.signal, cmd) + : std::format("exited with code {}: {}", r.exitCode, cmd); + } + if (r.crashed) { + return std::format("{}\nterminated by signal {}", r.output, r.signal); + } + return r.output; } // --- Dependencies of project.cpp itself ------------------------------------- @@ -330,7 +312,7 @@ std::string Crafter::RunBuildCommand(std::string_view cmd) { // file, so this is a directive next to the `import` it enables — where // `#include` lives. Each one is fetched, built for the host, and put on // project.so's module path and link line before project.cpp is compiled. The -// dependency's own project.cpp is loaded the same way, so its pragmas +// dependency's own project.cpp goes through LoadProject, so its pragmas // resolve recursively. namespace { struct PragmaDependency { @@ -431,18 +413,18 @@ namespace { struct ProjectFileFrame { fs::path project; - // What the load was given, for ProjectArgs(), and only once the - // entry point is about to be called (see OpenProjectFile). A view - // is enough: the caller's storage outlives the load, and the frame - // is popped before the load returns. + // What LoadProject was given, for ProjectArgs(), and only once + // CrafterBuildProject is about to be called (see LoadProject). A view + // is enough: the caller's storage outlives LoadProject, and the frame + // is popped before LoadProject returns. std::span args; std::vector dependencies; }; - // Loads nest: a dependency's project.cpp loads inside its consumer's - // pre-pass, and GitProject inside an entry point nests again. Several - // threads may also load at once (ConcurrentCacheRace), so the stack is - // per thread. ProjectDependency() reads the top frame. + // LoadProject nests: a dependency's project.cpp loads inside its + // consumer's pre-pass, and GitProject inside CrafterBuildProject nests + // again. Several threads may also load at once (ConcurrentCacheRace), so + // the stack is per thread. ProjectDependency() reads the top frame. thread_local std::vector LoadingFrames; // A frame's dependencies, kept past the frame for PragmaDependencies(). @@ -452,7 +434,7 @@ namespace { std::mutex PragmaDependenciesMutex; std::unordered_map> PragmaDependenciesByProject; - // Held for the whole of one load of a project file. Pushing one that is + // Held for the whole of one LoadProject call. Pushing a file that is // already on the stack is a cycle, which used to recurse forever. class ProjectFileGuard { public: @@ -493,18 +475,17 @@ namespace { // A pre-dependency is host tooling: project.so is loaded into the running // crafter-build, so the dependency is built for the host and against the - // same PCM cache a load populates — the hostConfig the load itself + // same PCM cache LoadProject populates — the hostConfig LoadProject itself // compiles project.so with, so the dependency's std/Crafter.Build PCMs // land in the cache dir project.so is built against. Recursive, because // the dependency's project.cpp is loaded with no arguments and so passes - // none on, while its own deps still read CRAFTER_BUILD_MARCH and - // CRAFTER_BUILD_CUDA_ARCH from the environment. + // none on, while its own deps still read CRAFTER_BUILD_MARCH from the + // environment. void ForceHostTooling(Configuration& cfg, const Configuration& host, std::unordered_set& seen) { if (!seen.insert(&cfg).second) return; cfg.target = host.target; cfg.march = host.march; cfg.mtune = host.mtune; - cfg.cudaArch = host.cudaArch; cfg.debug = false; // project.so is a shared object, so the archive it links has to be // position-independent; static libraries aren't by default. Part of @@ -522,12 +503,7 @@ namespace { struct ProjectFileDependencies { std::vector configs; std::string compileFlags; // " -fprebuilt-module-path=…" for each dependency and its transitive deps - // Every dependency's BuildResult.libs, verbatim, then its runtimeLibs, - // the CUDA runtime, then a run path per directory of its runPaths - // (RunPathFlags), as Build() links a program: the shared libraries a - // pragma dependency is built on are found there when the load - // dlopens project.so. - std::string linkFlags; + std::string linkFlags; // every dependency's BuildResult.libs, verbatim fs::file_time_type newestArtifact = fs::file_time_type::min(); }; @@ -545,12 +521,10 @@ namespace { std::unordered_set forced; std::unordered_set walked; std::set libs; - std::set runtimeLibs; - std::set runPaths; for (const PragmaDependency& pragma : pragmas) { // Neither spec sets args, and the tool still gets none of the - // consumer's: this pre-pass runs before the load hands the + // consumer's: this pre-pass runs before LoadProject hands the // frame its args, so ProjectArgs() is empty. Given the consumer's // --target=, the tool's project.cpp would pick sources and flags // for the wrong triple, and its flags would split the tool's @@ -568,7 +542,7 @@ namespace { cfg = GitProject(spec); } else { if (!pragma.branch.empty() || !pragma.commit.empty()) PragmaError(absProject, pragma.line, "'branch' and 'commit' only apply to a git source"); - // Relative to the project file, not the cwd: the load runs + // Relative to the project file, not the cwd: LoadProject runs // from wherever the consumer was invoked. fs::path local = (absProject.parent_path() / pragma.source).lexically_normal(); if (fs::is_directory(local)) { @@ -591,8 +565,6 @@ namespace { if (!built.result.empty()) PragmaError(absProject, pragma.line, std::format("project dependency '{}' failed to build: {}", cfg->name, built.result)); out.configs.push_back(cfg); libs.insert(built.libs.begin(), built.libs.end()); - runtimeLibs.insert(built.runtimeLibs.begin(), built.runtimeLibs.end()); - runPaths.insert(built.runPaths.begin(), built.runPaths.end()); // The module path needs the dependency and everything it depends // on, same as GetCompileCommand does for a consumer; the newest @@ -608,8 +580,6 @@ namespace { walk(cfg); } for (const std::string& lib : libs) out.linkFlags += std::format(" {}", lib); - for (const std::string& lib : runtimeLibs) out.linkFlags += std::format(" {}", lib); - for (const std::string& dir : runPaths) out.linkFlags += RunPathFlags(dir); return out; } @@ -686,10 +656,6 @@ namespace { } } -std::string Crafter::RunPathFlags(std::string_view dir) { - return std::format(" -Xlinker -rpath -Xlinker {}", ShellQuote(dir)); -} - std::string Crafter::ShellQuote(std::string_view s) { std::string out; out.reserve(s.size() + 2); @@ -718,118 +684,6 @@ CommandResult Crafter::RunCommandChecked(std::string_view cmd) { return result; } -std::string Crafter::JsonQuote(std::string_view s) { - std::string out = "\""; - for (const char c : s) { - if (c == '"') out += "\\\""; - else if (c == '\\') out += "\\\\"; - else if (c == '\n') out += "\\n"; - else if (c == '\t') out += "\\t"; - else if (c == '\r') out += "\\r"; - else if (static_cast(c) < 0x20) out += std::format("\\u{:04x}", static_cast(c)); - else out.push_back(c); - } - out.push_back('"'); - return out; -} - -namespace { - bool InFlatpak() { - std::error_code ec; - return fs::exists("/.flatpak-info", ec); - } - - // The command line that runs `program arguments` on the host: as it is - // natively, through the Flatpak session helper inside crafter-build's - // Flatpak, started there in `directory`. flatpak-spawn would start it in - // crafter-build's own working directory, which the host need not have, - // so it is / unless a caller asks for another: every host command names - // its paths absolutely. --watch-bus ends the host command when - // flatpak-spawn ends. A crafter-build killed outright leaves - // flatpak-spawn running, so the host command runs on until it finishes. - // Every host command of crafter-build's own is built here: the host's - // flatpak and flatpak-builder, for RunHostFlatpak, RunHostFlatpakBuilder - // and HostFlatpakUnavailable's probes. - std::string HostCommand(std::string_view program, std::string_view arguments, const fs::path& directory = "/") { - if (!InFlatpak()) return std::format("{} {}", program, arguments); - std::string env; - if (const char* userDir = std::getenv("FLATPAK_USER_DIR"); userDir && *userDir) { - env = std::format(" {}", ShellQuote(std::format("--env=FLATPAK_USER_DIR={}", userDir))); - } - return std::format("flatpak-spawn --host --watch-bus {}{} {} {}", ShellQuote(std::format("--directory={}", directory.string())), env, program, arguments); - } - - std::int32_t RunOnHost(std::string_view program, std::string_view arguments, std::string_view shown) { - if (Progress::GetVerbosity() != Progress::Verbosity::Quiet) std::println("$ {} {}", shown, arguments); - return RunCommandAttached(HostCommand(program, arguments)); - } -} - -std::string Crafter::HostFlatpakUnavailable(const fs::path& projectDir) { - if (!InFlatpak()) { - // Through the shell: `command` is one of its builtins, which the - // `timeout` RunCommandWithTimeout wraps a command in cannot run. - if (RunCommandChecked("command -v flatpak").exitCode != 0) return "flatpak is not installed"; - return ""; - } - std::ifstream file("/.flatpak-info", std::ios::binary); - const std::string info((std::istreambuf_iterator(file)), std::istreambuf_iterator()); - if (!info.contains("org.freedesktop.Flatpak=talk")) { - return "crafter-build's Flatpak lacks the org.freedesktop.Flatpak permission it runs the host's flatpak with: it is older than that, or runs in a build sandbox"; - } - // The program install and bundle run, built as they build theirs, in - // `directory` on the host; and what it said, for a refusal. - const auto probe = [](const fs::path& directory) { return RunCommandWithTimeout(HostCommand("flatpak", "--version", directory), std::chrono::seconds(30)); }; - const auto said = [](const CommandResult& result) { - std::string_view output = result.output; - while (!output.empty() && (output.back() == '\n' || output.back() == '\r')) output.remove_suffix(1); - return std::string(output); - }; - if (const CommandResult reached = probe("/"); reached.exitCode != 0) { - return std::format("the host cannot be reached through flatpak-spawn --host: {}", said(reached)); - } - // install and bundle hand the host's flatpak paths in the project's bin/ - // and build/, so the host has to see those where crafter-build does, - // which it does not in the sandbox's own /tmp, /var, /usr, /etc and /app, - // nor where a link leads into one. The host answers for itself, by its - // own links and by whatever the sandbox shares, overrides included: the - // same program, started in a directory just made in each of them under a - // name no other has, starts only where the host sees that very directory, - // not merely a path it has as well, as it has /tmp. What this makes is - // removed again, bin/ and build/ too where they were not there before, so - // a refusal leaves nothing behind in the project's directory, which the - // caller's project.cpp is in. - std::random_device random; - const std::string mark = std::format(".crafter-build-host-probe-{:08x}{:08x}", random(), random()); - for (const std::string_view sub : {"bin", "build"}) { - const fs::path dir = fs::absolute(projectDir / sub).lexically_normal(); - std::error_code ec; - const bool existed = fs::exists(fs::symlink_status(dir, ec)); - fs::create_directories(dir / mark, ec); - if (ec) return std::format("{} cannot be made, to see whether the host sees it: {}", (dir / mark).string(), ec.message()); - const CommandResult seen = probe(dir / mark); - fs::remove(dir / mark, ec); - if (!existed) fs::remove(dir, ec); - if (seen.exitCode != 0) { - return std::format("the host does not see {} where crafter-build does ({}): crafter-build's sandbox has /tmp, /var, /usr, /etc and /app of its own, so keep the project, its bin/ and build/ and where their links lead in a directory the sandbox shares with the host, such as your home", dir.string(), said(seen)); - } - } - return ""; -} - -std::int32_t Crafter::RunHostFlatpak(std::string_view arguments) { - return RunOnHost("flatpak", arguments, "flatpak"); -} - -std::int32_t Crafter::RunHostFlatpakBuilder(std::string_view arguments) { - // flatpak-builder as a host package, else the org.flatpak.Builder app, - // as the self-host's `run flatpak` script finds it. - if (RunCommandWithTimeout(HostCommand("flatpak-builder", "--version"), std::chrono::seconds(30)).exitCode == 0) { - return RunOnHost("flatpak-builder", arguments, "flatpak-builder"); - } - return RunOnHost("flatpak", std::format("run org.flatpak.Builder {}", arguments), "flatpak"); -} - std::int32_t Crafter::RunCommandAttached(std::string_view cmd) { // The child writes straight to the terminal. Anything of ours that is // still pending — the in-place status line, buffered stdout when it is @@ -876,168 +730,6 @@ CommandResult Crafter::RunCommandWithTimeout(std::string_view cmd, std::chrono:: return result; } -namespace { - // How a child that waitid saw end ended, read as DecodeWaitStatus reads - // a pclose: the exit code, or 128+signal when a signal ended it. - std::int32_t ChildExitCode(const siginfo_t& info) { - return info.si_code == CLD_EXITED ? info.si_status : 128 + info.si_status; - } -} - -Crafter::BackgroundCommand::BackgroundCommand(std::string_view command, std::span environment, const fs::path& log, std::chrono::seconds lifetime) { - // The death signal goes to the process this forks, so that has to be - // the timeout process: `exec` makes the sh it starts as become it. - // timeout passes a SIGTERM on to its whole group and ends what is still - // running 2 s later. - std::string script = std::format("exec timeout -k 2 {} sh -c {}", lifetime.count(), ShellQuote(command)); - std::string shell = "sh"; - std::string flag = "-c"; - std::array argv = { shell.data(), flag.data(), script.data(), nullptr }; - - std::vector variables; - for (char** entry = environ; *entry != nullptr; ++entry) { - const std::string_view variable(*entry); - const std::string_view name = variable.substr(0, variable.find('=')); - if (std::ranges::none_of(environment, [&](const EnvironmentChange& change) { return change.name == name; })) { - variables.emplace_back(variable); - } - } - for (const EnvironmentChange& change : environment) { - if (change.value) variables.push_back(std::format("{}={}", change.name, *change.value)); - } - std::vector envp; - for (std::string& variable : variables) envp.push_back(variable.data()); - envp.push_back(nullptr); - - // Both close-on-exec: the child keeps them only as its 0, 1 and 2. - const std::int32_t output = ::open(log.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); - if (output < 0) throw std::runtime_error(std::format("cannot write {}: {}", log.string(), std::strerror(errno))); - const std::int32_t input = ::open("/dev/null", O_RDONLY | O_CLOEXEC); - if (input < 0) { - const std::int32_t openError = errno; - ::close(output); - throw std::runtime_error(std::format("cannot open /dev/null: {}", std::strerror(openError))); - } - - const pid_t parent = ::getpid(); - // Everything the child uses was made above: between fork and exec it - // makes async-signal-safe calls only, since another thread of this - // process may hold the allocator's lock at the moment of the fork. - pid = ::fork(); - if (pid == 0) { - // The signal is sent when the thread that forked ends, not the - // process; the parent may also have ended before this line. - if (::prctl(PR_SET_PDEATHSIG, SIGTERM) != 0 || ::getppid() != parent) ::_exit(126); - // A signal mask outlives exec, and a SIGTERM blocked in it would - // keep both the death signal and Stop() from reaching timeout. - sigset_t none; - ::sigemptyset(&none); - ::sigprocmask(SIG_SETMASK, &none, nullptr); - ::setpgid(0, 0); - ::dup2(input, STDIN_FILENO); - ::dup2(output, STDOUT_FILENO); - ::dup2(output, STDERR_FILENO); - ::execve("/bin/sh", argv.data(), envp.data()); - ::_exit(127); - } - const std::int32_t forkError = errno; - ::close(input); - ::close(output); - if (pid < 0) throw std::runtime_error(std::format("cannot start {}: {}", command, std::strerror(forkError))); - // From this side as well, so that the group exists before Stop() can - // signal it, whichever of the two runs first. Once the child has - // exec'd this fails, after the child's own call has made the group. - ::setpgid(pid, pid); -} - -Crafter::BackgroundCommand::~BackgroundCommand() { - Stop(std::chrono::seconds(5)); -} - -std::optional Crafter::BackgroundCommand::Exited() { - if (exitCode || pid < 0) return exitCode; - siginfo_t info{}; - // WNOWAIT leaves an ended command unreaped: its pid, and with it the - // number of its process group, which Stop() signals, cannot be handed - // to another process before Stop() reaps it. - if (::waitid(P_PID, static_cast(pid), &info, WEXITED | WNOHANG | WNOWAIT) == 0 && info.si_pid == pid) { - exitCode = ChildExitCode(info); - } - return exitCode; -} - -void Crafter::BackgroundCommand::Stop(std::chrono::milliseconds grace) { - if (pid < 0 || reaped) return; - ::kill(-pid, SIGTERM); - const auto deadline = std::chrono::steady_clock::now() + grace; - while (!Exited() && std::chrono::steady_clock::now() < deadline) { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - } - // What is left of the group: anything the command started that outlived - // it, and the command itself when it did not end within `grace`. - ::kill(-pid, SIGKILL); - std::int32_t status = 0; - while (::waitpid(pid, &status, 0) < 0 && errno == EINTR) {} - reaped = true; -} - -namespace { - // Removes what PrivateDirectory's destructor would have, for the - // processes that never ran it. - void RemoveAbandonedDirectories(const fs::path& parent, std::string_view prefix) { - std::error_code ec; - const auto now = fs::file_time_type::clock::now(); - for (const fs::directory_entry& entry : fs::directory_iterator(parent, ec)) { - std::error_code entryError; - if (!entry.path().filename().string().starts_with(prefix) || !entry.is_directory(entryError) || entry.is_symlink(entryError)) continue; - // Another user's directory does not open: mkdtemp made it 0700. - const std::int32_t held = ::open(entry.path().c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); - if (held < 0) continue; - // Dated only once it is held: a directory that is kept is dated - // by its holder just before it lets go of it, so a date read - // before the lock can be one the holder has replaced since. - if (::flock(held, LOCK_EX | LOCK_NB) == 0) { - const auto changed = fs::last_write_time(entry.path(), entryError); - if (!entryError && now - changed >= std::chrono::minutes(1)) fs::remove_all(entry.path(), entryError); - } - ::close(held); - } - } - - fs::path MakeDirectory(const fs::path& parent, std::string_view prefix) { - RemoveAbandonedDirectories(parent, prefix); - std::string pattern = (parent / std::format("{}XXXXXX", prefix)).string(); - if (::mkdtemp(pattern.data()) == nullptr) { - throw std::runtime_error(std::format("cannot make a directory in {}: {}", parent.string(), std::strerror(errno))); - } - return fs::path(pattern); - } -} - -Crafter::PrivateDirectory::PrivateDirectory(const fs::path& parent, std::string_view prefix) : path(MakeDirectory(parent, prefix)) { - // Close-on-exec, so that the lock is this process's alone: a command it - // starts that outlives it does not keep the directory from being - // removed. - fd = ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if (fd >= 0) { - while (::flock(fd, LOCK_EX) != 0 && errno == EINTR) {} - } -} - -Crafter::PrivateDirectory::~PrivateDirectory() { - std::error_code ec; - if (kept) { - // Dated now, while it is still held: its date is that of what was - // last made or removed in it, which may be long before, as for the - // run of a test that failed after minutes, and a directory nobody - // holds is removed a minute after its date. - fs::last_write_time(path, fs::file_time_type::clock::now(), ec); - } else { - fs::remove_all(path, ec); - } - if (fd >= 0) ::close(fd); -} - std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { CacheLock lock(stdPcm.parent_path()); if(config.target == "x86_64-w64-mingw32") { @@ -1045,17 +737,14 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { // library, naming the std module's source relative to itself. It is // looked for in the library directories the compiler searches for // this target, as it would look for libstdc++ itself, but only in - // those that belong to the mingw toolchain. The list also holds - // clang's resource directory, the sysroot's generic lib/, where a - // prefix given whole can keep a libstdc++ built for another target, - // and, when clang finds no gcc directory, an empty entry that would - // name a manifest in the working directory. A toolchain that isn't - // there is a build error, not an exception: Build() runs this with - // the threads of its external dependencies started. + // those that belong to the mingw toolchain: the list also has the + // generic /lib, where the host's own (Linux) libstdc++ keeps + // its manifest. A toolchain that isn't there is a build error, not + // an exception: Build() runs this with its worker threads started. const Toolchain& tc = GetToolchain(); - const std::string where = tc.mingwPrefix.empty() + const std::string where = tc.mingwSysroot.empty() ? std::string("where clang finds it by the x86_64-w64-mingw32 gcc on PATH") - : std::format("under {}", tc.mingwPrefix.string()); + : std::format("under {}", tc.mingwSysroot.string()); const std::string missing = std::format("no mingw-w64 libstdc++ with the std module (libstdc++ 15 or newer) {}. Install mingw-w64, or point CRAFTER_MINGW_DIR at its prefix, the directory holding x86_64-w64-mingw32/ and lib/gcc/", where); // Asked once a run for each compiler and target: every mingw // configuration comes through here, up to date or not, and the answer @@ -1086,19 +775,17 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { } } if (manifestPath.empty()) return missing; - // Found through the view MingwSysroot() may have made of the prefix, - // and named from here on by its place in the prefix, the directory - // the user knows and can go and look at. - manifestPath = fs::path(MingwViewToPrefix(manifestPath.string())); const std::optional source = StdModuleSourcePath(FileBytes(manifestPath)); if (!source) return std::format("{} names no std module", manifestPath.string()); const fs::path stdCc = (manifestPath.parent_path() / *source).lexically_normal(); if (!fs::exists(stdCc)) return std::format("{}, which {} names as the std module, is missing", stdCc.string(), manifestPath.string()); + // -femulated-tls keeps PCM TLS access matching libstdc++'s emutls + // definitions; mismatch surfaces as undefined std::__once_callable. // The std.cc → std.cppm copy uses a plain filename: held under the // cache lock, no other builder writes this path concurrently. fs::path stdCppm = stdPcm.parent_path() / "std.cppm"; - std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config, GetToolchain()), stdCppm.string(), stdPcm.string()); + std::string command = std::format("{} --target={} -march={} -mtune={} -femulated-tls -O3 -std=c++26 -Wno-reserved-identifier -Wno-reserved-module-identifier --precompile {} -o {}", GetBaseCommand(config), config.target, config.march, config.mtune, stdCppm.string(), stdPcm.string()); std::string stamp = HashStamp(command + '\0' + FileBytes(stdCc)); if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return ""; std::error_code copyEc; @@ -1116,7 +803,7 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { // /usr/share/libc++/v1/. std::string stdCppm; if (isWasm) { - stdCppm = std::format("{}/share/libc++/v1/std.cppm", config.ResolvedSysroot(GetToolchain())); + stdCppm = std::format("{}/share/libc++/v1/std.cppm", config.sysroot); } else if (config.sysroot.empty()) { stdCppm = GetToolchain().stdCppm.string(); } else { @@ -1128,11 +815,27 @@ std::string Crafter::BuildStdPcm(const Configuration& config, fs::path stdPcm) { if (!source.error.empty()) return source.error; stdCppm = source.stdCppm.string(); } + std::string sysrootFlag = config.sysroot.empty() + ? std::string() + : std::format(" --sysroot={}", config.sysroot); + // wasm32 rejects -march, and the std module has to be compiled the way + // the units importing it are, a variant pass's flags (e.g. + // -mrelaxed-simd) included, or the BMI is not feature-compatible. + std::string archFlags = isWasm + ? WasmCompileFlags(config) + : std::format(" -march={} -mtune={}", config.march, config.mtune); + // non-wasm cross builds: the driver ranks the host toolchain's own + // libc++ headers (/../include/c++/v1) above --sysroot, so + // the PCM would mix host libc++ with the foreign libc — force the + // sysroot's copy. + if (!isWasm && !config.sysroot.empty()) { + archFlags += std::format(" -nostdinc++ -isystem {}/usr/include/c++/v1", config.sysroot); + } // Keyed on the command and the module source's bytes, never on // mtimes: an installed std.cppm can be dated at the epoch (OSTree), // and a libc++ update under the same clang changes the bytes but // not the path. - std::string command = std::format("{}{} --precompile {} -o {}", GetBaseCommand(config), StdPcmFlags(config, GetToolchain()), stdCppm, stdPcm.string()); + std::string command = std::format("{} --target={} -std=c++26{}{} -O3 -Wno-reserved-identifier -Wno-reserved-module-identifier --precompile {} -o {}", GetBaseCommand(config), config.target, sysrootFlag, archFlags, stdCppm, stdPcm.string()); std::string stamp = HashStamp(command + '\0' + FileBytes(stdCppm)); if (fs::exists(stdPcm) && ReadStamp(StampPath(stdPcm)) == stamp) return ""; std::string result = RunBuildCommand(command); @@ -1159,25 +862,23 @@ std::string Crafter::GetBaseCommand(const Configuration& config) { if (config.target == "x86_64-w64-mingw32") { // libstdc++ from the mingw toolchain, said outright: a clang built to // default to libc++ (the Flatpak's) would otherwise reach for that. - // Found by clang's own mingw discovery unless there is a prefix. + // Found by clang's own mingw discovery unless there is a sysroot. command += " -stdlib=libstdc++"; - if (const fs::path& sysroot = MingwSysroot(); !sysroot.empty()) command += std::format(" --sysroot={}", sysroot.string()); + if (!tc.mingwSysroot.empty()) command += std::format(" --sysroot={}", tc.mingwSysroot.string()); return command; } command += " -stdlib=libc++"; // A sysroot build (wasm, a cross rootfs) takes libc++ from the sysroot; // only host builds can be pointed at an explicit libc++ install. - if (config.ResolvedSysroot(tc).empty()) command += tc.LibcxxCompileFlags(); + if (config.sysroot.empty()) command += tc.LibcxxCompileFlags(); return command; } namespace { - constexpr std::array CrafterBuildModules = { + constexpr std::array CrafterBuildModules = { "Crafter.Build-Toolchain", "Crafter.Build-Shader", "Crafter.Build-Platform", - "Crafter.Build-Flatpak", - "Crafter.Build-Jobs", "Crafter.Build-Interface", "Crafter.Build-Implementation", "Crafter.Build-External", @@ -1231,32 +932,10 @@ namespace { } } -namespace { - using ProjectFn = Configuration (*)(std::span); - using ConfigurationsFn = std::vector (*)(std::span); - - // The entry point of a loaded project file: one of the two is set. - struct ProjectEntry { - ProjectFn one = nullptr; - ConfigurationsFn several = nullptr; - }; - - // Every Configuration a CrafterBuildProject returned to - // LoadConfigurations, kept for the rest of the process like the ones a - // CrafterBuildConfigurations returns, which its project file keeps: - // whoever holds a pointer LoadConfigurations gave out, the project cache - // or a consumer's `dependencies`, holds it that long. - std::mutex ReturnedConfigurationsMutex; - std::vector> ReturnedConfigurations; -} - -// Compiles the project file `guard` holds into project.so, unless the one -// there is current, loads it and finds its entry point. The frame holds -// `args` once this returns, for the call the caller makes next. -static ProjectEntry OpenProjectFile(ProjectFileGuard& guard, std::span args) { - // A copy: the loads of the file's dependencies push frames of their own, - // which can move this one. - const fs::path absProject = guard.Frame().project; +Configuration Crafter::LoadProject(const fs::path& projectFile, std::span args) { + RequireToolchain(); + fs::path absProject = fs::canonical(projectFile); + ProjectFileGuard guard(absProject); fs::path buildDir = absProject.parent_path() / "build"; if (!fs::exists(buildDir)) { fs::create_directories(buildDir); @@ -1340,20 +1019,11 @@ static ProjectEntry OpenProjectFile(ProjectFileGuard& guard, std::span(dlsym(handle, "CrafterBuildProject")); - entry.several = reinterpret_cast(dlsym(handle, "CrafterBuildConfigurations")); - if (!entry.one && !entry.several) { - throw std::runtime_error(std::format("{} defines neither CrafterBuildProject nor CrafterBuildConfigurations (looked in {})", absProject.string(), soPath.string())); - } - // Calling the first would leave what the second returns unbuilt, and - // the other way around, without a word. - if (entry.one && entry.several) { - throw std::runtime_error(std::format("{} defines both CrafterBuildProject and CrafterBuildConfigurations; a project file has one entry point", absProject.string())); + using ProjectFn = Configuration (*)(std::span); + dlerror(); + auto fn = reinterpret_cast(dlsym(handle, "CrafterBuildProject")); + if (const char* err = dlerror()) { + throw std::runtime_error(std::format("CrafterBuildProject not found in {}: {}", soPath.string(), err)); } // The args only for the call itself, unlike the dependencies. A static @@ -1363,67 +1033,5 @@ static ProjectEntry OpenProjectFile(ProjectFileGuard& guard, std::span args) { - RequireToolchain(); - const fs::path absProject = fs::canonical(projectFile); - ProjectFileGuard guard(absProject); - const ProjectEntry entry = OpenProjectFile(guard, args); - if (!entry.one) { - throw std::runtime_error(std::format("{} defines CrafterBuildConfigurations, which LoadProject cannot return by value; load it with LoadConfigurations", absProject.string())); - } - return entry.one(args); -} - -std::vector Crafter::LoadConfigurations(const fs::path& projectFile, std::span args) { - RequireToolchain(); - const fs::path absProject = fs::canonical(projectFile); - ProjectFileGuard guard(absProject); - const ProjectEntry entry = OpenProjectFile(guard, args); - if (entry.one) { - // The call's return value is the initialiser of the new-expression, - // so the Configuration is constructed where it stays and is never - // moved; std::make_unique would move a temporary into place. A - // project file takes pointers to the configuration it returns, for a - // test that links the library it describes (cfg.AddTest(...) - // .Dependencies({ &cfg })), and they are pointers to this object - // when the compiler constructed the local the file returns in place - // of the return value, as clang does for a function that returns one - // local. - std::unique_ptr returned(new Configuration(entry.one(args))); - Configuration* const configuration = returned.get(); - const std::lock_guard lock(ReturnedConfigurationsMutex); - ReturnedConfigurations.push_back(std::move(returned)); - return { configuration }; - } - - std::vector configurations = entry.several(args); - if (configurations.empty()) { - throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned no configuration", absProject.string())); - } - std::unordered_set seen; - for (const Configuration* configuration : configurations) { - if (!configuration) { - throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned a null pointer", absProject.string())); - } - // Most often a pasted `&lib` where `&tool` was meant, which would - // leave `tool` unbuilt without a word. - if (!seen.insert(configuration).second) { - throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned {} twice", absProject.string(), configuration->name)); - } - // One that a project GitProject or LocalProject loaded keeps to - // itself, taken out of the `dependencies` or the `tests` of what - // that project's file returned. Returned from here it would count - // as one this file - // made: `test` would run its tests and `run` offer its scripts, - // which are that project's. And only the configurations a project - // file returns are rebased onto its directory, so this one would be - // built wherever its relative `path` leads from here. - if (const std::optional keeper = KeptBy(*configuration)) { - throw std::runtime_error(std::format("{}: CrafterBuildConfigurations returned {}, which {} keeps to itself: a project file returns the configurations it makes and the ones GitProject or LocalProject returned", absProject.string(), configuration->name, keeper->name)); - } - } - return configurations; + return fn(args); } diff --git a/implementations/Crafter.Build-Script.cpp b/implementations/Crafter.Build-Script.cpp index bbeff51..f08d219 100644 --- a/implementations/Crafter.Build-Script.cpp +++ b/implementations/Crafter.Build-Script.cpp @@ -11,18 +11,11 @@ namespace fs = std::filesystem; using namespace Crafter; namespace { - // A script and the configuration it is declared on, which is the - // project its callback is handed. - struct Declared { - const Script* script; - Configuration* owner; - }; - - std::string JoinNames(std::span scripts) { + std::string JoinNames(std::span scripts) { std::string out; - for (const Declared& declared : scripts) { + for (const Script& script : scripts) { if (!out.empty()) out += ", "; - out += declared.script->name; + out += script.name; } return out; } @@ -36,22 +29,10 @@ std::int32_t ScriptContext::Run(std::string_view command) const { } std::int32_t Crafter::RunScript(Configuration& projectCfg, const RunScriptOptions& opts) { - std::array one = { &projectCfg }; - return RunScript(std::span(one), opts); -} - -std::int32_t Crafter::RunScript(std::span configurations, const RunScriptOptions& opts) { // Loading the project may have left an in-place status line behind. Progress::Clear(); - std::vector scripts; - std::unordered_set listed; - for (Configuration* cfg : configurations) { - // Once, however often the list names it: its scripts are not names - // declared twice. - if (!listed.insert(cfg).second) continue; - for (const Script& script : cfg->scripts) scripts.push_back({ &script, cfg }); - } + const std::span scripts = projectCfg.scripts; if (scripts.empty()) { std::println(std::cerr, R"msg(No scripts defined. @@ -70,8 +51,7 @@ returned; ctx.args holds the arguments.)msg"); // declaration is reported the first time anyone uses `run` and not only // when that one name is asked for. std::unordered_set seen; - for (const Declared& declared : scripts) { - const Script& script = *declared.script; + for (const Script& script : scripts) { if (script.name.empty() || script.name.starts_with('-')) { std::println(std::cerr, "script name '{}' cannot be run: a name must not be empty or start with '-'", script.name); return 1; @@ -89,37 +69,36 @@ returned; ctx.args holds the arguments.)msg"); } if (opts.listOnly || !opts.named) { - for (const Declared& declared : scripts) std::println("{}", declared.script->name); + for (const Script& script : scripts) std::println("{}", script.name); return 0; } - const auto found = std::ranges::find_if(scripts, [&](const Declared& declared) { return declared.script->name == opts.name; }); + const auto found = std::ranges::find(scripts, opts.name, &Script::name); if (found == scripts.end()) { std::println(std::cerr, "No script named '{}'. Scripts: {}", opts.name, JoinNames(scripts)); return 1; } - const Script& script = *found->script; ScriptContext ctx{ - .project = *found->owner, + .project = projectCfg, // lexically_normal: fs::absolute keeps a "./" component. - .projectDir = opts.projectFile.empty() ? fs::absolute(found->owner->path).lexically_normal() : opts.projectFile.parent_path(), + .projectDir = opts.projectFile.empty() ? fs::absolute(projectCfg.path).lexically_normal() : opts.projectFile.parent_path(), .args = opts.args, }; try { - const std::int32_t code = script.run(ctx); + const std::int32_t code = found->run(ctx); if (code >= 0 && code <= 255) return code; - std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", script.name, code); + std::println(std::cerr, "script '{}' returned {}, which is not an exit status (0..255); exiting with 1", found->name, code); return 1; } catch (const std::exception& e) { // Never let a script's exception unwind across the project.so // boundary and out of Run: report it as this script's failure. Progress::Clear(); - std::println(std::cerr, "script '{}' failed: {}", script.name, e.what()); + std::println(std::cerr, "script '{}' failed: {}", found->name, e.what()); return 1; } catch (...) { Progress::Clear(); - std::println(std::cerr, "script '{}' failed: it threw something that isn't a std::exception", script.name); + std::println(std::cerr, "script '{}' failed: it threw something that isn't a std::exception", found->name); return 1; } } diff --git a/implementations/Crafter.Build-Test.cpp b/implementations/Crafter.Build-Test.cpp index 3160dd9..fef2108 100644 --- a/implementations/Crafter.Build-Test.cpp +++ b/implementations/Crafter.Build-Test.cpp @@ -16,6 +16,11 @@ namespace { return target.find("windows") != std::string_view::npos || target.find("mingw") != std::string_view::npos; } + fs::path TestBinaryPath(const Configuration& cfg) { + fs::path outputDir = cfg.BinDir(); + return outputDir / (TargetIsWindows(cfg.target) ? std::format("{}.exe", cfg.outputName) : cfg.outputName); + } + // MatchGlob/MatchAny live in :Platform — shared with the lint verb. std::string JoinAndQuoteArgs(std::span args) { @@ -64,78 +69,12 @@ namespace { } } - // Writes build/test-logs/.log and returns its path, or nothing - // when the directory cannot be made. - std::optional WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) { + void WriteLog(const fs::path& projectPath, const std::string& name, const std::string& output) { fs::path logDir = projectPath / "build" / "test-logs"; std::error_code ec; fs::create_directories(logDir, ec); - if (ec) return std::nullopt; - const fs::path log = logDir / std::format("{}.log", name); - std::ofstream(log) << output; - return log; - } - - // weston on its headless backend: the compositor a test that sets - // Test::wayland runs with unless --compositor= or CRAFTER_BUILD_COMPOSITOR - // names another. Its GL renderer takes the dmabufs that hardware Vulkan - // and EGL drivers present, which the headless backend's default, a - // renderer that draws nothing, and pixman do not. --no-config keeps the - // user's weston.ini out of the test, and --idle-time=0 keeps the output - // from going idle after the default 300 s, which would stop frame - // callbacks. - constexpr std::string_view DefaultCompositor = "weston --backend=headless --renderer=gl --no-config --idle-time=0"; - // The compositor named for none of the test's own: the test gets the - // display crafter-build has, to watch its windows, and the TMPDIR it is - // given, as any test does. - constexpr std::string_view HostDisplay = "host"; - // How long a compositor may take to listen. weston needs a fraction of a - // second; this is for a machine running a test on every hardware thread. - constexpr std::chrono::seconds CompositorStartup{30}; - - std::string CompositorCommand(const std::optional& compositorOverride) { - if (compositorOverride && !compositorOverride->empty()) return *compositorOverride; - const char* named = std::getenv("CRAFTER_BUILD_COMPOSITOR"); - if (named != nullptr && *named != '\0') return named; - return std::string(DefaultCompositor); - } - - // The wayland- socket a compositor made in `directory`. Any number: - // libwayland's wl_display_add_socket_auto starts at 0 and weston at 1. - std::optional WaylandSocket(const fs::path& directory) { - constexpr std::string_view prefix = "wayland-"; - std::error_code ec; - for (const fs::directory_entry& entry : fs::directory_iterator(directory, ec)) { - const std::string name = entry.path().filename().string(); - if (!name.starts_with(prefix) || name.size() == prefix.size()) continue; - if (!std::ranges::all_of(name.substr(prefix.size()), [](char c) { return c >= '0' && c <= '9'; })) continue; - std::error_code statError; - if (fs::is_socket(entry.symlink_status(statError))) return entry.path(); - } - return std::nullopt; - } - - // Where the directory one test's compositor gets as its XDG_RUNTIME_DIR - // is made: in $XDG_RUNTIME_DIR, where a session's sockets live, when - // that is a directory, else in /tmp. A socket's path holds at most 107 - // bytes, so the directory needs a short path, which a project's, a - // scratch directory's or the temp directory TMPDIR names need not be. - fs::path CompositorParent() { - const char* runtime = std::getenv("XDG_RUNTIME_DIR"); - std::error_code ec; - if (runtime != nullptr && *runtime != '\0' && fs::is_directory(runtime, ec)) return runtime; - return "/tmp"; - } - - // That directory, which also holds the compositor's log. - struct CompositorDirectory : PrivateDirectory { - CompositorDirectory() : PrivateDirectory(CompositorParent(), "crafter-build-wayland-") {} - fs::path Log() const { return path / "compositor.log"; } - }; - - std::string ReadWhole(const fs::path& file) { - std::ifstream in(file, std::ios::binary); - return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + if (ec) return; + std::ofstream(logDir / (std::format("{}.log", name))) << output; } void PrintResult(const TestResult& r, std::string_view runnerName) { @@ -177,8 +116,7 @@ namespace { } namespace { - std::mutex ParentProjectsMutex; - std::vector ParentProjects; + std::atomic ParentProject{nullptr}; Configuration* FindLibInTree(Configuration* root, std::string_view name, std::unordered_set& seen) { if (!seen.insert(root).second) return nullptr; @@ -191,31 +129,17 @@ namespace { } void Crafter::SetParentProject(Configuration* parent) { - SetParentProject(parent ? std::span(&parent, 1) : std::span()); -} - -void Crafter::SetParentProject(std::span parents) { - const std::lock_guard lock(ParentProjectsMutex); - ParentProjects.assign(parents.begin(), parents.end()); + ParentProject.store(parent); } Configuration* Crafter::ParentLib(std::string_view name) { - std::vector roots; - { - const std::lock_guard lock(ParentProjectsMutex); - roots = ParentProjects; - } - if (roots.empty()) { + Configuration* root = ParentProject.load(); + if (!root) { throw std::runtime_error(std::format("Crafter::ParentLib('{}'): no parent project set", name)); } std::unordered_set seen; - std::string names; - for (Configuration* root : roots) { - if (auto found = FindLibInTree(root, name, seen)) return found; - if (!names.empty()) names += ", "; - names += root->name; - } - throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, names)); + if (auto found = FindLibInTree(root, name, seen)) return found; + throw std::runtime_error(std::format("Crafter::ParentLib('{}'): not found in parent project '{}'", name, root->name)); } TestRunner TestRunner::Local() { @@ -325,91 +249,27 @@ TestRunner TestRunner::FromEnv(std::string_view target, TestRunner fallback) { return fallback; } -TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout, const std::optional& compositorOverride, const fs::path& temporaryDirectory) { +TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std::chrono::seconds timeout) { TestResult result; result.name = test.config.name; std::map ph; ph["{args}"] = JoinAndQuoteArgs(test.args); - std::string cmd; + auto start = std::chrono::steady_clock::now(); + CommandResult r; + if (test.runner.exec.empty()) { // Local runner: spawn the binary directly through the host shell. - cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]); + std::string cmd = std::format("{} {}", ShellQuote(binary.string()), ph["{args}"]); + r = RunCommandWithTimeout(cmd, timeout); } else { // Prefix runner (qemu-user, wasmtime, wine, ...): templated exec // wraps the local binary. ph["{bin}"] = binary.string(); - cmd = Substitute(test.runner.exec, ph); + r = RunCommandWithTimeout(Substitute(test.runner.exec, ph), timeout); } - // What `env` changes for the test, its -u options and its assignments, - // which it takes in that order. - std::string unset; - std::string set; - if (!temporaryDirectory.empty()) set += std::format(" TMPDIR={}", ShellQuote(temporaryDirectory.string())); - - // The test's own compositor, which no other test shares, so that no - // two tests cover each other's windows or take each other's focus. Its - // directory goes after it: declared first, it is destroyed last. - const std::string compositor = test.wayland ? CompositorCommand(compositorOverride) : std::string(); - std::optional directory; - std::optional process; - if (test.wayland && compositor != HostDisplay) { - directory.emplace(); - // Without a WAYLAND_DISPLAY, which the compositor would take for a - // session to open a window in (wlroots does), or a DISPLAY. - const std::array environment = {{ - {"XDG_RUNTIME_DIR", directory->path.string()}, - {"WAYLAND_DISPLAY", std::nullopt}, - {"WAYLAND_SOCKET", std::nullopt}, - {"DISPLAY", std::nullopt}, - }}; - // As long as the test may run, the wait for its socket and 30 s - // more; none for a test with none, a timeout of 0, which timeout(1) - // takes for no limit, the test's as the compositor's. - const std::chrono::seconds lifetime = timeout.count() > 0 ? timeout + CompositorStartup + std::chrono::seconds(30) : std::chrono::seconds(0); - process.emplace(compositor, environment, directory->Log(), lifetime); - - // weston makes its socket once its backend and renderer are up, so a - // socket means a compositor that takes clients. - const auto deadline = std::chrono::steady_clock::now() + CompositorStartup; - std::optional socket = WaylandSocket(directory->path); - std::optional ended; - while (!socket && !(ended = process->Exited()) && std::chrono::steady_clock::now() < deadline) { - std::this_thread::sleep_for(std::chrono::milliseconds(10)); - socket = WaylandSocket(directory->path); - } - if (!socket) { - process->Stop(std::chrono::seconds(5)); - std::string printed = ReadWhole(directory->Log()); - if (!printed.empty() && !printed.ends_with('\n')) printed.push_back('\n'); - // A compositor that is missing fails the test as any other that - // does not start does. The one skip is the test's own requires_, - // tool:weston for the default, which RunTests checks before the - // build; a probe of the command here would not do, since it is any - // sh command, whose first word need not be the compositor. - result.outcome = TestOutcome::Fail; - result.exitCode = -1; - result.output = ended - ? std::format("the headless compositor ({}) ended with status {} before it listened for clients; it printed:\n{}", compositor, *ended, printed) - : std::format("the headless compositor ({}) made no wayland- socket in {} within {} s; it printed:\n{}", compositor, directory->path.string(), CompositorStartup.count(), printed); - // sh's status for a command it cannot find. - if (ended == 127) result.output += "install weston, name another compositor with CRAFTER_BUILD_COMPOSITOR or --compositor=, or skip a test that may run without it with requires_, tool:weston for weston\n"; - return result; - } - unset += " -u DISPLAY -u WAYLAND_SOCKET"; - set += std::format(" WAYLAND_DISPLAY={}", ShellQuote(socket->string())); - } - // env's command is sh, which execs the test's words as they are: env - // takes every word with an '=' in it ahead of its command for an - // assignment, the binary's path among them where it has one (a test - // named a=b), and with no command left it printed its environment and - // exited 0, a pass for a test that never ran. - if (!unset.empty() || !set.empty()) cmd = std::format("env{}{} sh -c 'exec \"$@\"' sh {}", unset, set, cmd); - - auto start = std::chrono::steady_clock::now(); - CommandResult r = RunCommandWithTimeout(cmd, timeout); auto end = std::chrono::steady_clock::now(); result.duration = std::chrono::duration_cast(end - start); result.output = std::move(r.output); @@ -422,19 +282,6 @@ TestResult Crafter::RunSingleTest(const Test& test, const fs::path& binary, std: else if (r.exitCode != 0) result.outcome = TestOutcome::Fail; else result.outcome = TestOutcome::Pass; - if (process) { - // Asked before Stop() ends it, which would make every compositor one - // that ended. - const std::optional ended = process->Exited(); - process->Stop(std::chrono::seconds(5)); - if (result.outcome != TestOutcome::Pass && result.outcome != TestOutcome::Skipped) { - if (ended) { - if (!result.output.empty() && !result.output.ends_with('\n')) result.output.push_back('\n'); - result.output += std::format("the headless compositor ({}) ended with status {} while the test ran\n", compositor, *ended); - } - result.compositorLog = ReadWhole(directory->Log()); - } - } return result; } @@ -528,7 +375,6 @@ TestBuilder Configuration::AddTest(std::string_view name, std::span in t.config.mtune = this->mtune; t.config.sysroot = this->sysroot; t.config.debug = this->debug; - t.config.cudaArch = this->cudaArch; // Inherited so a project flag that changes what the library contains also // moves the test's own outputs, rather than letting two flag settings share // one test bin dir. @@ -557,7 +403,6 @@ void Configuration::AddMarchVariants(std::string_view name, std::span t.config.mtune = tier.mtune; t.config.sysroot = this->sysroot; t.config.debug = this->debug; - t.config.cudaArch = this->cudaArch; t.config.projectArgs = this->projectArgs; t.config.type = ConfigurationType::Executable; @@ -587,48 +432,24 @@ TestBuilder& TestBuilder::Define(std::string n, std::string v) { TestBuilder& TestBuilder::Timeout(std::chrono::seconds s) { Ref().timeout = s; return *this; } TestBuilder& TestBuilder::Args(std::vector a) { Ref().args = std::move(a); return *this; } TestBuilder& TestBuilder::Requires(std::string r) { Ref().requires_.push_back(std::move(r)); return *this; } -TestBuilder& TestBuilder::Dependencies(std::vector d) { Ref().config.dependencies = std::move(d); return *this; } +TestBuilder& TestBuilder::Dependencies(std::vector d) { + Ref().config.dependencies = std::move(d); + // AddTest already scanned tests//main.cpp, at which point this test + // had no dependencies, so every `import ;` in it came back + // unresolved. Place them now that the libraries are known — without this + // the test's object carries no staleness edge to the interfaces it consumes + // and survives a layout change to them (issue #27). Build() re-runs the + // same sweep as a backstop; doing it here keeps the Configuration coherent + // for anyone inspecting it before the build. + Ref().config.ResolvePendingImports(); + return *this; +} TestBuilder& TestBuilder::LinkFlag(std::string f) { Ref().config.linkFlags.push_back(std::move(f)); return *this; } TestBuilder& TestBuilder::CompileFlag(std::string f) { Ref().config.compileFlags.push_back(std::move(f)); return *this; } -TestBuilder& TestBuilder::Wayland(bool w) { Ref().wayland = w; return *this; } - -void Crafter::UnpackageTests(Configuration& cfg) { - for (Test& test : cfg.tests) test.config.packaging = Packaging::None; -} TestSummary Crafter::RunTests(Configuration& projectCfg, const RunTestsOptions& opts, std::span projectArgs) { - std::array one = { &projectCfg }; - return RunTests(std::span(one), opts, projectArgs); -} - -namespace { - // The directory of one run of `crafter-build test`, in the temp - // directory, which each test's TMPDIR is made in, and the names given - // out in it. Every pass of a sweep over targets shares it: the first - // that runs a test makes it, and RunTests lets go of it once the last - // pass is done. A pass that made one of its own made it once the - // passes before had let go of theirs, and making it removed any of - // those that had not changed for a minute: a kept one after a pass - // that long, while its test's output said where it was kept. - struct RunTemporaries { - std::optional directory; - std::set used; - }; -} - -// RunTests, with the run's temporaries. -static TestSummary RunTestsWith(std::span configurations, const RunTestsOptions& opts, std::span projectArgs, RunTemporaries& run) { - // Each of them once, however often the list names it: named twice, a - // configuration would have each of its tests built twice at once. - std::vector distinct; - for (Configuration* cfg : configurations) { - if (!std::ranges::contains(distinct, cfg)) distinct.push_back(cfg); - } - if (distinct.size() != configurations.size()) return RunTestsWith(distinct, opts, projectArgs, run); - - for (Configuration* cfg : configurations) UnpackageTests(*cfg); // Multi-target sweep: when no --target= was given, the run covers every - // distinct target declared across the tests plus the host target. + // distinct target declared across projectCfg.tests plus the host target. // Lets a bare `crafter-build test` exercise cross-arch tests without the // user having to know which targets exist. An explicit --target=X // bypasses the sweep and runs that target only. @@ -638,10 +459,8 @@ static TestSummary RunTestsWith(std::span configurations, // the one shown and filtered on. std::map sweep; sweep.emplace(NormalizeTarget(HostTarget()), HostTarget()); - for (const Configuration* cfg : configurations) { - for (const Test& t : cfg->tests) { - if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target); - } + for (const Test& t : projectCfg.tests) { + if (!t.config.target.empty()) sweep.emplace(NormalizeTarget(t.config.target), t.config.target); } TestSummary aggregate; for (const auto& [normalized, target] : sweep) { @@ -651,7 +470,7 @@ static TestSummary RunTestsWith(std::span configurations, Progress::Clear(); std::println("\n=== target: {} ===", target); } - TestSummary s = RunTestsWith(configurations, perTarget, projectArgs, run); + TestSummary s = RunTests(projectCfg, perTarget, projectArgs); aggregate.passed += s.passed; aggregate.failed += s.failed; aggregate.crashed += s.crashed; @@ -669,22 +488,17 @@ static TestSummary RunTestsWith(std::span configurations, // time) because runnerOverride and FromEnv resolution depend on the // run's options, which the project.cpp doesn't know about. std::vector filtered; - // The configuration that declares each of them, whose path its log is - // written under. - std::vector owners; - for (Configuration* cfg : configurations) { - for (auto& test : cfg->tests) { - if (!SameTarget(test.config.target, opts.targetFilter)) continue; - if (!MatchAny(opts.globs, test.config.name)) continue; - test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config)); - if (opts.runnerOverride) { - if (auto r = TestRunner::FromSpec(*opts.runnerOverride)) { - test.runner = std::move(*r); - } + filtered.reserve(projectCfg.tests.size()); + for (auto& test : projectCfg.tests) { + if (!SameTarget(test.config.target, opts.targetFilter)) continue; + if (!MatchAny(opts.globs, test.config.name)) continue; + test.runner = TestRunner::FromEnv(test.config.target, TestRunner::ForTarget(test.config)); + if (opts.runnerOverride) { + if (auto r = TestRunner::FromSpec(*opts.runnerOverride)) { + test.runner = std::move(*r); } - filtered.push_back(&test); - owners.push_back(cfg); } + filtered.push_back(&test); } if (opts.listOnly) { @@ -699,60 +513,6 @@ static TestSummary RunTestsWith(std::span configurations, return summary; } - // A test is built in a directory named after the test and what it is - // compiled as, not after the configuration that declares it, and its - // sources are tests/ whichever one does. Two configurations that - // each declare a test of one name, compiled alike, would have the two - // built in that one directory, at once when the run has the jobs for - // it, each with the dependencies and link flags of its own declaration. - // Neither is built: both fail, and say which configurations declare - // them. Only tests of different configurations are looked at: a test - // one configuration declares twice is as it was. - std::vector clashes(filtered.size()); - { - std::unordered_map> builtInto; - for (std::size_t i = 0; i < filtered.size(); ++i) { - builtInto[fs::absolute(filtered[i]->config.PcmDir()).lexically_normal()].push_back(i); - } - for (const auto& [directory, sharing] : builtInto) { - std::vector declaring; - for (const std::size_t i : sharing) { - if (!std::ranges::contains(declaring, owners[i])) declaring.push_back(owners[i]); - } - if (declaring.size() < 2) continue; - std::string names; - for (const Configuration* cfg : declaring) { - if (!names.empty()) names += ", "; - names += cfg->name; - } - for (const std::size_t i : sharing) { - clashes[i] = std::format("{} each declare a test named {}, which would be built for each of them in {}: give each test a name of its own", names, filtered[i]->config.name, directory.string()); - } - } - } - - // Each test runs with TMPDIR naming a directory of its own, /, - // in the run's directory in the temp directory (RunTemporaries), so that - // fs::temp_directory_path() in the test names it, where its runner hands - // it TMPDIR (RunSingleTest). Tests stage their fixtures under - // fixed names in it (crafter-build-), and two runs at once staged - // into the same ones: natively every process shares the machine's - // /tmp, and every sandbox of crafter-build's Flatpak shares the one the - // app has. A second test of one name in the run, as two configurations - // or two targets may each have one, gets -2. What a test that - // passes or skips leaves there is removed when it ends; what one that - // fails, crashes or times out leaves is kept, its output says where, and - // so is the run's directory, for a later run to remove a minute after - // this one ends, or after its last change to it where this one is - // killed (PrivateDirectory::Keep). - if (!run.directory) run.directory.emplace(fs::temp_directory_path(), "crafter-build-tests-"); - std::vector temporary(filtered.size()); - for (std::size_t i = 0; i < filtered.size(); ++i) { - std::string name = filtered[i]->config.name; - for (std::int32_t n = 2; !run.used.insert(name).second; ++n) name = std::format("{}-{}", filtered[i]->config.name, n); - temporary[i] = run.directory->path / name; - } - std::int32_t jobs = opts.jobs > 0 ? opts.jobs : std::max(1u, std::thread::hardware_concurrency()); @@ -787,18 +547,6 @@ static TestSummary RunTestsWith(std::span configurations, TestResult r; r.name = t.config.name; - if (!clashes[i].empty()) { - r.outcome = TestOutcome::Fail; - r.output = clashes[i]; - r.exitCode = -1; - { - std::lock_guard lk(printMutex); - PrintResult(r, t.runner.name); - } - results[i] = std::move(r); - continue; - } - // Declarative preconditions set via TestBuilder::Requires. Evaluated // before the build so a missing tool/file/env turns into a Skip without // paying the compile cost. Reports the first failure only — once one @@ -867,53 +615,17 @@ static TestSummary RunTestsWith(std::span configurations, } std::chrono::seconds timeout = opts.timeoutOverride.value_or(t.timeout); - // The file the link wrote, by the rule the staleness checks and -r - // use, which for a wasm32 executable is the .wasm the link - // writes. A rule of its own here once added .exe for any Windows - // triple and nothing for wasm, so every wasm test was handed to - // wasmtime without the .wasm it was linked as. - fs::path binary = ExpectedOutput(t.config); - std::error_code temporaryError; - fs::create_directories(temporary[i], temporaryError); + fs::path binary = TestBinaryPath(t.config); try { - if (temporaryError) throw std::runtime_error(std::format("cannot make the test's TMPDIR {}: {}", temporary[i].string(), temporaryError.message())); - r = RunSingleTest(t, binary, timeout, opts.compositorOverride, temporary[i]); + r = RunSingleTest(t, binary, timeout); } catch (const std::exception& e) { r.outcome = TestOutcome::Fail; r.output = std::format("runner threw: {}", e.what()); r.exitCode = -1; } - // The logs are named as the test's TMPDIR is, -2 for a later - // test of one name in the run, so that each has its own: with one - // for both, the second's was written over the first's, and with it - // where what the first left is kept. - const std::string logName = temporary[i].filename().string(); - // Beside the test's own log rather than in it: weston prints some - // 70 lines starting up, which would bury what the test said. - if (!r.compositorLog.empty()) { - if (const std::optional log = WriteLog(owners[i]->path, std::format("{}.compositor", logName), r.compositorLog)) { - if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n'); - r.output += std::format("the headless compositor's output is in {}\n", log->string()); - } - } - if (!temporaryError) { - std::error_code ec; - const bool failed = r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped; - if (failed && !fs::is_empty(temporary[i], ec) && !ec) { - // Kept at once, so that it stays whatever ends the run: - // a later pass that throws, as one does for a target whose - // runner CRAFTER_BUILD_RUNNER_ gives wrong, or a worker - // that cannot be started unwinds past the end of RunTests. - run.directory->Keep(); - if (!r.output.empty() && !r.output.ends_with('\n')) r.output.push_back('\n'); - r.output += std::format("what it left in its TMPDIR is kept in {}\n", temporary[i].string()); - } else { - fs::remove_all(temporary[i], ec); - } - } if (r.outcome != TestOutcome::Pass && r.outcome != TestOutcome::Skipped && !r.output.empty()) { - WriteLog(owners[i]->path, logName, r.output); + WriteLog(projectCfg.path, r.name, r.output); } { @@ -959,8 +671,3 @@ static TestSummary RunTestsWith(std::span configurations, return summary; } - -TestSummary Crafter::RunTests(std::span configurations, const RunTestsOptions& opts, std::span projectArgs) { - RunTemporaries run; - return RunTestsWith(configurations, opts, projectArgs, run); -} diff --git a/implementations/Crafter.Build-Toolchain.cpp b/implementations/Crafter.Build-Toolchain.cpp index abb8525..68d9f8f 100644 --- a/implementations/Crafter.Build-Toolchain.cpp +++ b/implementations/Crafter.Build-Toolchain.cpp @@ -21,42 +21,9 @@ namespace { "CRAFTER_BUILD_LIBCXX_DIR", "CRAFTER_BUILD_LIBCLANG", "CRAFTER_BUILD_WASI_SYSROOT", - "CRAFTER_BUILD_FLATPAK_INFO", "CRAFTER_MINGW_DIR", - "CUDA_PATH", - "PATH", }; - // The arch and branch of the runtime=runtime/// line - // in the [Application] group of a .flatpak-info; empty when it has none. - std::pair FlatpakRuntimeOf(std::string_view info) { - bool inApplication = false; - for (std::size_t begin = 0; begin < info.size();) { - std::size_t end = info.find('\n', begin); - if (end == std::string_view::npos) end = info.size(); - std::string_view line = info.substr(begin, end - begin); - begin = end + 1; - if (line.ends_with('\r')) line.remove_suffix(1); - if (line.starts_with("[")) { - inApplication = line == "[Application]"; - continue; - } - if (!inApplication || !line.starts_with("runtime=")) continue; - std::vector parts; - std::string_view ref = line.substr(std::string_view("runtime=").size()); - for (std::size_t at = 0;;) { - const std::size_t slash = ref.find('/', at); - parts.push_back(ref.substr(at, slash == std::string_view::npos ? std::string_view::npos : slash - at)); - if (slash == std::string_view::npos) break; - at = slash + 1; - } - if (parts.size() == 4 && parts[0] == "runtime" && !parts[2].empty() && !parts[3].empty()) { - return {std::string(parts[2]), std::string(parts[3])}; - } - } - return {}; - } - std::string_view Env(const ToolchainInputs& in, std::string_view name) { auto it = in.env.find(name); return it == in.env.end() ? std::string_view{} : std::string_view(it->second); @@ -76,97 +43,6 @@ namespace { while (!s.empty() && (s.back() == '\n' || s.back() == '\r' || s.back() == ' ')) s.pop_back(); return s; } - - // `link` made a symbolic link to `target`, or found one already. Another - // crafter-build may make the same link at the same moment, which is as - // good as making it; a link to anything else is an error. - void EnsureSymlink(const fs::path& target, const fs::path& link) { - std::error_code ec; - if (fs::read_symlink(link, ec) == target) return; - fs::create_directories(link.parent_path()); - fs::create_directory_symlink(target, link, ec); - std::error_code ignored; - if (ec && fs::read_symlink(link, ignored) != target) { - throw fs::filesystem_error("cannot make a link", target, link, ec); - } - } - - // `dir` made absolute and spelled one way, once, when the toolchain is - // resolved. The mingw prefix ends up as the target of links and in the - // names of build and cache directories: a relative path read later from - // another working directory would name something else, and /opt/mingw/ - // next to /opt/mingw would rebuild everything for the same directory. - fs::path PrefixPath(const fs::path& dir) { - fs::path normal = fs::absolute(dir).lexically_normal(); - if (!normal.has_filename() && normal.has_relative_path()) normal = normal.parent_path(); - return normal; - } - - // A regular file someone may run, as the shell's PATH lookup wants one. - bool IsProgram(const fs::path& file) { - std::error_code ec; - if (!fs::is_regular_file(file, ec)) return false; - constexpr fs::perms Exec = fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec; - return (fs::status(file, ec).permissions() & Exec) != fs::perms::none; - } - - // `path`, as the host names it, where this process finds it. A sandbox - // shows the host's /usr and /etc, and the directories beside them its - // own runtime has (bin, sbin, lib, lib64), under hostRoot, and - // everything else, /opt and /home among it, where the host has it. A - // link to an absolute path names the host's path wherever the link is, - // and the sandbox would look it up in its own root instead: NVIDIA's - // /usr/local/cuda is a link, to /usr/local/cuda- or through - // /etc/alternatives, and an /opt/cuda can be one to such a directory. - // So where the path is a link, it is followed here, and so is its - // target where that is one, each taken as the host's. Outside a - // sandbox, `path` itself. - fs::path HostPath(fs::path path, const fs::path& hostRoot) { - if (hostRoot.empty()) return path; - fs::path shown = path; - // As many links as the kernel follows before it gives up on a loop. - for (std::int32_t hops = 0; hops < 40; ++hops) { - if (!path.is_absolute()) return path; - // Without a trailing separator, which has readlink follow the - // link instead of reading it. - path = path.lexically_normal(); - if (!path.has_filename() && path.has_relative_path()) path = path.parent_path(); - const fs::path relative = path.relative_path(); - const fs::path top = relative.empty() ? fs::path() : *relative.begin(); - const bool underHostRoot = top == "usr" || top == "etc" || top == "bin" || top == "sbin" || top == "lib" || top == "lib64"; - shown = underHostRoot ? hostRoot / relative : path; - std::error_code ec; - const fs::path target = fs::read_symlink(shown, ec); - if (ec) return shown; - path = target.is_absolute() ? target : (path.parent_path() / target).lexically_normal(); - } - // Still a link after all of them: a loop, which opens as nothing. - return shown; - } - - // The view MingwSysroot() made and the prefix it shows, for - // MingwViewToPrefix. Written once, before ViewMade is set. - fs::path MadeView; - fs::path ViewedPrefix; - std::atomic ViewMade = false; -} - -fs::path Toolchain::InstalledClangxx(std::string_view command) const { - // Every word of the command, as clang's driver.cpp reads its arguments - // before it names its own path; the build quotes neither flag. - bool canonical = true; - for (std::size_t at = 0; at < command.size();) { - const std::size_t end = std::min(command.find(' ', at), command.size()); - const std::string_view word = command.substr(at, end - at); - if (word == "-canonical-prefixes") { - canonical = true; - } else if (word == "-no-canonical-prefixes") { - canonical = false; - } - at = end + 1; - } - const fs::path& dir = canonical ? installedDir : installedDirAsWritten; - return dir.empty() ? clangxx : dir / clangxx.filename(); } std::string Toolchain::LibcxxCompileFlags() const { @@ -174,27 +50,20 @@ std::string Toolchain::LibcxxCompileFlags() const { return std::format(" -nostdinc++ -isystem {}", (libcxxDir / "include" / "c++" / "v1").string()); } -// clang searches its per-target runtime directory and the system library -// paths for -lc++, not /lib, so a toolchain outside /usr with the -// classic layout needs the search path as well as the run-time path. -fs::path Toolchain::LibcxxLibDir() const { - if (!libcxxDir.empty()) return libcxxDir / "lib"; - if (!prefix.empty() && prefix != "/usr") return prefix / "lib"; - return {}; -} - std::string Toolchain::LibcxxLinkFlags() const { - const fs::path lib = LibcxxLibDir(); + // clang searches its per-target runtime directory and the system library + // paths for -lc++, not /lib, so a toolchain outside /usr with the + // classic layout needs the search path as well as the run-time path. + fs::path lib; + if (!libcxxDir.empty()) { + lib = libcxxDir / "lib"; + } else if (!prefix.empty() && prefix != "/usr") { + lib = prefix / "lib"; + } if (lib.empty()) return {}; return std::format(" -L{} -Wl,-rpath,{}", lib.string(), lib.string()); } -std::string Toolchain::LibcxxSearchFlags() const { - const fs::path lib = LibcxxLibDir(); - if (lib.empty()) return {}; - return std::format(" -L{}", lib.string()); -} - std::string Toolchain::Key() const { std::string identity; for (const std::string& part : {clangxx.string(), clangVersion, libcxxDir.string(), stdCppm.string()}) { @@ -224,14 +93,10 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { tc.clangxx = "clang++"; tc.clang = "clang"; tc.llvmAr = "llvm-ar"; - tc.llvmReadelf = "llvm-readelf"; - tc.clangScanDeps = "clang-scan-deps"; } else { tc.clangxx = tc.prefix / "bin" / "clang++"; tc.clang = tc.prefix / "bin" / "clang"; tc.llvmAr = tc.prefix / "bin" / "llvm-ar"; - tc.llvmReadelf = tc.prefix / "bin" / "llvm-readelf"; - tc.clangScanDeps = tc.prefix / "bin" / "clang-scan-deps"; if (tc.prefix != "/usr" && fs::exists(tc.prefix / "include" / "clang-c" / "Index.h")) { tc.llvmIncludeDir = tc.prefix / "include"; } @@ -271,112 +136,12 @@ Toolchain Crafter::ResolveToolchain(const ToolchainInputs& in) { tc.wasiSysroot = "/usr/share/wasi-sysroot"; } if (std::string_view dir = Env(in, "CRAFTER_MINGW_DIR"); !dir.empty()) { - tc.mingwPrefix = PrefixPath(fs::path(dir)); - // A prefix that holds a Linux system as well as mingw-w64, /usr - // itself, has that system's C library in include/: features.h, which - // every glibc and musl header includes and mingw-w64 has no use for. - // One that holds mingw-w64 alone stays the sysroot, so Windows - // libraries installed into its include/ and lib/ stay visible. - tc.mingwPrefixIsSystem = fs::exists(tc.mingwPrefix / "include" / "features.h"); + tc.mingwSysroot = fs::path(dir); } else if (!in.hostRoot.empty() && fs::exists(in.hostRoot / "usr" / "x86_64-w64-mingw32")) { // The sandbox has no mingw-w64 of its own, and no mingw gcc on PATH - // for clang to find one by. The host's /usr is the host's system, - // whether or not its C library's headers are installed. - tc.mingwPrefix = PrefixPath(in.hostRoot / "usr"); - tc.mingwPrefixIsSystem = true; + // for clang to find one by. + tc.mingwSysroot = in.hostRoot / "usr"; } - - // 5. nvcc, for cfg.cuda. CUDA_PATH is exclusive, as CRAFTER_BUILD_LLVM_DIR - // is: it names the toolkit, and one without nvcc is an error rather - // than a reason to use another. PATH is searched here, not by the - // shell: in crafter-build's Flatpak it is /app/bin:/usr/bin, which - // never holds the host's toolkit, and every CUDA build there stopped - // at "nvcc: command not found", which named no place to put one. - if (std::string_view cudaPath = Env(in, "CUDA_PATH"); !cudaPath.empty()) { - // Absolute and spelled one way, once, as CRAFTER_MINGW_DIR is: nvcc - // runs later, from whatever working directory a build is in. - const fs::path named = PrefixPath(fs::path(cudaPath)); - if (const fs::path nvcc = HostPath(named, in.hostRoot) / "bin" / "nvcc"; IsProgram(nvcc)) { - tc.nvcc = nvcc; - } else { - tc.nvccError = std::format("no nvcc at {} (CUDA_PATH)", (named / "bin" / "nvcc").string()); - } - } else { - std::vector lookedAt; - for (const fs::path& root : in.cudaRoots) { - if (const fs::path nvcc = HostPath(root, in.hostRoot) / "bin" / "nvcc"; IsProgram(nvcc)) { - tc.nvcc = nvcc; - break; - } - lookedAt.push_back((root / "bin" / "nvcc").string()); - } - const std::string_view path = Env(in, "PATH"); - for (std::size_t at = 0; tc.nvcc.empty() && at <= path.size();) { - std::size_t end = path.find(':', at); - if (end == std::string_view::npos) end = path.size(); - // An empty or a relative entry names a directory under whatever - // the working directory is, and this lookup is made once per - // process: only an absolute one names a place. - if (const std::string_view dir = path.substr(at, end - at); fs::path(dir).is_absolute() && IsProgram(fs::path(dir) / "nvcc")) { - tc.nvcc = fs::path(dir) / "nvcc"; - } - at = end + 1; - } - if (tc.nvcc.empty()) { - lookedAt.push_back(std::format("nvcc on PATH ({})", path.empty() ? std::string_view("unset") : path)); - std::string places = lookedAt.front(); - for (std::size_t i = 1; i < lookedAt.size(); ++i) places += std::format("{}{}", i + 1 == lookedAt.size() ? " and " : ", ", lookedAt[i]); - tc.nvccError = std::format("no CUDA toolkit found: looked for {}; set CUDA_PATH to the directory a toolkit is installed in", places); - } - } - // What VariantId keys a CUDA configuration's nvcc by. Its path stays - // when the toolkit behind it is updated, by a package at /opt/cuda or by - // /usr/local/cuda pointed at another release, and the objects the old - // nvcc compiled would be kept. The binary's canonical path, size and - // time change with it, and reading them starts no process. - if (!tc.nvcc.empty()) { - std::error_code ec; - fs::path real = fs::canonical(tc.nvcc, ec); - if (ec) real = tc.nvcc; - const std::uintmax_t size = fs::file_size(real, ec); - const auto time = fs::last_write_time(real, ec).time_since_epoch().count(); - tc.nvccStamp = std::format("{}|{}|{}", real.string(), size, time); - } - // What VariantId keys -arch=native by: nvcc compiles it for the GPUs it - // finds, so a GPU of another model, the same GPUs in each other's slots, - // or CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER choosing another or, - // empty, none, has to build in a directory of its own, where the word - // alone would keep an object compiled for the old GPU, with no PTX for the - // new one. The NVIDIA display devices (class 0x03) by PCI address and - // device ID, in the order of their addresses, from sysfs, which starts no - // process; an entry that cannot be read counts as none, and nothing here - // throws. It is crafter-build's reading of the machine, not nvcc's: a - // change it cannot see, such as a GPU bound to another driver, keeps the - // key. - if (!tc.nvcc.empty()) { - std::vector gpus; - std::error_code ec; - for (fs::directory_iterator it(in.pciDevices, ec), end; !ec && it != end; it.increment(ec)) { - const auto field = [&it](std::string_view name) { - std::string value; - std::ifstream(it->path() / name) >> value; - return value; - }; - if (field("vendor") == "0x10de" && field("class").starts_with("0x03")) gpus.push_back(std::format("{}={}", it->path().filename().string(), field("device"))); - } - std::ranges::sort(gpus); - const auto spelled = [](const std::optional& value) { return value ? std::format("={}", *value) : std::string("unset"); }; - tc.cudaNativeKey = std::format("{}|{}|{}", std::views::join_with(gpus, std::string(",")) | std::ranges::to(), spelled(in.cudaVisibleDevices), spelled(in.cudaDeviceOrder)); - } - // The static runtime beside that nvcc, for the link of a configuration - // with CUDA sources. Looked for without throwing: a lib64 that cannot be - // looked into, through a link loop or for want of permission, counts as - // one without it. - if (!tc.nvcc.empty()) { - const fs::path archive = tc.nvcc.parent_path().parent_path() / "lib64" / "libcudart_static.a"; - if (std::error_code ec; fs::exists(archive, ec)) tc.cudaRuntime = archive; - } - std::tie(tc.flatpakArch, tc.flatpakBranch) = FlatpakRuntimeOf(in.flatpakInfo); return tc; } @@ -394,17 +159,6 @@ const Toolchain& Crafter::GetToolchain() { in.crafterPrefix = GetCrafterBuildHome().parent_path().parent_path(); } catch (const std::exception&) {} if (fs::exists("/.flatpak-info")) in.hostRoot = "/run/host"; - in.cudaRoots = { "/opt/cuda", "/usr/local/cuda" }; - in.pciDevices = "/sys/bus/pci/devices"; - if (const char* value = std::getenv("CUDA_VISIBLE_DEVICES")) in.cudaVisibleDevices = value; - if (const char* value = std::getenv("CUDA_DEVICE_ORDER")) in.cudaDeviceOrder = value; - { - auto it = in.env.find("CRAFTER_BUILD_FLATPAK_INFO"); - const fs::path info = it != in.env.end() ? fs::path(it->second) : fs::path("/.flatpak-info"); - if (std::ifstream file(info, std::ios::binary); file) { - in.flatpakInfo.assign(std::istreambuf_iterator(file), std::istreambuf_iterator()); - } - } Toolchain tc = ResolveToolchain(in); if (!tc.error.empty()) return tc; @@ -416,22 +170,11 @@ const Toolchain& Crafter::GetToolchain() { return tc; } tc.hostTriple = Trimmed(std::move(triple.output)); - // The InstalledDir line of a `--version` run; empty where the run - // failed or printed none. - const auto installedDirOf = [](const CommandResult& run) { - constexpr std::string_view InstalledDirLine = "\nInstalledDir: "; - const std::size_t at = run.output.find(InstalledDirLine); - if (run.exitCode != 0 || at == std::string::npos) return fs::path(); - const std::size_t begin = at + InstalledDirLine.size(); - return fs::path(Trimmed(run.output.substr(begin, run.output.find('\n', begin) - begin))); - }; CommandResult version = RunCommandChecked(std::format("{} --version", tc.clangxx.string())); if (version.exitCode == 0) { std::string first = version.output.substr(0, version.output.find('\n')); tc.clangVersion = Trimmed(std::move(first)); } - tc.installedDir = installedDirOf(version); - tc.installedDirAsWritten = installedDirOf(RunCommandChecked(std::format("{} -no-canonical-prefixes --version", tc.clangxx.string()))); return tc; }(); return Resolved; @@ -443,69 +186,6 @@ const Toolchain& Crafter::RequireToolchain() { return tc; } -fs::path Crafter::MakeMingwSysroot(const fs::path& prefix, std::span parents) { - std::string reasons; - for (const fs::path& parent : parents) { - // One view per prefix: two shells with different CRAFTER_MINGW_DIRs - // share one cache and would otherwise rewrite each other's. - const fs::path sysroot = parent / "mingw-sysroot" / std::format("{:016x}", std::hash{}(prefix.string())); - try { - // All clang's mingw driver takes from a sysroot other than its - // include/ and the rest of its lib/: the mingw-w64 tree (headers, - // libraries, and libstdc++ where a distro's cross gcc installs - // it) and gcc's per-target directory (crtbegin.o, libgcc, and the - // version that names libstdc++'s header directory), which - // openSUSE keeps under lib64. A link to nothing is skipped like a - // missing directory. - for (std::string_view entry : {"x86_64-w64-mingw32", "lib/gcc", "lib64/gcc"}) { - EnsureSymlink(prefix / entry, sysroot / entry); - } - return sysroot; - } catch (const std::exception& e) { - reasons += std::format("; {}", e.what()); - } - } - throw std::runtime_error(std::format("cannot make a sysroot that shows clang only the mingw-w64 parts of {}{}", prefix.string(), reasons)); -} - -const fs::path& Crafter::MingwSysroot() { - // Made on first use rather than by GetToolchain(), so that only what - // compiles for the mingw target, a build or an AST lint of one, writes - // anything for it, and a failure surfaces as that command's error - // instead of on every command. - static const fs::path Sysroot = []() -> fs::path { - const Toolchain& tc = GetToolchain(); - if (!tc.mingwPrefixIsSystem) return tc.mingwPrefix; - // In the cache, or where the XDG spec promises symbolic links when - // the cache's filesystem takes none (vfat, exFAT, CIFS without unix - // extensions), which costs nothing else crafter-build caches. - // Absolute, because CMake runs the compiler from directories of its - // own. - std::vector parents = { fs::absolute(GetCacheDir()) }; - if (const char* runtime = std::getenv("XDG_RUNTIME_DIR"); runtime && *runtime) { - parents.push_back(fs::absolute(fs::path(runtime) / "crafter.build")); - } - fs::path view = MakeMingwSysroot(tc.mingwPrefix, parents); - MadeView = view; - ViewedPrefix = tc.mingwPrefix; - ViewMade.store(true, std::memory_order_release); - return view; - }(); - return Sysroot; -} - -std::string Crafter::MingwViewToPrefix(std::string text) { - if (!ViewMade.load(std::memory_order_acquire)) return text; - // With the separator, so a --sysroot= naming the view itself, in a - // command line the output quotes, stays what was run. - const std::string view = (MadeView / "").string(); - const std::string prefix = (ViewedPrefix / "").string(); - for (std::size_t at = text.find(view); at != std::string::npos; at = text.find(view, at + prefix.size())) { - text.replace(at, view.size(), prefix); - } - return text; -} - std::int32_t Crafter::LibcxxVersion(const fs::path& includeDir) { // "# define _LIBCPP_VERSION 230102", the one place libc++ states its // release in a form the preprocessor does not have to be run for. diff --git a/interfaces/Crafter.Build-Agents.cppm b/interfaces/Crafter.Build-Agents.cppm index 1660526..77e3c4e 100644 --- a/interfaces/Crafter.Build-Agents.cppm +++ b/interfaces/Crafter.Build-Agents.cppm @@ -7,17 +7,10 @@ namespace fs = std::filesystem; // Dependency notes. A crafter-build project ships an AGENTS.consumer.md beside // its project.cpp, written for the agents of the projects that depend on it, -// and crafter-build merges those files into each consumer's AGENTS.md. Without +// and crafter-build keeps those files in each consumer's AGENTS.md. Without // that, an agent working on a consumer knows nothing about the libraries it // builds against unless someone copied the knowledge in by hand, and a copy // goes stale the moment the library changes. -// -// The consumer writes its own instructions in an AGENTS.template.md beside its -// project.cpp, and every build writes AGENTS.md from that, so AGENTS.md is -// build output and stays out of version control. Kept in a committed -// AGENTS.md instead, as they once were, the notes changed that file whenever -// a dependency changed its own, on builds that changed nothing else, and -// every diff and rebase carried changes nobody had made. export namespace Crafter { struct Configuration; @@ -30,7 +23,7 @@ export namespace Crafter { // Only the projects this one's own configurations and // `#pragma crafter dependency` lines name. Direct, - // None: AGENTS.md holds the template's text alone. + // None. A section an earlier build wrote is removed. None, }; @@ -41,57 +34,39 @@ export namespace Crafter { std::string name; // The file's content, without leading blank lines or trailing // whitespace. Lines end in LF; the merge writes the line ending the - // template uses. + // document uses. std::string text; }; - // `templateMd` with its dependency notes section holding `notes`, in - // order: AGENTS.md as it reads below the line that says a build wrote it. - // A template without a section gets one appended after a blank line; one - // with a section, which is how a template places it, has it rewritten - // where it stands, whatever it held; and empty `notes` remove it. - // Removing a section that ends the template takes the blank line in front - // of it too, so the result ends as the text before it did. The section - // uses the template's line ending, so a CRLF file stays CRLF. + // `agentsMd` with its dependency notes section holding `notes`, in order. + // A document without a section gets one appended after a blank line; one + // with a section has it rewritten in place, wherever it was moved to; and + // empty `notes` remove it. Removing a section that ends the document takes + // the blank line in front of it too, so a document that ended in a newline + // before it gained the section gets its own bytes back. The section uses + // the document's line ending, so a CRLF file stays CRLF. // // The two marker lines count only as whole lines outside fenced code // blocks, which is what lets a document quote them. Throws, naming the // line, when there are notes to write and the markers are unbalanced, or - // when the section would have to be appended to a template that ends - // inside a code block: a lone or doubled marker is a slip in the - // template, and any guess at what it meant would put the notes, or cut - // the text, where its author did not, while notes appended inside a code - // block would read as code. With no notes it never throws, since nothing - // has to be placed. Also throws for a note that would break the section - // for whoever reads it: one with a marker line of its own, or a code - // block it never closes. - std::string MergeDependencyNotes(std::string_view templateMd, std::span notes); + // when the section would have to be appended to a document that ends + // inside a code block: guessing which part of someone's file is generated + // would overwrite their text, and missing the section would add another on + // every build. With no notes it never throws, since leaving the document + // alone loses nothing. Also throws for a note that would break the section + // when it is read back: one with a marker line of its own, or a code block + // it never closes. + std::string MergeDependencyNotes(std::string_view agentsMd, std::span notes); - // Write the AGENTS.md beside `projectFile` from the AGENTS.template.md - // beside it, with the AGENTS.consumer.md of every dependency - // project.dependencyNotes selects merged in. `project` is the - // Configuration that file returned, once it is loaded: loading is what - // found the dependencies. Creates AGENTS.md when it is missing, and - // replaces only one a build wrote: an AGENTS.md someone wrote is left - // alone, with a warning. Without a template it writes nothing, and only - // warns about a section an earlier crafter-build left in AGENTS.md. - // Writes only when the text changes, in place, so hard links, ownership - // and a read-only AGENTS.md are respected; returns whether it wrote. A - // read or write that fails, a template the notes cannot be placed in and + // Refresh the dependency notes section of the AGENTS.md beside + // `projectFile` from the AGENTS.consumer.md of every dependency + // project.dependencyNotes selects. `project` is the Configuration that + // file returned, after LoadProject: loading is what found the + // dependencies. Does nothing when there is no AGENTS.md, which is never + // created. Writes only when the text changes, in place, so hard links, + // ownership and a read-only AGENTS.md are respected; returns whether it + // wrote. A read or write that fails, a section that cannot be placed and // a dependency's unusable notes are warnings: the notes never fail a // build, and nothing is reported when nothing would have been written. bool UpdateAgentsMd(const Configuration& project, const fs::path& projectFile); - // The same for a project file that returned several configurations. - // Each one the file made itself selects, by its dependencyNotes, among - // the projects that one is built against, and the notes are merged: a - // dependency's are in when a configuration that asks for them leads to - // it. The file's `#pragma crafter dependency` lines, and a - // configuration it loaded from another project and returns, which - // counts as a dependency here, go by the widest of those settings, and - // by Transitive when the file made no configuration itself. A - // configuration is another project's when GitProject or LocalProject - // loaded it from another project file than `projectFile`, two files - // being one when they resolve to one path: one they loaded from - // `projectFile` itself is that file's own. - bool UpdateAgentsMd(std::span configurations, const fs::path& projectFile); } diff --git a/interfaces/Crafter.Build-Clang.cppm b/interfaces/Crafter.Build-Clang.cppm index 3693d6a..0797e88 100644 --- a/interfaces/Crafter.Build-Clang.cppm +++ b/interfaces/Crafter.Build-Clang.cppm @@ -9,7 +9,6 @@ import :Implementation; import :External; import :Toolchain; import :Agents; -import :Flatpak; namespace fs = std::filesystem; namespace Crafter { @@ -49,35 +48,11 @@ export namespace Crafter { // recorded last time, so they come out the same however the // dependency threads that fill them happen to finish. std::set 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 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 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 runPaths; - // The configuration this is the build of: the one whose Build() ran. - // A build pass builds a directory once, so of two configurations - // that would be built into one, as the same project loaded along two - // paths with its args in two orders is, only one is built, and only - // that one has the modules the build read in the sources - // (Configuration::interfaces). What is built on the other finds them - // through this. Null where Build() stopped before it read the - // sources. - const struct Configuration* built = nullptr; }; struct Define { @@ -108,25 +83,6 @@ export namespace Crafter { 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 { @@ -176,11 +132,6 @@ export namespace Crafter { std::int32_t signal = 0; std::chrono::milliseconds duration{0}; std::string output; - // What the headless compositor of a test that sets Test::wayland - // printed, kept when the test ran and failed, crashed or timed out, - // for RunTests to write beside the test's own log. A compositor that - // did not start has what it printed in `output`. - std::string compositorLog; }; // One lint diagnostic. Produced by LintContext::Report — or derived by @@ -441,24 +392,13 @@ export namespace Crafter { }; 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 ` // 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. + // The Configuration project.cpp returned. Read the project through + // this rather than capturing the local in CrafterBuildProject by + // reference: that local is gone by the time a script runs. Configuration& project; // Absolute directory of the project file. Commands run in the // directory crafter-build was started from, like everything else it @@ -516,47 +456,10 @@ export namespace Crafter { 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; - // The module interface units (.cppm) and the implementation units - // (.cpp) of the configuration, as GetInterfacesAndImplementations - // lists them: absolute, with their extensions. - std::vector interfaceSources; - std::vector implementationSources; - // What those sources are, as Build() found them the last time it read - // all of them without an error: each module whose primary interface - // unit is among interfaceSources, with its partitions, and a unit for - // each of implementationSources, with what each of them imports. - // Build() takes what a source declares and imports from - // clang-scan-deps, which preprocesses the source with the command it - // is compiled with, so it reads them as the compiler does: one in a - // string literal, in a comment or in a branch that #if leaves out is - // not there. It reads them once the configuration's dependencies and - // external dependencies are built, since the command takes their - // include paths and a source may include their headers. Empty until a - // Build() has read the sources. A pass builds a directory once, so a - // configuration whose directory it built for another keeps what it - // had, and what is built on it finds the modules of that build - // through BuildResult::built. std::vector> interfaces; std::vector implementations; std::vector cFiles; std::vector 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 dependencies; std::vector files; // Build-time-only source files this configuration exposes to its own @@ -626,29 +529,28 @@ export namespace Crafter { // Not part of VariantId: a script changes nothing that is compiled. std::vector