authorgravatar for jay@jayschwa.netJay Petacat <jay@jayschwa.net> 2021-01-04 23:48:34-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2021-01-09 12:50:39-08:00
loga0ad2dee6a0b3bb7fd04032f6113206f7b4e73eb
tree3af35b3737044d92a507541684e240be9f86d64d
parent5c49a137d5948310d8abbf9d6f1fb899e7122239

builtin: Add zig_version

This will enable code to perform version checks and make it easier to support multiple versions of Zig. Within the SemVer implementation, an intermediate value needed to be coerced to a slice to workaround a comptime bug. Closes #6466

2 files changed, 16 insertions(+), 1 deletions(-)

lib/std/SemanticVersion.zig+10-1
......@@ -102,7 +102,7 @@ pub fn parse(text: []const u8) !Version {
102102 if (extra_index == null) return ver;
103103
104104 // Slice optional pre-release or build metadata components.
105 const extra = text[extra_index.?..text.len];
105 const extra: []const u8 = text[extra_index.?..text.len];
106106 if (extra[0] == '-') {
107107 const build_index = std.mem.indexOfScalar(u8, extra, '+');
108108 ver.pre = extra[1..(build_index orelse extra.len)];
......@@ -293,3 +293,12 @@ fn testFmt(expected: []const u8, comptime template: []const u8, args: anytype) !
293293 std.debug.warn("\n======================================\n", .{});
294294 return error.TestFailed;
295295}
296
297test "zig_version" {
298 // An approximate Zig build that predates this test.
299 const older_version = .{ .major = 0, .minor = 8, .patch = 0, .pre = "dev.874" };
300
301 // Simulated compatibility check using Zig version.
302 const compatible = comptime @import("builtin").zig_version.order(older_version) == .gt;
303 if (!compatible) @compileError("zig_version test failed");
304}
src/Compilation.zig+6
......@@ -2703,6 +2703,11 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8
27032703 \\pub const arch = Target.current.cpu.arch;
27042704 \\/// Deprecated
27052705 \\pub const endian = Target.current.cpu.arch.endian();
2706 \\
2707 \\/// Zig version. When writing code that supports multiple versions of Zig, prefer
2708 \\/// feature detection (i.e. with `@hasDecl` or `@hasField`) over version checks.
2709 \\pub const zig_version = try @import("std").SemanticVersion.parse("{s}");
2710 \\
27062711 \\pub const output_mode = OutputMode.{};
27072712 \\pub const link_mode = LinkMode.{};
27082713 \\pub const is_test = {};
......@@ -2714,6 +2719,7 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8
27142719 \\ .features = Target.{}.featureSet(&[_]Target.{}.Feature{{
27152720 \\
27162721 , .{
2722 build_options.version,
27172723 std.zig.fmtId(@tagName(comp.bin_file.options.output_mode)),
27182724 std.zig.fmtId(@tagName(comp.bin_file.options.link_mode)),
27192725 comp.bin_file.options.is_test,