跳转到内容
语言参考Zig 0.17.0官方原文

Zig 重视表达式是否在编译时已知这一概念。它应用于多个不同场景;通过组合这些基础机制,语言得以保持精简、易读且功能强大。

编译时概念介绍

编译时参数

Zig 通过编译时参数实现泛型,其本质是编译时鸭子类型。

compile-time_duck_typing.zig
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
fn gimmeTheBiggerFloat(a: f32, b: f32) f32 {
return max(f32, a, b);
}
fn gimmeTheBiggerInteger(a: u64, b: u64) u64 {
return max(u64, a, b);
}

在 Zig 中,类型是一等值,可以赋值给变量、作为参数传入函数,也可以从函数返回。但类型只能用于编译时已知的表达式,因此上例参数 T 必须标记为 comptime。

comptime 参数意味着:

  • 在调用点,该值必须在编译时已知,否则产生编译错误。
  • 在函数定义内部,该值在编译时已知。

例如,在上例中引入另一个函数:

test_unresolved_comptime_value.zig
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
test "try to pass a runtime type" {
foo(false);
}
fn foo(condition: bool) void {
const result = max(if (condition) f32 else u64, 1234, 5678);
_ = result;
}
命令行
$ zig test test_unresolved_comptime_value.zig
/home/andy/src/zig/doc/langref/test_unresolved_comptime_value.zig:8:28: error: unable to resolve comptime value
const result = max(if (condition) f32 else u64, 1234, 5678);
^~~~~~~~~
/home/andy/src/zig/doc/langref/test_unresolved_comptime_value.zig:8:24: note: argument to comptime parameter must be comptime-known
const result = max(if (condition) f32 else u64, 1234, 5678);
^~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/andy/src/zig/doc/langref/test_unresolved_comptime_value.zig:1:8: note: parameter declared comptime here
fn max(comptime T: type, a: T, b: T) T {
^~~~~~~~
referenced by:
test.try to pass a runtime type: /home/andy/src/zig/doc/langref/test_unresolved_comptime_value.zig:5:8

这里会报错,因为程序员试图把仅在运行时已知的值,传给需要编译时已知值的函数。

另一种报错方式是传入某个类型,使函数分析时无法通过类型检查。这就是编译时鸭子类型的含义。

例如:

test_comptime_mismatched_type.zig
fn max(comptime T: type, a: T, b: T) T {
return if (a > b) a else b;
}
test "try to compare bools" {
_ = max(bool, true, false);
}
命令行
$ zig test test_comptime_mismatched_type.zig
/home/andy/src/zig/doc/langref/test_comptime_mismatched_type.zig:2:18: error: operator > not allowed for type 'bool'
return if (a > b) a else b;
~~^~~
referenced by:
test.try to compare bools: /home/andy/src/zig/doc/langref/test_comptime_mismatched_type.zig:5:12

另一方面,在具有 comptime 参数的函数定义内部,该参数值在编译时已知。因此,只要愿意,也可以让此函数支持 bool 类型:

test_comptime_max_with_bool.zig
fn max(comptime T: type, a: T, b: T) T {
if (T == bool) {
return a or b;
} else if (a > b) {
return a;
} else {
return b;
}
}
test "try to compare bools" {
try @import("std").testing.expectEqual(true, max(bool, false, true));
}
命令行
$ zig test test_comptime_max_with_bool.zig
1/1 test_comptime_max_with_bool.test.try to compare bools...OK
All 1 tests passed.

之所以可行,是因为条件在编译时已知时,Zig 会隐式内联 if 表达式,并保证跳过未选择分支的语义分析。

因此,在这种情况下,实际为 max 生成的函数如下:

compiler_generated_function.zig
fn max(a: bool, b: bool) bool {
{
return a or b;
}
}

所有处理编译时已知值的代码都已消除,只留下完成任务必需的运行时代码。

switch 表达式也遵循相同规则:目标表达式在编译时已知时,会隐式内联。

编译时变量

Zig 中可以将变量标记为 comptime,从而向编译器保证该变量的每次读取和写入都在编译时进行。违反此要求会产生编译错误。

结合可以 inline 循环这一能力,就能编写部分在编译时、部分在运行时求值的函数。

例如:

test_comptime_evaluation.zig
const expectEqual = @import("std").testing.expectEqual;
const CmdFn = struct {
name: []const u8,
func: fn (i32) i32,
};
const cmd_fns = [_]CmdFn{
CmdFn{ .name = "one", .func = one },
CmdFn{ .name = "two", .func = two },
CmdFn{ .name = "three", .func = three },
};
fn one(value: i32) i32 {
return value + 1;
}
fn two(value: i32) i32 {
return value + 2;
}
fn three(value: i32) i32 {
return value + 3;
}
fn performFn(comptime prefix_char: u8, start_value: i32) i32 {
var result: i32 = start_value;
comptime var i = 0;
inline while (i < cmd_fns.len) : (i += 1) {
if (cmd_fns[i].name[0] == prefix_char) {
result = cmd_fns[i].func(result);
}
}
return result;
}
test "perform fn" {
try expectEqual(6, performFn('t', 1));
try expectEqual(1, performFn('o', 0));
try expectEqual(99, performFn('w', 99));
}
命令行
$ zig test test_comptime_evaluation.zig
1/1 test_comptime_evaluation.test.perform fn...OK
All 1 tests passed.

这个例子略显人为,因为编译时求值部分并非必要;全部在运行时执行也能正常工作。但生成的代码确实不同:根据传入的不同 prefix_char 值,会为函数 performFn 分别生成三份代码:

performFn_1
// 来自这一行:
// expect(performFn('t', 1) == 6);
fn performFn(start_value: i32) i32 {
var result: i32 = start_value;
result = two(result);
result = three(result);
return result;
}
performFn_2
// 来自这一行:
// expect(performFn('o', 0) == 1);
fn performFn(start_value: i32) i32 {
var result: i32 = start_value;
result = one(result);
return result;
}
performFn_3
// 来自这一行:
// expect(performFn('w', 99) == 99);
fn performFn(start_value: i32) i32 {
var result: i32 = start_value;
_ = &result;
return result;
}

注意,即使是调试构建也会如此。这并非编写更优代码的方法,而是确保应该在编译时发生的操作确实在编译时发生。这样可以发现更多错误,并提供其他语言需要宏、代码生成或预处理器才能达到的表达能力。

编译时表达式

在 Zig 中,表达式在编译时已知还是运行时已知非常重要。程序员可以通过 comptime 表达式保证表达式在编译时求值;如果无法做到,编译器会报错。例如:

test_comptime_call_extern_function.zig
extern fn exit() noreturn;
test "foo" {
comptime {
exit();
}
}
命令行
$ zig test test_comptime_call_extern_function.zig
/home/andy/src/zig/doc/langref/test_comptime_call_extern_function.zig:5:13: error: comptime call of extern function
exit();
~~~~^~
/home/andy/src/zig/doc/langref/test_comptime_call_extern_function.zig:4:5: note: 'comptime' keyword forces comptime evaluation
comptime {
^~~~~~~~

程序无法合理地在编译时调用 exit() 或其他外部函数,因此这里产生编译错误。但 comptime 表达式的作用远不止偶尔触发编译错误。

在 comptime 表达式内部:

  • 所有变量都是 comptime 变量。
  • 所有 if、while、for 和 switch 表达式都在编译时求值;无法做到时产生编译错误。
  • 所有 return 和 try 表达式均无效,除非函数本身就是在编译时调用的。
  • 所有具有运行时副作用或依赖运行时值的代码,都会产生编译错误。
  • 所有函数调用都会让编译器在编译时解释执行该函数;函数尝试执行具有全局运行时副作用的操作时,会产生编译错误。

因此,无须修改函数,就可以让同一个函数既在编译时调用,也在运行时调用。

看一个例子:

test_fibonacci_recursion.zig
const expectEqual = @import("std").testing.expectEqual;
fn fibonacci(index: u32) u32 {
if (index < 2) return index;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
// 在运行时测试 fibonacci
try expectEqual(13, fibonacci(7));
// 在编译时测试 fibonacci
try comptime expectEqual(13, fibonacci(7));
}
命令行
$ zig test test_fibonacci_recursion.zig
1/1 test_fibonacci_recursion.test.fibonacci...OK
All 1 tests passed.

假设忘记编写递归函数的基本情况,并尝试运行测试:

test_fibonacci_comptime_overflow.zig
const expectEqual = @import("std").testing.expectEqual;
fn fibonacci(index: u32) u32 {
//if (index < 2) return index;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
try comptime expectEqual(13, fibonacci(7));
}
命令行
$ zig test test_fibonacci_comptime_overflow.zig
/home/andy/src/zig/doc/langref/test_fibonacci_comptime_overflow.zig:5:28: error: overflow of integer type 'u32' with value '-1'
return fibonacci(index - 1) + fibonacci(index - 2);
~~~~~~^~~
/home/andy/src/zig/doc/langref/test_fibonacci_comptime_overflow.zig:5:21: note: called at comptime here (7 times)
return fibonacci(index - 1) + fibonacci(index - 2);
~~~~~~~~~^~~~~~~~~~~
/home/andy/src/zig/doc/langref/test_fibonacci_comptime_overflow.zig:9:43: note: called at comptime here
try comptime expectEqual(13, fibonacci(7));
~~~~~~~~~^~~

编译器会产生错误,其中包含尝试在编译时求值该函数所形成的栈追踪。

幸好使用了无符号整数,因此尝试从 0 减 1会触发非法行为;编译器若知道发生了非法行为,就始终报编译错误。如果使用有符号整数,会发生什么?

fibonacci_comptime_infinite_recursion.zig
const assert = @import("std").debug.assert;
fn fibonacci(index: i32) i32 {
//if (index < 2) return index;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
try comptime assert(fibonacci(7) == 13);
}

编译器本应注意到该函数的编译时求值经过了超过 1000 个分支,于是报错并停止。如果要增加编译时计算预算,可以使用内置函数 @setEvalBranchQuota,将默认的 1000 改为其他值。

但编译器存在设计缺陷,这里会发生栈溢出,而非预期行为。原文作者对此表示歉意,并希望在下一个版本之前修复。

如果修复了基本情况,但在 expect 这一行填入错误的值,会怎样?

test_fibonacci_comptime_unreachable.zig
const assert = @import("std").debug.assert;
fn fibonacci(index: i32) i32 {
if (index < 2) return index;
return fibonacci(index - 1) + fibonacci(index - 2);
}
test "fibonacci" {
try comptime assert(fibonacci(7) == 99999);
}
命令行
$ zig test test_fibonacci_comptime_unreachable.zig
/home/andy/src/zig/lib/std/debug.zig:442:14: error: reached unreachable code
if (!ok) unreachable; // assertion failure
^~~~~~~~~~~
/home/andy/src/zig/doc/langref/test_fibonacci_comptime_unreachable.zig:9:24: note: called at comptime here
try comptime assert(fibonacci(7) == 99999);
~~~~~~^~~~~~~~~~~~~~~~~~~~~~~

在命名空间级别,即所有函数之外,所有表达式都隐式为 comptime 表达式。因此可以使用函数初始化复杂的常量数据。例如:

test_namespace-level_comptime_expressions.zig
const first_25_primes = firstNPrimes(25);
const sum_of_first_25_primes = sum(&first_25_primes);
fn firstNPrimes(comptime n: usize) [n]i32 {
var prime_list: [n]i32 = undefined;
var next_index: usize = 0;
var test_number: i32 = 2;
while (next_index < prime_list.len) : (test_number += 1) {
var test_prime_index: usize = 0;
var is_prime = true;
while (test_prime_index < next_index) : (test_prime_index += 1) {
if (test_number % prime_list[test_prime_index] == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
prime_list[next_index] = test_number;
next_index += 1;
}
}
return prime_list;
}
fn sum(numbers: []const i32) i32 {
var result: i32 = 0;
for (numbers) |x| {
result += x;
}
return result;
}
test "variable values" {
try @import("std").testing.expectEqual(1060, sum_of_first_25_primes);
}
命令行
$ zig test test_namespace-level_comptime_expressions.zig
1/1 test_namespace-level_comptime_expressions.test.variable values...OK
All 1 tests passed.

编译此程序时,Zig 会预先算出结果并生成常量。以下是生成的 LLVM IR 中的相关行:

@0 = internal unnamed_addr constant [25 x i32] [i32 2, i32 3, i32 5, i32 7, i32 11, i32 13, i32 17, i32 19, i32 23, i32 29, i32 31, i32 37, i32 41, i32 43, i32 47, i32 53, i32 59, i32 61, i32 67, i32 71, i32 73, i32 79, i32 83, i32 89, i32 97]
@1 = internal unnamed_addr constant i32 1060

注意,并未对这些函数使用任何特殊语法。例如,可以原样调用 sum 函数,传入长度和值都仅在运行时已知的数字切片。

泛型数据结构

Zig 使用 comptime 能力实现泛型数据结构,无须引入特殊语法。

以下是一个泛型 List 数据结构示例。

generic_data_structure.zig
fn List(comptime T: type) type {
return struct {
items: []T,
len: usize,
};
}
// 传入一个类型即可实例化泛型 List 数据结构:
var buffer: [10]i32 = undefined;
var list = List(i32){
.items = &buffer,
.len = 0,
};

仅此而已:它是返回匿名 struct 的函数。为了错误提示和调试,Zig 根据创建该匿名结构体时调用的函数名称与参数,推导出名称 "List(i32)"。

要显式为类型命名,只需将其赋值给常量。

anonymous_struct_name.zig
const Node = struct {
next: ?*Node,
name: []const u8,
};
var node_a = Node{
.next = null,
.name = "Node A",
};
var node_b = Node{
.next = &node_a,
.name = "Node B",
};

本例中的 Node 结构体引用自身。所有顶层声明都与顺序无关,因此这样做可行。只要编译器能确定结构体大小,就允许自引用。此处 Node 通过指针引用自身,指针大小在编译时有明确定义,因此可以正常工作。

案例分析:Zig 中的 print

结合上述机制,来看 Zig 中的 print 如何工作。

print.zig
const print = @import("std").debug.print;
const a_number: i32 = 1234;
const a_string = "foobar";
pub fn main() void {
print("here is a string: '{s}' here is a number: {}\n", .{ a_string, a_number });
}
命令行
$ zig build-exe print.zig
$ ./print
here is a string: 'foobar' here is a number: 1234

展开它的实现,看看具体工作方式:

poc_print_fn.zig
const Writer = struct {
/// 调用 print,然后刷新缓冲区。
pub fn print(self: *Writer, comptime format: []const u8, args: anytype) anyerror!void {
const State = enum {
start,
open_brace,
close_brace,
};
comptime var start_index: usize = 0;
comptime var state = State.start;
comptime var next_arg: usize = 0;
inline for (format, 0..) |c, i| {
switch (state) {
State.start => switch (c) {
'{' => {
if (start_index < i) try self.write(format[start_index..i]);
state = State.open_brace;
},
'}' => {
if (start_index < i) try self.write(format[start_index..i]);
state = State.close_brace;
},
else => {},
},
State.open_brace => switch (c) {
'{' => {
state = State.start;
start_index = i;
},
'}' => {
try self.printValue(args[next_arg]);
next_arg += 1;
state = State.start;
start_index = i + 1;
},
's' => {
continue;
},
else => @compileError("Unknown format character: " ++ [1]u8{c}),
},
State.close_brace => switch (c) {
'}' => {
state = State.start;
start_index = i;
},
else => @compileError("Single '}' encountered in format string"),
},
}
}
comptime {
if (args.len != next_arg) {
@compileError("Unused arguments");
}
if (state != State.start) {
@compileError("Incomplete format string: " ++ format);
}
}
if (start_index < format.len) {
try self.write(format[start_index..format.len]);
}
try self.flush();
}
fn write(self: *Writer, value: []const u8) !void {
_ = self;
_ = value;
}
pub fn printValue(self: *Writer, value: anytype) !void {
_ = self;
_ = value;
}
fn flush(self: *Writer) !void {
_ = self;
}
};

这是概念验证实现;标准库中的实际函数具有更丰富的格式化能力。

注意,这不是 Zig 编译器硬编码的功能,而是标准库中的用户态代码。

从上例分析此函数时,Zig 会对函数进行部分求值,实际生成的函数如下:

Emitted print Function
pub fn print(self: *Writer, arg0: []const u8, arg1: i32) !void {
try self.write("here is a string: '");
try self.printValue(arg0);
try self.write("' here is a number: ");
try self.printValue(arg1);
try self.write("\n");
try self.flush();
}

printValue 接受任意类型的参数,并根据类型执行不同操作:

poc_printValue_fn.zig
const Writer = struct {
pub fn printValue(self: *Writer, value: anytype) !void {
switch (@typeInfo(@TypeOf(value))) {
.int => {
return self.writeInt(value);
},
.float => {
return self.writeFloat(value);
},
.pointer => {
return self.write(value);
},
else => {
@compileError("Unable to print type '" ++ @typeName(@TypeOf(value)) ++ "'");
},
}
}
fn write(self: *Writer, value: []const u8) !void {
_ = self;
_ = value;
}
fn writeInt(self: *Writer, value: anytype) !void {
_ = self;
_ = value;
}
fn writeFloat(self: *Writer, value: anytype) !void {
_ = self;
_ = value;
}
};

如果向 print 传入过多参数,会发生什么?

test_print_too_many_args.zig
const print = @import("std").debug.print;
const a_number: i32 = 1234;
const a_string = "foobar";
test "print too many arguments" {
print("here is a string: '{s}' here is a number: {}\n", .{
a_string,
a_number,
a_number,
});
}
命令行
$ zig test test_print_too_many_args.zig
/home/andy/src/zig/lib/std/Io/Writer.zig:821:18: error: unused argument in 'here is a string: '{s}' here is a number: {}
'
1 => @compileError("unused argument in '" ++ fmt ++ "'"),
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
referenced by:
print__func_957: /home/andy/src/zig/lib/std/debug.zig:330:39
test.print too many arguments: /home/andy/src/zig/doc/langref/test_print_too_many_args.zig:7:10

Zig 向程序员提供防范自身失误所需的工具。

Zig 不关心格式参数是否为字符串字面量,只要求它是编译时已知、可以强制转换为 []const u8 的值:

print_comptime-known_format.zig
const print = @import("std").debug.print;
const a_number: i32 = 1234;
const a_string = "foobar";
const fmt = "here is a string: '{s}' here is a number: {}\n";
pub fn main() void {
print(fmt, .{ a_string, a_number });
}
命令行
$ zig build-exe print_comptime-known_format.zig
$ ./print_comptime-known_format
here is a string: 'foobar' here is a number: 1234

这可以正常工作。

Zig 不在编译器中对字符串格式化做特殊处理,而是提供足够的能力,让用户态代码完成此任务;同时不必在 Zig 之上引入宏语言、预处理器语言等另一种语言。从上到下使用的都是 Zig。

另见: