liveBook · Manning

Comptime

As explained in Systems Programming with Zig

Comptime is Zig's compile-time execution feature that allows code to be evaluated during compilation.

A configurable file-copying utility needs buffers whose sizes are part of their array types. Zig’s comptime lets those sizes come from build options: the values are known while the program is compiled, not when it runs. section 3.5.3

Listing 3.16 Using the buffering option
const std = @import("std");
const options = @import("options"); #1

pub fn main(init: std.process.Init) !void {
    const io = init.io;
    const arena = init.arena.allocator();

    const args = try init.minimal.args.toSlice(arena);
    const cwd = std.Io.Dir.cwd();

    var stdout_buffer: [options.writer_buffer_size]u8 = #2
        undefined;
    var stderr_buffer: [1024]u8 = undefined;
    var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer);
    var stderr_writer = std.Io.File.stderr().writer(io, &stderr_buffer);
    const stdout = &stdout_writer.interface;
    const stderr = &stderr_writer.interface;

    for (args[1..]) |filepath| {
        const file = cwd.openFile(io, filepath, .{}) catch {
            stderr.print("could not open: {s}\n", .{filepath}) catch {};
            stderr.flush() catch {};
            continue;
        };
        defer file.close(io);

        var file_buffer: [options.reader_buffer_size]u8 = undefined;
        var file_reader = file.reader(io, &file_buffer);
        const reader = &file_reader.interface; #3

        _ = try reader.streamRemaining(stdout);
    }

    try stdout.flush();
}

The imported options supply a compile-time array length for the output buffer. section 3.5.3

Comptime is code executed by the Zig compiler while producing machine-executable code; runtime code executes when the compiled program runs. It supports metaprogramming with almost arbitrary Zig code, filling roles often handled by generics, macros, code-generation scripts, and constant expressions. section 2.1 section 1.3.2

Bake a dictionary into a program

For a word-ladder game, load a file of four-character words, count them, and copy them into an array during compilation. Parsing and checking unchanging data up front avoids loading it on every run; invalid data can produce a helpful compilation error instead. section 4.1.1 section 4.3

Comptime has deliberate limits:

  • It cannot introduce nondeterminism by interacting with the operating system or adding randomness. Use the build system for tasks needing those capabilities; @embedFile is a convenience for embedding files. section 4.1.2
  • Evaluation has a limit on backwards branches, including loops and function calls. If the compiler reports that limit, check the work first, then raise it with @setEvalBranchQuota if needed. section 4.1.2

Comptime also supports generic code through type parameters. For troubleshooting compile-time work, @compileError and @compileLog provide ways to report and inspect it. section 4.4

How Systems Programming with Zig covers it

How deep it goes
Explains compile-time evaluation through configuration and data-processing steps, including hermeticity restrictions and evaluation quotas.
Examples
Uses configurable file-copying buffers and an embedded word-ladder dictionary to demonstrate comptime.
What you can do after
Apply comptime to configure buffer sizes and prepare fixed data during compilation.
How it connects
Connects comptime to metaprogramming, generics, array types, build systems, and hermetic builds.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.