zig
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesezig
zig
Zig ecosystem for systems programming without hidden control flow.
用于无隐藏控制流的系统编程的Zig生态系统。
Atomic Skills
核心技能
| Skill | Commands | Domain |
|---|---|---|
| zig build | build system | Compile, link, cross-compile |
| zig test | testing | Run test blocks |
| zig fmt | formatter | Canonical formatting |
| zls | LSP | Autocomplete, diagnostics |
| 技能 | 命令 | 领域 |
|---|---|---|
| zig build | 构建系统 | 编译、链接、交叉编译 |
| zig test | 测试 | 运行测试块 |
| zig fmt | 格式化工具 | 标准化格式化 |
| zls | LSP | 自动补全、诊断 |
Quick Start
快速入门
bash
undefinedbash
undefinedNew project
新建项目
mkdir myproject && cd myproject
zig init
mkdir myproject && cd myproject
zig init
Build and run
构建并运行
zig build run
zig build run
Test
测试
zig build test
zig build test
Format
格式化
zig fmt src/
zig fmt src/
Cross-compile to WASM
交叉编译到WASM
zig build -Dtarget=wasm32-freestanding
undefinedzig build -Dtarget=wasm32-freestanding
undefinedbuild.zig (0.15.2)
build.zig (0.15.2)
zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "myapp",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the application");
run_step.dependOn(&run_cmd.step);
const tests = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
}zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "myapp",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the application");
run_step.dependOn(&run_cmd.step);
const tests = b.addTest(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&b.addRunArtifact(tests).step);
}build.zig Module Registration (0.15.2)
build.zig模块注册(0.15.2版本)
When registering many modules in build.zig, Zig 0.15.2 enforces unused-const rules:
zig
// If a module has downstream imports, keep the named const:
const message_frame_mod = b.addModule("message_frame", .{
.root_source_file = b.path("src/message_frame.zig"),
});
// If a module has NO downstream imports, discard the return value directly:
_ = b.addModule("terminal", .{
.root_source_file = b.path("src/terminal.zig"),
});
// WRONG — "pointless discard of local constant" error:
// const terminal_mod = b.addModule(...);
// _ = terminal_mod;
// Dependency chaining:
const qrtp_frame_mod = b.addModule("qrtp_frame", .{
.root_source_file = b.path("src/qrtp_frame.zig"),
.imports = &.{ .{ .name = "fountain", .module = fountain_mod } },
});在build.zig中注册多个模块时,Zig 0.15.2会强制检查未使用常量规则:
zig
// 如果模块有下游导入,保留命名常量:
const message_frame_mod = b.addModule("message_frame", .{
.root_source_file = b.path("src/message_frame.zig"),
});
// 如果模块没有下游导入,直接丢弃返回值:
_ = b.addModule("terminal", .{
.root_source_file = b.path("src/terminal.zig"),
});
// 错误写法 —— 会抛出「无意义丢弃本地常量」错误:
// const terminal_mod = b.addModule(...);
// _ = terminal_mod;
// 依赖链:
const qrtp_frame_mod = b.addModule("qrtp_frame", .{
.root_source_file = b.path("src/qrtp_frame.zig"),
.imports = &.{ .{ .name = "fountain", .module = fountain_mod } },
});Core Patterns
核心模式
Explicit Allocators
显式分配器
zig
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
try list.appendSlice("hello");
}zig
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
try list.appendSlice("hello");
}Error Handling
错误处理
zig
fn readFile(path: []const u8) ![]u8 {
const file = try std.fs.cwd().openFile(path, .{});
defer file.close();
return file.readToEndAlloc(allocator, 1024 * 1024);
}
// Usage with catch
const data = readFile("config.txt") catch |err| {
std.log.err("Failed: {}", .{err});
return err;
};zig
fn readFile(path: []const u8) ![]u8 {
const file = try std.fs.cwd().openFile(path, .{});
defer file.close();
return file.readToEndAlloc(allocator, 1024 * 1024);
}
// catch用法
const data = readFile("config.txt") catch |err| {
std.log.err("Failed: {}", .{err});
return err;
};Comptime Metaprogramming
编译期元编程
zig
fn Vec(comptime T: type, comptime N: usize) type {
return struct {
data: [N]T,
const Self = @This();
pub fn dot(self: Self, other: Self) T {
var sum: T = 0;
inline for (0..N) |i| {
sum += self.data[i] * other.data[i];
}
return sum;
}
};
}
const Vec3 = Vec(f32, 3);zig
fn Vec(comptime T: type, comptime N: usize) type {
return struct {
data: [N]T,
const Self = @This();
pub fn dot(self: Self, other: Self) T {
var sum: T = 0;
inline for (0..N) |i| {
sum += self.data[i] * other.data[i];
}
return sum;
}
};
}
const Vec3 = Vec(f32, 3);Defer/Errdefer
Defer/Errdefer
zig
fn process() !void {
const resource = try acquire();
defer release(resource); // Always runs
const temp = try allocate();
errdefer free(temp); // Only on error
try doWork(resource, temp);
// temp ownership transferred, no errdefer needed
}zig
fn process() !void {
const resource = try acquire();
defer release(resource); // 始终执行
const temp = try allocate();
errdefer free(temp); // 仅在出现错误时执行
try doWork(resource, temp);
// temp所有权已转移,不需要errdefer
}C Interop
C语言互操作
zig
const c = @cImport({
@cInclude("stdio.h");
@cInclude("mylib.h");
});
pub fn main() void {
_ = c.printf("Hello from C\n");
}zig
const c = @cImport({
@cInclude("stdio.h");
@cInclude("mylib.h");
});
pub fn main() void {
_ = c.printf("Hello from C\n");
}Emerging Patterns (zig-syrup)
新兴模式(来自zig-syrup)
Pattern 1: SplitMix64 Bijection (Gay.jl Integration)
模式1:SplitMix64双射(Gay.jl集成)
Comptime modular multiplicative inverse via Newton's method. Enables invertible hashing
with Strong Parallelism Invariance (SPI): same gives the same result
regardless of call order or parallelism.
(seed, index)zig
pub const SplitMix64 = struct {
pub const GOLDEN: u64 = 0x9e3779b97f4a7c15;
pub const MIX1: u64 = 0xbf58476d1ce4e5b9;
pub const MIX2: u64 = 0x94d049bb133111eb;
pub const MIX1_INV: u64 = modInverse64(MIX1);
pub const MIX2_INV: u64 = modInverse64(MIX2);
state: u64,
/// Forward bijection: deterministic, invertible.
pub fn mix(x: u64) u64 {
var z = x +% GOLDEN;
z = (z ^ (z >> 30)) *% MIX1;
z = (z ^ (z >> 27)) *% MIX2;
return z ^ (z >> 31);
}
/// Inverse: unmix(mix(x)) == x for all x.
pub fn unmix(z: u64) u64 {
var x = z;
x ^= x >> 31; x ^= x >> 62;
x *%= MIX2_INV;
x ^= x >> 27; x ^= x >> 54;
x *%= MIX1_INV;
x ^= x >> 30; x ^= x >> 60;
x -%= GOLDEN;
return x;
}
/// O(1) random access. SPI-compatible.
pub fn colorAt(seed: u64, index: u64) u64 {
return mix(seed ^ index);
}
/// Comptime modular inverse mod 2^64 via Newton's method.
fn modInverse64(a: u64) u64 {
@setEvalBranchQuota(10000);
var x: u64 = a;
x *%= 2 -% a *% x; // doubling correct bits each step
x *%= 2 -% a *% x;
x *%= 2 -% a *% x;
x *%= 2 -% a *% x;
x *%= 2 -% a *% x; // 64 bits converged
return x;
}
};Key insight: runs entirely at comptime — and are compile-time constants. The is necessary for the comptime evaluator.
modInverse64MIX1_INVMIX2_INV@setEvalBranchQuota通过牛顿法实现的编译期模乘逆元,支持具备强并行不变性(SPI)的可逆哈希:无论调用顺序或并行度如何,相同的始终返回相同结果。
(seed, index)zig
pub const SplitMix64 = struct {
pub const GOLDEN: u64 = 0x9e3779b97f4a7c15;
pub const MIX1: u64 = 0xbf58476d1ce4e5b9;
pub const MIX2: u64 = 0x94d049bb133111eb;
pub const MIX1_INV: u64 = modInverse64(MIX1);
pub const MIX2_INV: u64 = modInverse64(MIX2);
state: u64,
/// 正向双射:确定性、可逆
pub fn mix(x: u64) u64 {
var z = x +% GOLDEN;
z = (z ^ (z >> 30)) *% MIX1;
z = (z ^ (z >> 27)) *% MIX2;
return z ^ (z >> 31);
}
/// 逆向:对所有x满足unmix(mix(x)) == x
pub fn unmix(z: u64) u64 {
var x = z;
x ^= x >> 31; x ^= x >> 62;
x *%= MIX2_INV;
x ^= x >> 27; x ^= x >> 54;
x *%= MIX1_INV;
x ^= x >> 30; x ^= x >> 60;
x -%= GOLDEN;
return x;
}
/// O(1)随机访问,兼容SPI
pub fn colorAt(seed: u64, index: u64) u64 {
return mix(seed ^ index);
}
/// 通过牛顿法实现的2^64模下编译期模逆元
fn modInverse64(a: u64) u64 {
@setEvalBranchQuota(10000);
var x: u64 = a;
x *%= 2 -% a *% x; // 每一步正确位数翻倍
x *%= 2 -% a *% x;
x *%= 2 -% a *% x;
x *%= 2 -% a *% x;
x *%= 2 -% a *% x; // 64位收敛
return x;
}
};核心要点:完全在编译期运行 —— 和是编译期常量。是编译期求值器的必要配置。
modInverse64MIX1_INVMIX2_INV@setEvalBranchQuotaPattern 2: Three-Mode Tagged Union PRNG
模式2:三模式标签联合伪随机数生成器
Tagged union for GF(3)-aligned PRNG modes. Each mode has a distinct role:
zig
pub const PrngMode = enum {
splitmix, // -1 (MINUS): bijective, invertible, SPI. Default.
xoshiro, // 0 (ERGODIC): fast, non-cryptographic.
chacha, // +1 (PLUS): CSPRNG for identity proofs.
};
pub const Prng = union(PrngMode) {
splitmix: SplitMix64,
xoshiro: std.Random.Xoshiro256,
chacha: std.Random.ChaCha,
pub fn init(prng_mode: PrngMode, seed: u64) Prng {
return switch (prng_mode) {
.splitmix => .{ .splitmix = SplitMix64.init(seed) },
.xoshiro => .{ .xoshiro = std.Random.Xoshiro256.init(seed) },
.chacha => initChaCha(seed),
};
}
pub fn next(self: *Prng) u64 {
return switch (self.*) {
.splitmix => |*s| s.next(),
.xoshiro => |*x| x.next(),
.chacha => |*c| c.random().int(u64),
};
}
// IMPORTANT: Don't name a method the same as the active tag field.
// Use `activeMode` instead of `mode` to avoid shadowing.
pub fn activeMode(self: *const Prng) PrngMode {
return self.*;
}
};Gotcha: would shadow the union's internal tag — renamed to .
pub fn mode(self)modeactiveMode面向GF(3)对齐的PRNG模式的标签联合,每种模式具备不同作用:
zig
pub const PrngMode = enum {
splitmix, // -1 (MINUS):双射、可逆、SPI,默认模式
xoshiro, // 0 (ERGODIC):快速非加密级
chacha, // +1 (PLUS):用于身份证明的CSPRNG
};
pub const Prng = union(PrngMode) {
splitmix: SplitMix64,
xoshiro: std.Random.Xoshiro256,
chacha: std.Random.ChaCha,
pub fn init(prng_mode: PrngMode, seed: u64) Prng {
return switch (prng_mode) {
.splitmix => .{ .splitmix = SplitMix64.init(seed) },
.xoshiro => .{ .xoshiro = std.Random.Xoshiro256.init(seed) },
.chacha => initChaCha(seed),
};
}
pub fn next(self: *Prng) u64 {
return switch (self.*) {
.splitmix => |*s| s.next(),
.xoshiro => |*x| x.next(),
.chacha => |*c| c.random().int(u64),
};
}
// 重要:不要命名和激活标签字段同名的方法
// 使用`activeMode`而非`mode`避免命名遮蔽
pub fn activeMode(self: *const Prng) PrngMode {
return self.*;
}
};注意点:会遮蔽联合内部的标签,因此重命名为。
pub fn mode(self)modeactiveModePattern 3: C ABI Callback Abstraction
模式3:C ABI回调抽象
Platform-agnostic callbacks for hardware interaction (QRTP QR code rendering):
zig
/// Platform renders QR code from raw bytes. Returns 0 on success.
pub const RenderQRFn = *const fn (
data: [*]const u8,
data_len: usize,
context: ?*anyopaque,
) callconv(.c) c_int;
/// Platform scans QR code from camera. Returns decoded length, 0 if none.
pub const ScanQRFn = *const fn (
buf: [*]u8,
buf_len: usize,
context: ?*anyopaque,
) callconv(.c) usize;
pub const TransportConfig = struct {
render_qr: RenderQRFn,
scan_qr: ScanQRFn,
delay: DelayFn,
context: ?*anyopaque = null,
frame_delay_ms: u32 = 100,
};Gotcha (0.15.2): Use (lowercase). is a compile error.
callconv(.c)callconv(.C)用于硬件交互(QRTP二维码渲染)的平台无关回调:
zig
/// 平台从原始字节渲染二维码,成功返回0
pub const RenderQRFn = *const fn (
data: [*]const u8,
data_len: usize,
context: ?*anyopaque,
) callconv(.c) c_int;
/// 平台从摄像头扫描二维码,返回解码长度,无内容返回0
pub const ScanQRFn = *const fn (
buf: [*]u8,
buf_len: usize,
context: ?*anyopaque,
) callconv(.c) usize;
pub const TransportConfig = struct {
render_qr: RenderQRFn,
scan_qr: ScanQRFn,
delay: DelayFn,
context: ?*anyopaque = null,
frame_delay_ms: u32 = 100,
};注意点(0.15.2版本):使用小写的,会触发编译错误。
callconv(.c)callconv(.C)Pattern 4: SIMD XOR Block Combining
模式4:SIMD异或块合并
Fixed-size blocks enable SIMD vectorization without allocations:
zig
pub fn xorBlocks(dst: []u8, src: []const u8) void {
const len = @min(dst.len, src.len);
const vec_len = 16;
const full_vecs = len / vec_len;
var i: usize = 0;
while (i < full_vecs * vec_len) : (i += vec_len) {
const d: @Vector(vec_len, u8) = dst[i..][0..vec_len].*;
const s: @Vector(vec_len, u8) = src[i..][0..vec_len].*;
dst[i..][0..vec_len].* = d ^ s;
}
// Scalar tail
while (i < len) : (i += 1) {
dst[i] ^= src[i];
}
}固定大小块无需分配即可实现SIMD向量化:
zig
pub fn xorBlocks(dst: []u8, src: []const u8) void {
const len = @min(dst.len, src.len);
const vec_len = 16;
const full_vecs = len / vec_len;
var i: usize = 0;
while (i < full_vecs * vec_len) : (i += vec_len) {
const d: @Vector(vec_len, u8) = dst[i..][0..vec_len].*;
const s: @Vector(vec_len, u8) = src[i..][0..vec_len].*;
dst[i..][0..vec_len].* = d ^ s;
}
// 标量处理尾部
while (i < len) : (i += 1) {
dst[i] ^= src[i];
}
}Pattern 5: Sheaf-Theoretic Decoder (Bumpus StructuredDecompositions.jl)
模式5:层论解码器(Bumpus StructuredDecompositions.jl)
Fountain decoder maps to adhesion_filter from Bumpus's tree decompositions:
- Source blocks = bags in the tree decomposition
- Encoded blocks = adhesion spans between bags
- XOR = pullback projection on the adhesion
- Belief propagation = sheaf consistency filtering
zig
/// Fountain decoder with adhesion_filter alias.
pub const Decoder = struct {
// ... source blocks, state, pending buffer ...
/// Public alias: StructuredDecompositions.jl naming convention.
pub fn adhesionFilter(self: *Decoder) bool {
return self.propagate();
}
/// Sheaf consistency propagation:
/// When a bag (source block) is solved, check all adhesion spans
/// (pending encoded blocks) for newly degree-1 solvable entries.
fn propagate(self: *Decoder) bool {
var progress = true;
while (progress) {
progress = false;
// XOR out known blocks from pending, solve degree-1 entries
// ... (see fountain.zig for full implementation)
}
return progress;
}
};喷泉解码器映射到Bumpus树分解的adhesion_filter:
- 源块 = 树分解中的包
- 编码块 = 包之间的粘附跨度
- XOR = 粘附的拉回投影
- 置信传播 = 层一致性过滤
zig
/// 带adhesion_filter别名的喷泉解码器
pub const Decoder = struct {
// ... 源块、状态、待处理缓冲区 ...
/// 公开别名:遵循StructuredDecompositions.jl命名规范
pub fn adhesionFilter(self: *Decoder) bool {
return self.propagate();
}
/// 层一致性传播:
/// 当一个包(源块)被求解后,检查所有粘附跨度(待处理编码块)中新增的度1可求解条目
fn propagate(self: *Decoder) bool {
var progress = true;
while (progress) {
progress = false;
// 从待处理块中异或已知块,求解度1条目
// ... 完整实现见fountain.zig
}
return progress;
}
};Pattern 6: Compact Binary Framing (QRTP)
模式6:紧凑二进制帧(QRTP)
Fixed-layout binary serialization without allocators, fitting QR code capacity:
zig
pub fn encodeFrame(block: *const fountain.EncodedBlock) QrtpFrame {
var frame = QrtpFrame{};
var pos: usize = 0;
@memcpy(frame.data[pos..][0..4], "qrtp"); // 4-byte tag
pos += 4;
frame.data[pos] = PROTOCOL_VERSION; // 1-byte version
pos += 1;
writeU64BE(frame.data[pos..], block.seed); // 8-byte big-endian
pos += 8;
// ... indices, payload ...
frame.len = pos;
return frame;
}无分配的固定布局二进制序列化,适配二维码容量:
zig
pub fn encodeFrame(block: *const fountain.EncodedBlock) QrtpFrame {
var frame = QrtpFrame{};
var pos: usize = 0;
@memcpy(frame.data[pos..][0..4], "qrtp"); // 4字节标签
pos += 4;
frame.data[pos] = PROTOCOL_VERSION; // 1字节版本
pos += 1;
writeU64BE(frame.data[pos..], block.seed); // 8字节大端序
pos += 8;
// ... 索引、 payload ...
frame.len = pos;
return frame;
}Zig 0.15.2 Gotchas
Zig 0.15.2常见坑点
| Issue | Wrong | Right |
|---|---|---|
| C calling convention | | |
| Unused module const | | |
| Method name = tag field | | |
| Hex literal | | Only |
| Wrapping arithmetic | | |
| 问题 | 错误写法 | 正确写法 |
|---|---|---|
| C调用约定 | | |
| 未使用模块常量 | | |
| 方法名与标签字段重名 | | |
| 十六进制字面量 | | 仅允许 |
| 包装算术 | | |
Version Detection
版本检测
zig
// Feature detection over version checks
const has_new_api = @hasDecl(std, "Build");
const T = if (has_new_api) std.Build else std.build.Builder;zig
// 基于功能检测而非版本检查
const has_new_api = @hasDecl(std, "Build");
const T = if (has_new_api) std.Build else std.build.Builder;Debug
调试
zig
std.debug.print("value: {any}\n", .{x});
std.log.info("structured: {}", .{data});
@breakpoint(); // Debugger trapzig
std.debug.print("value: {any}\n", .{x});
std.log.info("structured: {}", .{data});
@breakpoint(); // 调试器陷阱Cross-Compile Targets
交叉编译目标
bash
undefinedbash
undefinedList all targets
列出所有目标
zig targets | jq '.native'
zig targets | jq '.native'
Common targets
常用目标
zig build -Dtarget=x86_64-linux-gnu
zig build -Dtarget=aarch64-macos
zig build -Dtarget=wasm32-wasi
zig build -Dtarget=thumb-none-eabi # Embedded
undefinedzig build -Dtarget=x86_64-linux-gnu
zig build -Dtarget=aarch64-macos
zig build -Dtarget=wasm32-wasi
zig build -Dtarget=thumb-none-eabi # 嵌入式设备
undefinedReference: zig-syrup Module Map
参考:zig-syrup模块映射
| Module | LOC | Trit | Role |
|---|---|---|---|
| 907 | +1 | Luby Transform encoder/decoder, 3-mode PRNG |
| 427 | 0 | Binary framing for QR/TCP transport |
| 403 | -1 | Send/recv via C ABI QR callbacks |
| — | 0 | TCP length-prefixed framing |
| — | -1 | TCP OCapN transport |
| — | 0 | Scoped propagators (lattice cells) |
| — | +1 | Gay.jl Okhsl color space |
| 模块 | 代码行数 | Trit | 作用 |
|---|---|---|---|
| 907 | +1 | Luby变换编解码器、三模式PRNG |
| 427 | 0 | QR/TCP传输的二进制帧 |
| 403 | -1 | 通过C ABI QR回调收发数据 |
| — | 0 | TCP长度前缀帧 |
| — | -1 | TCP OCapN传输 |
| — | 0 | 作用域传播器(格单元) |
| — | +1 | Gay.jl Okhsl色彩空间 |
Related Skills
相关技能
| Skill | Trit | Role |
|---|---|---|
| zig-programming | -1 | 223 recipes, full docs |
| rama-gay-zig | -1 | Rama + Gay.jl + Zig interleave |
| structured-decomp | 0 | Bumpus tree decompositions |
| zig | -1 | Ecosystem wrapper + emerging patterns |
| 技能 | Trit | 作用 |
|---|---|---|
| zig-programming | -1 | 223个示例、完整文档 |
| rama-gay-zig | -1 | Rama + Gay.jl + Zig混合开发 |
| structured-decomp | 0 | Bumpus树分解 |
| zig | -1 | 生态封装 + 新兴模式 |
GF(3) Triads
GF(3)三元组
zig(-1) ⊗ zls-integration(0) ⊗ c-interop(+1) = 0 ✓
zig(-1) ⊗ acsets(0) ⊗ gay-mcp(+1) = 0 ✓ [Schema coloring]
zig(-1) ⊗ babashka(0) ⊗ duckdb-ies(+1) = 0 ✓ [Build analytics]
zig(-1) ⊗ structured-decomp(0) ⊗ fountain(+1) = 0 ✓ [Sheaf decoder]
zig(-1) ⊗ qrtp-frame(0) ⊗ qrtp-transport(+1) = 0 ✓ [Air-gapped transport]zig(-1) ⊗ zls-integration(0) ⊗ c-interop(+1) = 0 ✓
zig(-1) ⊗ acsets(0) ⊗ gay-mcp(+1) = 0 ✓ [Schema着色]
zig(-1) ⊗ babashka(0) ⊗ duckdb-ies(+1) = 0 ✓ [构建分析]
zig(-1) ⊗ structured-decomp(0) ⊗ fountain(+1) = 0 ✓ [层解码器]
zig(-1) ⊗ qrtp-frame(0) ⊗ qrtp-transport(+1) = 0 ✓ [气隙传输]SDF Interleaving
SDF关联
This skill connects to Software Design for Flexibility (Hanson & Sussman, 2021):
本技能关联**《Software Design for Flexibility》**(Hanson & Sussman, 2021):
Primary Chapter: 2. Domain-Specific Languages
主要章节:2. 领域特定语言
Concepts: DSL, wrapper, pattern-directed, embedding
概念:DSL、封装、模式导向、嵌入
GF(3) Balanced Triad
GF(3)平衡三元组
zig (−) + SDF.Ch2 (−) + [balancer] (−) = 0Skill Trit: -1 (MINUS - verification)
zig (−) + SDF.Ch2 (−) + [balancer] (−) = 0技能Trit:-1(MINUS - 验证)
Secondary Chapters
次要章节
- Ch4: Pattern Matching
- Ch6: Layering
- Ch7: Propagators (fountain decoder = belief propagation)
- 第4章:模式匹配
- 第6章:分层
- 第7章:传播器(喷泉解码器 = 置信传播)
Connection Pattern
关联模式
DSLs embed domain knowledge. This skill defines domain-specific operations.
DSL嵌入领域知识,本技能定义了领域特定操作。
Cat# Integration
Cat#集成
This skill maps to Cat# = Comod(P) as a bicomodule:
Trit: -1 (MINUS/Validator)
Home: Prof
Poly Op: ⊗
Kan Role: Ran (right Kan extension)
Color: #3B82F6 (blue)本技能作为双余模映射到Cat# = Comod(P):
Trit: -1 (MINUS/验证器)
Home: Prof
Poly Op: ⊗
Kan角色: Ran (右Kan延拓)
颜色: #3B82F6 (蓝色)Why -1 (MINUS)?
为什么是-1(MINUS)?
Zig validates and constrains:
- No hidden allocations
- No hidden control flow
- No exceptions
- Explicit error handling
- Compile-time safety checks
The language itself is a validator — it refuses to compile unsafe patterns.
Zig用于验证和约束:
- 无隐藏分配
- 无隐藏控制流
- 无异常
- 显式错误处理
- 编译期安全检查
语言本身就是验证器——它拒绝编译不安全的模式。
zig-syrup Cat# Morphisms
zig-syrup Cat#态射
fountain.Encoder (+1, Lan_K) →[qrtp_frame (0, Adj)]→ qrtp_transport (-1, Ran_K)
Presheaves Prof Span
SplitMix64.mix (−1, Ran) ↔ SplitMix64.unmix (−1, Ran)
Bijection = isomorphism in Cat#, self-dual in Spanfountain.Encoder (+1, Lan_K) →[qrtp_frame (0, Adj)]→ qrtp_transport (-1, Ran_K)
预层 Prof 跨度
SplitMix64.mix (−1, Ran) ↔ SplitMix64.unmix (−1, Ran)
双射 = Cat#中的同构,跨度中自对偶Philosophy
设计理念
"Zig is not designed to make fancy high-level things. It's designed to make it easy to write correct low-level code."
- Explicit over implicit
- Compile-time over runtime
- No hidden control flow
- Allocator-aware by design
- C interop without FFI overhead
- SPI: same seed → same output regardless of execution order
"Zig不是为了实现花哨的高层功能而设计的,它的目标是让编写正确的底层代码变得简单。"
- 显式优于隐式
- 编译期优于运行时
- 无隐藏控制流
- 设计上天然感知分配器
- 无FFI开销的C语言互操作
- SPI:无论执行顺序如何,相同种子生成相同输出