zig

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

zig

zig

Zig ecosystem for systems programming without hidden control flow.
用于无隐藏控制流的系统编程的Zig生态系统。

Atomic Skills

核心技能

SkillCommandsDomain
zig buildbuild systemCompile, link, cross-compile
zig testtestingRun test blocks
zig fmtformatterCanonical formatting
zlsLSPAutocomplete, diagnostics
技能命令领域
zig build构建系统编译、链接、交叉编译
zig test测试运行测试块
zig fmt格式化工具标准化格式化
zlsLSP自动补全、诊断

Quick Start

快速入门

bash
undefined
bash
undefined

New 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
undefined
zig build -Dtarget=wasm32-freestanding
undefined

build.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
(seed, index)
gives the same result regardless of call order or parallelism.
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:
modInverse64
runs entirely at comptime —
MIX1_INV
and
MIX2_INV
are compile-time constants. The
@setEvalBranchQuota
is necessary for the comptime evaluator.
通过牛顿法实现的编译期模乘逆元,支持具备强并行不变性(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;
    }
};
核心要点
modInverse64
完全在编译期运行 ——
MIX1_INV
MIX2_INV
是编译期常量。
@setEvalBranchQuota
是编译期求值器的必要配置。

Pattern 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:
pub fn mode(self)
would shadow the union's internal
mode
tag — renamed to
activeMode
.
面向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)
会遮蔽联合内部的
mode
标签,因此重命名为
activeMode

Pattern 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
callconv(.c)
(lowercase).
callconv(.C)
is a compile error.
用于硬件交互(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常见坑点

IssueWrongRight
C calling convention
callconv(.C)
callconv(.c)
Unused module const
const m = b.addModule(...); _ = m;
_ = b.addModule(...)
Method name = tag field
pub fn mode(self)
on
union(PrngMode)
pub fn activeMode(self)
Hex literal
0xGAY
,
0xPASS
Only
[0-9a-fA-F]
valid
Wrapping arithmetic
a + b
(overflow trap)
a +% b
(wrapping)
问题错误写法正确写法
C调用约定
callconv(.C)
callconv(.c)
未使用模块常量
const m = b.addModule(...); _ = m;
_ = b.addModule(...)
方法名与标签字段重名
pub fn mode(self)
定义在
union(PrngMode)
pub fn activeMode(self)
十六进制字面量
0xGAY
,
0xPASS
仅允许
[0-9a-fA-F]
字符
包装算术
a + b
(溢出会触发陷阱)
a +% b
(溢出自动包装)

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 trap
zig
std.debug.print("value: {any}\n", .{x});
std.log.info("structured: {}", .{data});
@breakpoint();  // 调试器陷阱

Cross-Compile Targets

交叉编译目标

bash
undefined
bash
undefined

List 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
undefined
zig build -Dtarget=x86_64-linux-gnu zig build -Dtarget=aarch64-macos zig build -Dtarget=wasm32-wasi zig build -Dtarget=thumb-none-eabi # 嵌入式设备
undefined

Reference: zig-syrup Module Map

参考:zig-syrup模块映射

ModuleLOCTritRole
fountain.zig
907+1Luby Transform encoder/decoder, 3-mode PRNG
qrtp_frame.zig
4270Binary framing for QR/TCP transport
qrtp_transport.zig
403-1Send/recv via C ABI QR callbacks
message_frame.zig
0TCP length-prefixed framing
tcp_transport.zig
-1TCP OCapN transport
propagator.zig
0Scoped propagators (lattice cells)
color.zig
+1Gay.jl Okhsl color space
模块代码行数Trit作用
fountain.zig
907+1Luby变换编解码器、三模式PRNG
qrtp_frame.zig
4270QR/TCP传输的二进制帧
qrtp_transport.zig
403-1通过C ABI QR回调收发数据
message_frame.zig
0TCP长度前缀帧
tcp_transport.zig
-1TCP OCapN传输
propagator.zig
0作用域传播器(格单元)
color.zig
+1Gay.jl Okhsl色彩空间

Related Skills

相关技能

SkillTritRole
zig-programming-1223 recipes, full docs
rama-gay-zig-1Rama + Gay.jl + Zig interleave
structured-decomp0Bumpus tree decompositions
zig-1Ecosystem wrapper + emerging patterns
技能Trit作用
zig-programming-1223个示例、完整文档
rama-gay-zig-1Rama + Gay.jl + Zig混合开发
structured-decomp0Bumpus树分解
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] (−) = 0
Skill 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 Span
fountain.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:无论执行顺序如何,相同种子生成相同输出