Skip to content

Commit

Permalink
builtin: Add zig_version
Browse files Browse the repository at this point in the history
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 ziglang#6466
  • Loading branch information
jayschwa authored and dgbuckley committed Mar 9, 2021
1 parent c4af51a commit 0a37da0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/std/SemanticVersion.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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)];
Expand Down Expand Up @@ -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");
}
6 changes: 6 additions & 0 deletions src/Compilation.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {};
Expand All @@ -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,
Expand Down

0 comments on commit 0a37da0

Please sign in to comment.