Generating Documentation
Zig's documentation generation makes use of doc comments, using ///
. These
doc comments will "attach" themselves to the declarations found under them.
File-level doc comments can also be made at the top of a file with //!
.
The Zig compiler comes with documentation generation. This can be invoked by
adding -femit-docs
to your zig build-{exe, lib, obj}
or zig run
command.
This documentation is saved into ./docs
, as a small static website.
Here we will save this file as src/main.zig
and build documentation for it with
zig build-lib -femit-docs src/main.zig
.
//! This module provides functions for dealing with spreadsheets.
const std = @import("std");
/// A spreadsheet position
pub const Pos = struct {
/// (0-indexed) row
x: u32,
/// (0-indexed) column
y: u32,
/// The top-left position
pub const zero: Pos = .{ .x = 0, .y = 0 };
/// Illegal position
pub const invalid_pos: Pos = .{
.x = std.math.maxInt(u32),
.y = std.math.maxInt(u32),
};
};
pub const OpenFileError = error{
/// Unexpected file extension
InvalidSheet,
FileNotFound,
};
pub const ParseError = error{
/// File header invalid
InvalidSheet,
InvalidPosition,
};
pub const OpenError = OpenFileError || ParseError;
pub fn readCell(file: std.fs.File, pos: Pos) OpenError![]const u8 {
_ = file;
_ = pos;
@panic("todo");
}
We should now have a folder called docs/
. To view these docs nicely, you may
want to start a (local) static web server. Here's some commands you might be
able to use on your system without installing anything new:
caddy file-server --root docs/ --listen :8000
python -m http.server 8000 -d docs/
Take a few minutes to browse around. Notice that the left side of an error set
merge will take precedence over the right side, when it comes to differing doc
comments on the same error name. In our case this means that
OpenError.InvalidSheet
will have the doc comment from
OpenFileError.InvalidSheet
, rather than from ParseError.InvalidSheet
.
The Zig compiler itself has the zig std
command, which automatically serves a
web server with the standard library documentation, however as of writing this
server isn't exposed to the build system. The Zig standard library documentation
can also be found here.
When using Zig Build, generated docs can be found by using getEmittedDocs()
on
a Compile step. Here's an example of a build.zig
that generates documentation:
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const lib = b.addStaticLibrary(.{
.name = "lib",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(lib);
const install_docs = b.addInstallDirectory(.{
.source_dir = lib.getEmittedDocs(),
.install_dir = .prefix,
.install_subdir = "docs",
});
const docs_step = b.step("docs", "Install docs into zig-out/docs");
docs_step.dependOn(&install_docs.step);
}