# Languages

---

# Building C

_Pekit / Languages_

> Compile, archive, and link C programs and static libraries with the gcc library, give each compile exactly its headers, and build with Bootlin's pinned compilers for the host or for aarch64.

The gcc library builds C programs and static libraries. Each of its
functions is one step, so pekit reruns only the compiles whose sources or
headers changed. Import it as `github.com/gcslib/gcc`.

## Before you start

- The gcc library. See [Libraries](/pekit/libraries/libraries.md) for how pekit finds
  one.
- Optional: Bootlin's pinned compilers registered in `pekitconf`. Without
  them, the library uses the host's `cc`.

## Build a program

1. In a build file, compile each source and link the objects:

   ```gcsl
   import "github.com/gcslib/gcc"

   def build hello() {
       = gcc.link([gcc.compile(file("hello.c"))], output = "hello")
   }
   ```

2. Build it:

   ```sh
   pekit build hello
   ```

## Check the result

pekit prints the program's path, `pekit-out/hello/link/hello`. Run it.

## The library's functions

The library has three steps:

| Function | Makes |
|---|---|
| `compile(src, headers, output, flags)` | The object of one C source, by default its name with `.o` for `.c`. |
| `archive(objs, output)` | A static library of objects, by `ar rcsD`, with no times or owners recorded. |
| `link(objs, libraries, output, flags)` | A program of objects and static libraries. |

`flags` go to the compiler as they are. `output` names the file the step
makes.

## Give each compile its headers

A compile's sandbox holds its source and the `headers` you give it, and
nothing else of the workspace. pekit passes each header's directory to the
compiler with `-I`. Give a compile exactly the headers it includes:

- A header it includes but isn't given fails the compile.
- A header it's given but doesn't include reruns it for nothing when the
  header changes.

## Build a library and a program that uses it

A library target can give its archive and its public headers together, so
that a program compiles against the public headers alone:

```gcsl
import "github.com/gcslib/gcc"

def build greet() {
    let obj = gcc.compile(file("lib/greet.c"), headers = [file("lib/greet.h"), file("lib/internal.h")])
    archive = gcc.archive([obj], output = "libgreet.a")
    headers = [file("lib/greet.h")]
}

def build app() {
    let g = build greet()
    let obj = gcc.compile(file("main.c"), headers = g.headers)
    = gcc.link([obj], libraries = [g.archive], output = "app")
}
```

Editing `lib/internal.h` reruns the library's compile, its archive, and the
link, but never the program's compile, which wasn't given that header.

## Build with pinned compilers

The gcc library defines toolchains of Bootlin's compilers. Each is fetched
by its SHA-256 digest and unpacked once, and its compiler runs in a sandbox
whose root is the toolchain's own runtime. A build with them reads nothing
of the host's compiler or libraries. Register them in `workspace.gcsl`:

```gcsl
import Toolchain::* from "github.com/gcslib/gcc"
import Toolchain from toolchain

pekitconf = {toolchains = [
    Toolchain::C gcc_x86_64,
    Toolchain::C gcc_x86_64_to_aarch64,
]}
```

The toolchains are:

| Toolchain | Runs on | Builds for |
|---|---|---|
| `gcc_x86_64` | x86-64 Linux | x86-64 Linux, with glibc |
| `gcc_x86_64_to_aarch64` | x86-64 Linux | aarch64 Linux, with glibc |

`gcc_x86_64_musl()` gives a Bootlin toolchain that builds for x86-64 Linux
with musl. It isn't registered, but a library can pass it to a step, as
the rust library does for static musl programs.

With both registered, `pekit build --platform aarch64 hello` builds the
program for aarch64. See [Building for Another
Platform](/pekit/building/building-for-another-platform.md).

## Tools built during the build

A program the build makes and then runs, such as a code generator, is a
file like any other: pass it to the step that runs it. Build it for the
machine steps run on, and link it statically, so that it runs in a step's
sandbox with nothing of the toolchain that built it:

```gcsl
def build embed() {
    = gcc.link([gcc.compile(file("gen/embed.c"))], output = "embed", flags = ["-static"])
}

def build app() {
    let tool = build embed() with { platform = ^host_platform }
    # Runs the tool in a step, then compiles what it wrote.
}
```

---

# Building Upstream Software

_Pekit / Languages_

> Build software that has its own build system, such as ./configure and make, as one step with the buildenv library, in a pinned environment or with the host's tools.

Code from elsewhere usually comes with its own build system. The buildenv
library runs one as a single step: `configure_make` runs `./configure`,
`make`, and `make install` on a source directory, and gives the directory
the build installed into. Import it as `github.com/gcslib/buildenv`.

## Before you start

- The buildenv and gcc libraries. See [Libraries](/pekit/libraries/libraries.md).
- A C toolchain and a build environment registered in `pekitconf`. This page
  registers pinned ones.

## Build zlib from source

1. Register a C toolchain and a build environment in `workspace.gcsl`:

   ```gcsl
   import Toolchain::* from "github.com/gcslib/gcc"
   import Toolchain::* from "github.com/gcslib/buildenv"
   import Toolchain from toolchain

   pekitconf = {toolchains = [Toolchain::C gcc_x86_64, Toolchain::BuildEnv busybox_x86_64]}
   ```

   `busybox_x86_64` gives `/bin/sh` and the usual tools from a static
   busybox, and GNU make built from its pinned source, all fetched by their
   digests.

2. In a build file, fetch and unpack the source, and build it:

   ```gcsl
   import unpack from archive
   import "github.com/gcslib/buildenv"

   def build zlib() {
       let src = unpack(fetch("https://zlib.net/fossils/zlib-1.3.1.tar.gz", sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23"))
       let out = buildenv.configure_make(src.dir("zlib-1.3.1"), configure = ["--static"])
       headers = [out.file("include/zlib.h"), out.file("include/zconf.h")]
       archive = out.file("lib/libz.a")
   }
   ```

   `configure` words go to `./configure` after `--prefix`, and `make`
   words go to `make`. Each word is one argument, as written.

3. Build it:

   ```sh
   pekit build zlib
   ```

## Check the result

pekit prints the paths of the two headers and `libz.a`, in the directory
the build installed into. The target gives them in the same shape as the
gcc library's own libraries, so a program can compile against `headers`
and link `archive`.

## What the step does

The build runs with the registered C toolchain, given to it as `CC`, `AR`,
`RANLIB`, `OBJCOPY`, and `LD`, in the registered build environment. The
step copies the source to a writable directory first, as a build system
expects. Every path is the same on every run, so anything the build
records, such as its install prefix, doesn't change from one run to the
next. Each static archive it installs is made deterministic with
`objcopy -D`, so the same source gives the same archive.

pekit can't see inside the step, so any change to the source rebuilds all
of it.

## Use the host's tools

To build with the host's own compiler and tools instead, register
`host_tools` from the buildenv library and `system_c` from the `toolchain`
module:

```gcsl
import Toolchain::BuildEnv host_tools from "github.com/gcslib/buildenv"
import * from toolchain

pekitconf = {toolchains = [Toolchain::C system_c, Toolchain::BuildEnv host_tools]}
```

The step then runs in its own sandbox with the host's tools, and a strict
build refuses it.

---

# Building Python

_Pekit / Languages_

> Check Python sources and bundle a program and its libraries into one runnable archive with the python library, using a pinned CPython or the host's.

The python library builds a Python program into one file, an archive that
`python3 app.pyz` runs. It checks that each source compiles, as a step of
its own, so changing one file rechecks only that file. Import it as
`github.com/gcslib/python`.

## Before you start

- The python library. See [Libraries](/pekit/libraries/libraries.md).
- A Python interpreter registered in `pekitconf`. This page registers the
  library's pinned CPython.

## Build a program

1. Register an interpreter in `workspace.gcsl`:

   ```gcsl
   import Toolchain::Python python_3_14 from "github.com/gcslib/python"
   import Toolchain from toolchain

   pekitconf = {toolchains = [Toolchain::Python python_3_14]}
   ```

2. In a build file, declare a library for each group of sources, and a
   binary for the program:

   ```gcsl
   import "github.com/gcslib/python"

   def build words() {
       = python.library([file("words/words.py")])
   }

   def build greet() {
       = python.library([file("greet/greet.py")], deps = [build words()])
   }

   def build app() {
       = python.binary(file("app/__main__.py"), deps = [build greet()], output = "app.pyz")
   }
   ```

3. Build the program:

   ```sh
   pekit build app
   ```

## Check the result

Run the archive pekit printed with `python3`. It holds `app/__main__.py`
as its `__main__.py`, and the sources of `greet` and `words` beside it.

## Libraries and binaries

`python.library(srcs, deps)` gives a `python.Library`: its own sources,
and every source of its dependencies, all the way down. `app` depends on
`greet` alone, and still gets `words`.

`python.binary(main, deps, output)` bundles `main`, as `__main__.py`, and
every source of its dependencies into one archive, each at the top by its
name. Two different sources with one name are an error. A library reached
by two paths is bundled once.

The archive's entries are sorted and carry a fixed date, so the same
sources always give the same bytes. A step that uses the archive reruns
only when a source really changed.

## Interpreters

The library asks the `toolchain` module for a `Toolchain::Python`. It
defines two:

| Toolchain | Is |
|---|---|
| `python_3_14` | CPython 3.14 from python-build-standalone, pinned by its SHA-256, running in a sandbox whose root is the gcc library's Bootlin runtime. A build with it reads nothing of the host's Python. |
| `system_python` | The host's own `python3`, found on `PATH`. |

---

# Building Rust

_Pekit / Languages_

> Build Rust programs hermetically from the crates Cargo.lock pins with the rust library, one crate at a time or with Cargo whole, including tests, git crates, C dependencies, bindgen, control-flow protection, and the pinned Rust toolchain.

The rust library builds Rust programs from the crates your `Cargo.lock`
pins, with no network and nothing of the host. It builds a Cargo workspace
one crate at a time, as Bazel's Rust rules do, or whole, as Cargo does.
Import it as `github.com/gcslib/rust`.

## Before you start

- The rust, gcc, buildenv, and python libraries. See [Libraries](/pekit/libraries/libraries.md).
- A Cargo workspace with a `Cargo.lock`.

## Register the toolchain

The library asks the `toolchain` module for a `Toolchain::Rust`. Its
`rust_1_98` is Rust 1.98.1 from static.rust-lang.org, each part pinned by
its SHA-256, with the standard libraries for `x86_64-unknown-linux-gnu` and
`x86_64-unknown-linux-musl`, and their source, `rust-src`. It runs on the
gcc library's Bootlin sysroot and links with its compiler. Register both in
`workspace.gcsl`:

```gcsl
import Toolchain::C gcc_x86_64 from "github.com/gcslib/gcc"
import Toolchain::Rust rust_1_98 from "github.com/gcslib/rust"
import Toolchain from toolchain

pekitconf = {toolchains = [Toolchain::C gcc_x86_64, Toolchain::Rust rust_1_98]}
```

rustc needs zlib, which the sysroot lacks. The toolchain builds zlib from
its pinned source with the buildenv library's pinned environment, so a
first build takes longer.

## Build one crate at a time

1. Plan the workspace with `rust.workspace`, then build what you need of
   it:

   ```gcsl
   import "github.com/gcslib/rust"

   fn crates() -> rust.RustWorkspace {
       = rust.workspace(dir("."), rust.vendored(file("Cargo.lock")))
   }

   def build server() {
       = rust.bin(crates(), "server")
   }

   def build client_library() {
       = rust.library(crates(), "client")
   }
   ```

2. Build a program:

   ```sh
   pekit build server
   ```

`rust.bin(ws, package, name)` gives a member's program, by default the one
named after the member. `rust.library(ws, package)` gives its shared
library, and `rust.static_library(ws, package)` its static library. Give
each `features` to turn on the member's own features, as `cargo build
--features` does.

## Check the result

pekit prints the program's path. Change one source file and build again:
pekit compiles that file's crate, and the crates that depend on it, again,
and finds every other crate in the store.

## How planning works

Cargo plans the build: what each member needs, unit by unit, as `cargo
build --unit-graph` lists it. Each crate, with the features Cargo resolves
for the member you build, is compiled as a step of its own, and so is each
build script and each run of one. Two programs that use the same crate
with the same features share the one step.

Planning reads the manifests, `Cargo.lock`, and which files exist, never
what the sources say. Editing a source plans nothing again.

It leaves out files under a hidden directory, such as `.git` or `.claude`,
but `.cargo`, and under the paths that `workspace`'s `ignore` names,
relative to the workspace: by default `["target", "pekit-out"]`. Add any
other directory a build writes, such as `ignore = ["target", "pekit-out",
"docs/dist"]`, so that what it writes there doesn't plan the workspace
again. pekit never lists a nested checkout or a Git worktree inside the
workspace, a directory that holds a `.git` of its own, so an agent's
worktree under `crates/` isn't taken for a member. Planning doesn't read
`.gitignore`, and it still walks the directories that `ignore` names.

Features follow the member. A program built from a member that asks for a
crate's feature gets it, and a program from a member that doesn't never
does, even when you build both at once. Cargo unifies features across
everything one `cargo build` names; pekit plans each member on its own.
Give `workspace` `whole = true` to plan every member with the whole
workspace's features instead, as `cargo build --workspace` and `cargo test
--workspace` resolve them, so that a member's tests see what they see under
Cargo.

Cargo's plans leave out some of what it takes from the manifests: the
`[lints]` table, which targets have `harness = false`, and the `--check-cfg`
flags it gives every crate. The library reads each member's manifest for
them with the python library's pinned Python, and compiles the member's
crates with them, as Cargo does. Link-time optimization follows Cargo too:
the programs a profile's `lto` names are optimized whole, and the libraries
they link carry what that needs. A profile's `strip` applies as Cargo
applies it, so `strip = "symbols"` gives programs without symbols.

## Profiles

`workspace` plans for the Cargo profile `profile`, by default `release`:

```gcsl
fn crates() -> rust.RustWorkspace {
    = rust.workspace(dir("."), rust.vendored(file("Cargo.lock")), profile = "dev")
}
```

A profile is chosen as Cargo chooses it. `dev` builds as `cargo build`
does, and tests take the `test` profile, as under `cargo test`. `release`
builds as `--release` does. Any other profile, such as a `quick` profile
that your `Cargo.toml` defines, builds as `--profile quick` does. Each
crate is compiled with its profile's settings, `debug = "line-tables-only"`
and per-package overrides included.

A build script is told `PROFILE` as Cargo tells it: `release` for a
profile that inherits from `release`, and `debug` for one that inherits
from `dev`. pekit reads the chain of `inherits` from the workspace's
`Cargo.toml`. A profile that only `.cargo/config.toml` defines isn't
supported.

To set a profile as an environment variable would, give `profile_env`:

```gcsl
rust.workspace(
    dir("."),
    rust.vendored(file("Cargo.lock")),
    profile = "dev",
    profile_env = [{key = "CARGO_PROFILE_DEV_DEBUG"; value = "line-tables-only"}],
)
```

Each key has to start with `CARGO_PROFILE_`. Cargo plans with them set, so
they apply as they would to `cargo build`.

A profile's `rustflags`, which Cargo's unstable `profile-rustflags` feature
allows, apply as Cargo applies them, after the workspace's own flags.

## Control-flow protection

A program built one crate at a time for an x86-64 glibc target, such as
`x86_64-unknown-linux-gnu`, has Intel's control-flow protection (CET)
compiled in: indirect-branch tracking (IBT) and shadow stacks (SHSTK).

The linker marks a program with IBT and SHSTK only if every object it links
is marked. Upstream's prebuilt standard libraries aren't, so the rust
library compiles them again from the toolchain's `rust-src`:

- each crate is a step, as your own crates are, and every workspace that
  uses the same toolchain and target shares them;
- they have the features upstream's have, but `compiler_builtins`' C
  intrinsics, whose source `rust-src` doesn't include;
- they use the `dist` profile that upstream's use, so a crate compiled with
  link-time optimization still finds their bitcode;
- their source paths are `/rustc/COMMIT/library`, as upstream's are, so no
  path of the step's is in them.

Every crate compiled for the target is then compiled against them with
`-Zcf-protection=full`. C that a build script compiles through the `cc`
crate gets `-fcf-protection=full`, in `CFLAGS_<target>` and
`CXXFLAGS_<target>`. A package's `env` in `crates` can set those itself.

The first glibc build compiles the standard libraries, which takes a few
minutes. After that the store has them.

### Unstable flags on a stable Rust

`-Zcf-protection` is unstable, and the pinned Rust is stable. Only rustc is
told `RUSTC_BOOTSTRAP=1`, in the step that compiles a crate. Build scripts
aren't told it or the flags, so a build script that probes the compiler,
as autocfg does, finds the same stable compiler it would without them.
Build scripts and procedural macros run on the build machine, and are
compiled as before.

`RUSTC_BOOTSTRAP` isn't supported upstream, so a flag's behavior can change
between Rust versions. After updating the toolchain, check a program with
`readelf -n`.

### What glibc must provide

The program is marked only if the C library's own objects it links are
marked too: its start files, `Scrt1.o`, `crti.o` and `crtn.o`, and
`libc_nonshared.a`. The gcc library's Bootlin glibc isn't built with CET.
A program linked with `gcc_x86_64` is therefore not marked, even though
every object Rust compiles for it is. To see what isn't marked, link with
`-Clink-arg=-Wl,-z,cet-report=error` in `rustflags`, and the linker names
each object.

### Turning it off, and other targets

To use upstream's standard libraries without the flags, give `workspace`
`cet = false`.

A musl target never has control-flow protection: musl's assembly isn't
marked, so no static musl program can be. CET is x86-64's, so a target
for another architecture doesn't have it either. `cet = true` with any
target but an x86-64 glibc one is an error. `cargo_build`, which builds
with Cargo whole, doesn't give control-flow protection either.

## Crates that read outside their directory

Each step's sandbox holds the toolchain, the crate's own directory, and
what it is given. A crate that reads a file outside its directory needs it
named. Give `workspace` the settings of such packages in `crates`:

```gcsl
rust.workspace(
    dir("."),
    rust.vendored(file("Cargo.lock")),
    crates = [
        {package = "policy"; data = [{at = "registry.d"; place = dir("registry.d")}]},
        {
            package = "sdk-sys"
            env = [{key = "SDK_DIR"; value = "/opt/sdk"}]
            given = [{at = "/opt/sdk"; place = build sdk()}]
        },
    ],
)
```

Each setting does one thing:

- **`data`** places files and directories under the workspace, where the
  crate's compiles and build script find them.
- **`env`** sets variables for its build script and its compiles.
- **`given`** places files and directories at absolute paths, for its build
  script and its compiles, and for every crate that depends on it. A
  native library that a build script links goes here, so that the programs
  that use the crate link it too.

## Tests

`rust.tests(ws, package)` gives a member's test programs, its unit tests
and each integration test, as `cargo test -p` builds them. Give
`features` too if the tests need them. `rust.run_test(test)` runs one as a
step, in a sandbox of the toolchain's runtime with a writable `/tmp`. It
runs from its package's directory, as Cargo does, and the sandbox holds
that directory with the package's `data` and `beside`:

```gcsl
def test server_tests(tests: List<rust.RustTest> = rust.tests(crates(), "server")) {
    let ran = for each in tests { = rust.run_test(each) }
}
```

So a test reads its own files by relative paths or through
`CARGO_MANIFEST_DIR`, as it does under Cargo. What a test writes there stays
in its sandbox, so no change reaches your workspace.

Give `run_test` what else a test reads in `given`, such as another member's
directory, its variables in `env`, and its arguments in `args`, such as a
filter and `--test-threads=1`. A path in `given` that the package already
places is placed once, from the package. A test reruns when its program or
any file of its package changes.

A test target with `harness = false` in its manifest is compiled as a
program of its own, as Cargo compiles it.

`rust.tests` builds the package's examples too, as `cargo test` does. A
test program runs at `/work/deps/<name>`, with the examples beside it in
`/work/examples`, as in Cargo's target directory. So a test that finds an
example from its own path, at `../../examples/<name>`, finds it.

`rust.benches(ws, package)` gives a member's benchmarks, as `cargo test
--benches` builds them, and `rust.run_test` runs each. A benchmark with
`harness = false` is a program of its own, which runs with no arguments.

## Documentation, its tests, and Clippy

`rust.doctests(ws, package)` tests a member's documentation, as `cargo test
--doc` does: rustdoc compiles and runs each crate's examples as a step. It
takes `features`, `given`, and `env` as `run_test` does, and gives no tests
for a member with no library.

`rust.clippy(ws, package)` checks a member with Clippy, as `cargo clippy
--all-targets` does: its library, programs, build script, tests, benchmarks,
and examples, each crate a step. `flags` come after the member's lints, so
`flags = ["-Dwarnings"]` denies every warning. A check fails when a lint it
denies fires.

Clippy's `cargo` lints read `cargo metadata`, which a check of one crate
can't run, so `rust.clippy` allows them. `rust.cargo_lints(ws)` checks them
instead, as `cargo clippy --workspace` does, in one step for the whole
workspace. The step holds what Cargo plans with: the manifests, the lock,
the vendored crates, and Cargo's home, with the network off. The member's
`[lints]` that name these lints apply, then `flags`, so `flags =
["-Wclippy::cargo", "-Dwarnings"]` denies them. It reads the workspace's
Clippy configuration too, such as `allowed-duplicate-crates`.

`rust.docs(ws, package)` makes a member's library documentation, as `cargo
doc --no-deps` does, as a step, and gives the directory rustdoc wrote.
`flags` come after the member's lints, as they do for Clippy, so `flags =
["-Dwarnings"]` fails it when rustdoc warns, such as about a broken link.

All of these are steps that the rust library makes, so make them in a test's
parameter defaults, where a test plans and builds what it needs:

```gcsl
def test clippy(checked: List<List<{}>> = rust.clippy(crates(), "server", flags = ["-Dwarnings"])) {}

def test doctests(ran: List<List<{}>> = rust.doctests(crates(), "server")) {}

def test docs(made: Dir = rust.docs(crates(), "server", flags = ["-Dwarnings"])) {}

def test cargo_lints(checked: {} = rust.cargo_lints(crates(), flags = ["-Wclippy::cargo", "-Dwarnings"])) {}
```

## Build with Cargo, whole

`rust.cargo_build` builds the workspace with Cargo, in one step:

```gcsl
import "github.com/gcslib/rust"

def build ppk() {
    = rust.cargo_build(dir("src"), rust.vendored(file("src/Cargo.lock")), bins = ["ppk"])
}
```

`rust.cargo_build(src, vendor, bins)` builds the Cargo workspace `src` with
`cargo build --release --frozen --offline`, from the crates of `vendor`. It
gives a directory of the binaries `bins`, each by its name. `packages`
names the workspace's packages to build, as Cargo's `-p` does.

The whole of `cargo build` is one step, so changing one source file runs it
again. Cargo's target directory is kept between runs in the step's
[scratch directory](/pekit/building/writing-steps.md#keep-state-between-runs), so the
crates of `vendor` aren't compiled again. The workspace's own crates, and
crates it takes by their paths, are always compiled again. Cargo judges
them by their files' modification times, which a file put back as it was
can make look older than the last build.

Either way of building takes its crates from `rust.vendored`, so no crate
is fetched again.

## Where crates come from

`rust.vendored(lock)` fetches every crate of crates.io that `lock` pins,
each checked against the checksum `Cargo.lock` records for it, and lays
them out as `cargo vendor` does. Each crate's fetch and unpacking is kept
in the store.

A crate from a git repository is pinned by the commit `Cargo.lock` records
for it. `rust.vendored` fetches the repository at that commit with
`fetch_git`, once for every crate it holds. It gives each crate's directory
as the repository has it, so a crate that takes another of the same
repository by its path still finds it. A crate whose manifest takes values
from its workspace's, such as `version.workspace = true`, or names a
sibling crate's path, has its manifest written for it to build on its own.

A crate from anywhere else is an error, since nothing pins it.

## Git crates of a pinned library

If `pekit.lock` pins a library from the same repository as a git crate,
`Cargo.lock` must pin the crate at the library's commit, because the
library's settings for the crate and the crate must match. A crate at
another commit is an error that names both commits, so update one lock to
match the other.

A distribution that builds others' workspaces can set the context
`crates_at_pins` instead. Each such crate is then built at the library's
commit, not at the commit `Cargo.lock` records, so a fix to one crate of a
repository reaches every workspace that pins its library without a change
to each workspace's `Cargo.lock`:

```gcsl
let vendor = rust.vendored(file("Cargo.lock")) with { crates_at_pins = true }
```

`rust.overrides_report(vendor)` lists each crate built at another commit
than its lock records, one line each, `NAME URL LOCKED -> PINNED`, for a
packager to record.

Cargo takes the crate only while the lock still describes it. If the
crate has another version at the library's commit, the build fails and
says to update the lock with `cargo update -p NAME`. If its dependencies
changed, Cargo's own check of the lock fails.

## Targets and flags

By default `cargo_build` builds for `x86_64-unknown-linux-musl`, as static,
position-independent programs that need nothing of the system they run on.
Give `target = "x86_64-unknown-linux-gnu"` for programs linked against
glibc instead.

The flags follow the target: a glibc build takes none unless you give
`rustflags`. The library's flags are Cargo's `build.rustflags`, so a
project's own configuration of its target's flags, or of its linker, takes
precedence over them, as Cargo intends.

## C, libraries, and bindings

C that a crate compiles through the `cc` crate, such as `zstd-sys`, is
compiled for the target by `target_c`. By default that's the gcc library's
Bootlin musl toolchain, `gcc_x86_64_musl()`, for a musl target, which a
static musl program needs, and the registered C toolchain for any other.

`cargo_build` takes these as well:

- **`libs`** names libraries a crate builds to give besides the binaries,
  such as a `staticlib`: `libs = ["libpeios.a"]`.
- **`beside`** places directories next to the source, at `../NAME`, for a
  crate that takes another by a path outside its own tree.
- **`env`** gives every build script variables of its own, each a
  `{key; value}`, as Cargo's `[env]` table does.
- **`libclang`** is for a build script that runs bindgen: a list of one
  directory holding `libclang.so`, such as
  `libclang = [clang.libclang_18()]`. The clang library's `libclang_18` is
  a pinned build from PyPI. The build is given `LIBCLANG_PATH`, and
  `BINDGEN_EXTRA_CLANG_ARGS` names the target C toolchain's own headers and
  sysroot, so bindgen parses as that toolchain's compiler would.

A build script finds the C compiler in `CC_<target>`, the C++ compiler
beside it in `CXX_<target>`, such as `x86_64-linux-g++` beside
`x86_64-linux-gcc`, and the archiver in `AR_<target>`, so a crate that
compiles C++ through `cc` builds. That holds both one crate at a time and
with `cargo_build`.

No pkg-config is pinned, and a build script's sandbox holds only the
toolchain, so a probe for a system library fails the same way on every
machine. A crate that falls back without the library, or loads it at run
time, such as `wayland-sys` with its `dlopen` feature, builds. For a crate
that has to link a system library, give the library through `given` and
tell its build script where it is through `env`.

Everything is pinned, so a strict build gives the same program, byte for
byte, on any machine. See [Hermetic and Strict
Builds](/pekit/concepts/hermetic-and-strict-builds.md).

---

# Building Go

_Pekit / Languages_

> Build Go programs hermetically from the modules go.sum names with the go library, one package at a time, including tests, go vet, the race detector, embedded files, and the pinned Go toolchain.

The go library builds Go programs from the modules your `go.sum` names,
with no network and nothing of the host. It compiles a module one package
at a time, as Bazel's Go rules do. Import it as `github.com/gcslib/go`.

## Before you start

- The go, buildenv, and gcc libraries. See [Libraries](/pekit/libraries/libraries.md).
- A Go module with a `go.sum`.
- `curl` and `sha256sum` on the host, to pin the module files.

## Register the toolchain

The library asks the `toolchain` module for a `Toolchain::Go`. Its
`go_1_26` is Go 1.26.8 from go.dev, pinned by its SHA-256. It runs on the
buildenv library's busybox environment. Register both in `workspace.gcsl`,
with the gcc library's C toolchain for the race detector:

```gcsl
import Toolchain::* from "github.com/gcslib/buildenv"
import Toolchain::* from "github.com/gcslib/gcc"
import Toolchain::* from "github.com/gcslib/go"
import Toolchain from toolchain

pekitconf = {
    toolchains = [Toolchain::C gcc_x86_64, Toolchain::Go go_1_26, Toolchain::BuildEnv busybox_x86_64]
}
```

## Pin the modules

pekit fetches a file only by its SHA-256. `go.sum` records a different
hash, of a module's contents, so a second file, `go.pins`, records the
digest of each module file as the module proxy serves it.

1. Add a script that writes it:

   ```gcsl
   import "github.com/gcslib/go"

   def script pin_modules() {
       let count = go.pin_modules(file("go.sum"), "{dir(".").path}/go.pins")
   }
   ```

2. Run it, and commit `go.pins` beside `go.sum`:

   ```sh
   pekit run pin_modules
   ```

Run it again whenever `go.sum` changes, and review the change to `go.pins`
as you would review `go.sum`. A build fails when `go.pins` lacks a file
`go.sum` names, and says which.

The build fetches each file by its pin and lays them out as a module proxy
for the go command. The go command checks each module against `go.sum` as
it reads it, so the pins name the bytes and `go.sum` names what they must
be.

## Build a program

1. Plan the module with `go.workspace`, then build what you need of it:

   ```gcsl
   import "github.com/gcslib/go"

   fn module() -> go.GoWorkspace {
       = go.workspace(dir("."), file("go.sum"), file("go.pins"))
   }

   def build server() {
       = go.bin(module(), "./cmd/server")
   }
   ```

2. Build it:

   ```sh
   pekit build server
   ```

`go.bin(ws, package)` gives the program of a main package, named after its
last path element unless you give `name`. Give `ldflags` for the linker,
such as `ldflags = ["-B", "gobuildid"]`. The program carries the build
information `go build -trimpath` embeds, which `go version -m` prints.

`go.workspace` builds for Linux on x86-64, with cgo off. Give `goos` and
`goarch` for another platform. Its build mode is `exe` unless you give
`buildmode`, such as `buildmode = "pie"`. Give `tags` for build tags.

## Check the result

pekit prints the program's path. Change one source file and build again:
pekit compiles that file's package, and the packages that import it,
again, and finds every other package in the store. A change that leaves a
package's archive the same, such as a new comment, compiles nothing that
imports it.

## How planning works

The go command plans the build: `go list` lists each package a program
needs, with its files and imports. Each package is then a step of its own,
compiled as the go command compiles it. `compile` compiles its Go files,
`asm` its assembly, and `pack` adds the objects to its archive. A step
holds only the package's own files and the archives of the packages it
imports.

The go command reads the sources' imports to plan, so an edit plans again.
Planning is quick, and a package whose files and imports didn't change is
found in the store.

The standard library is built once for each configuration, by the go
command, as one step.

## Tests

`go.tests(ws, package)` gives a package's test program, as `go test -c`
builds it, or nothing for a package with no test files. `go.run_test(test)`
runs one as a step, in the package's directory, as `go test` does:

```gcsl
def test store(tests: List<go.GoTest> = go.tests(module(), "./internal/store")) {
    let ran = for each in tests { = go.run_test(each) }
}
```

Give `run_test` what a test reads in `given`, its variables in `env`, and
its arguments in `args`, such as `-test.run=TestOpen`. A test program is a
static program, as `go test` links one, whatever the workspace's build
mode.

## Vet and the race detector

`go.vet(ws)` runs `go vet` on every package, and `go.race(ws)` runs every
package's tests with `go test -race`. Each is one step, which fails as the
go command does. The race detector links with C, so `race` uses the
registered C toolchain:

```gcsl
def test vet(checked: {} = go.vet(module())) {}

def test race(checked: {} = go.race(module())) {}
```

Give either `patterns` to check only some packages, such as
`patterns = ["./internal/..."]`.

## Embedded files

A package's `//go:embed` files are placed with it, and its compile is given
the go command's own record of what each pattern matches. An edit to an
embedded file compiles its package again.

## What it doesn't build

These are errors, which say so:

- A package with cgo files.
- A package of a module that `go.mod` replaces with a local directory.

Everything is pinned, so a strict build gives the same program, byte for
byte, on any machine. See [Hermetic and Strict
Builds](/pekit/concepts/hermetic-and-strict-builds.md).
