From a0ad2dee6a0b3bb7fd04032f6113206f7b4e73eb Mon Sep 17 00:00:00 2001 From: Jay Petacat Date: Mon, 4 Jan 2021 23:48:34 -0500 Subject: [PATCH] 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 --- lib/std/SemanticVersion.zig | 11 ++++++++++- src/Compilation.zig | 6 ++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/std/SemanticVersion.zig b/lib/std/SemanticVersion.zig index dc9e6d85728a7cabfa731e01ea4f0205bc2934af..76767de8b5a541b4d0919c1190db665a45be433a 100644 --- a/lib/std/SemanticVersion.zig +++ b/lib/std/SemanticVersion.zig @@ -102,7 +102,7 @@ pub fn parse(text: []const u8) !Version { if (extra_index == null) return ver; // Slice optional pre-release or build metadata components. - const extra = text[extra_index.?..text.len]; + const extra: []const u8 = text[extra_index.?..text.len]; if (extra[0] == '-') { const build_index = std.mem.indexOfScalar(u8, extra, '+'); ver.pre = extra[1..(build_index orelse extra.len)]; @@ -293,3 +293,12 @@ fn testFmt(expected: []const u8, comptime template: []const u8, args: anytype) ! std.debug.warn("\n======================================\n", .{}); return error.TestFailed; } + +test "zig_version" { + // An approximate Zig build that predates this test. + const older_version = .{ .major = 0, .minor = 8, .patch = 0, .pre = "dev.874" }; + + // Simulated compatibility check using Zig version. + const compatible = comptime @import("builtin").zig_version.order(older_version) == .gt; + if (!compatible) @compileError("zig_version test failed"); +} diff --git a/src/Compilation.zig b/src/Compilation.zig index 75b9ac7520fc635fd194e135db6daf0adb057216..b017dde8c8ac9247754682fb0d12e6eb1f3c8de5 100644 --- a/src/Compilation.zig +++ b/src/Compilation.zig @@ -2703,6 +2703,11 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8 \\pub const arch = Target.current.cpu.arch; \\/// Deprecated \\pub const endian = Target.current.cpu.arch.endian(); + \\ + \\/// Zig version. When writing code that supports multiple versions of Zig, prefer + \\/// feature detection (i.e. with `@hasDecl` or `@hasField`) over version checks. + \\pub const zig_version = try @import("std").SemanticVersion.parse("{s}"); + \\ \\pub const output_mode = OutputMode.{}; \\pub const link_mode = LinkMode.{}; \\pub const is_test = {}; @@ -2714,6 +2719,7 @@ pub fn generateBuiltinZigSource(comp: *Compilation, allocator: *Allocator) ![]u8 \\ .features = Target.{}.featureSet(&[_]Target.{}.Feature{{ \\ , .{ + build_options.version, std.zig.fmtId(@tagName(comp.bin_file.options.output_mode)), std.zig.fmtId(@tagName(comp.bin_file.options.link_mode)), comp.bin_file.options.is_test, -- 2.54.0