From 41e1cd185b82a518c58c92544c45f0348c03ef74 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 7 May 2018 01:04:43 -0400 Subject: std.SegmentedList implementation --- std/math/log2.zig | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) (limited to 'std/math/log2.zig') diff --git a/std/math/log2.zig b/std/math/log2.zig index 998d6d6c5e..d5bbe385c2 100644 --- a/std/math/log2.zig +++ b/std/math/log2.zig @@ -31,17 +31,12 @@ pub fn log2(x: var) @typeOf(x) { return result; }, TypeId.Int => { - return log2_int(T, x); + return math.log2_int(T, x); }, else => @compileError("log2 not implemented for " ++ @typeName(T)), } } -pub fn log2_int(comptime T: type, x: T) T { - assert(x != 0); - return T.bit_count - 1 - T(@clz(x)); -} - pub fn log2_32(x_: f32) f32 { const ivln2hi: f32 = 1.4428710938e+00; const ivln2lo: f32 = -1.7605285393e-04; -- cgit v1.2.3 From 4787127cf6418f7a819c9d6f07a9046d76e0de65 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 10 May 2018 00:29:49 -0400 Subject: partial conversion to post-fix pointer deref using zig fmt --- std/atomic/queue.zig | 12 +- std/atomic/stack.zig | 16 +- std/buffer.zig | 11 +- std/build.zig | 207 ++++++-------- std/crypto/blake2.zig | 711 +++++++++++++++++++++++++++++++---------------- std/crypto/hmac.zig | 4 +- std/crypto/sha3.zig | 281 ++++++++++++------- std/event.zig | 53 ++-- std/hash/crc.zig | 32 +-- std/hash_map.zig | 102 ++++--- std/json.zig | 207 ++++++++------ std/math/acos.zig | 14 +- std/math/asin.zig | 18 +- std/math/atan2.zig | 66 ++--- std/math/cbrt.zig | 10 +- std/math/ceil.zig | 4 +- std/math/cos.zig | 12 +- std/math/floor.zig | 4 +- std/math/fma.zig | 7 +- std/math/hypot.zig | 8 +- std/math/ln.zig | 6 +- std/math/log10.zig | 18 +- std/math/log2.zig | 7 +- std/math/round.zig | 8 +- std/math/sin.zig | 12 +- std/math/tan.zig | 6 +- std/net.zig | 40 ++- std/os/child_process.zig | 192 +++++++------ std/segmented_list.zig | 54 ++-- std/sort.zig | 562 ++++++++++++++++++++++++++----------- 30 files changed, 1620 insertions(+), 1064 deletions(-) (limited to 'std/math/log2.zig') diff --git a/std/atomic/queue.zig b/std/atomic/queue.zig index e25c8e6b17..288a2b3b48 100644 --- a/std/atomic/queue.zig +++ b/std/atomic/queue.zig @@ -70,7 +70,7 @@ test "std.atomic.queue" { var queue: Queue(i32) = undefined; queue.init(); - var context = Context { + var context = Context{ .allocator = a, .queue = &queue, .put_sum = 0, @@ -81,16 +81,18 @@ test "std.atomic.queue" { var putters: [put_thread_count]&std.os.Thread = undefined; for (putters) |*t| { - *t = try std.os.spawnThread(&context, startPuts); + t.* = try std.os.spawnThread(&context, startPuts); } var getters: [put_thread_count]&std.os.Thread = undefined; for (getters) |*t| { - *t = try std.os.spawnThread(&context, startGets); + t.* = try std.os.spawnThread(&context, startGets); } - for (putters) |t| t.wait(); + for (putters) |t| + t.wait(); _ = @atomicRmw(u8, &context.puts_done, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); - for (getters) |t| t.wait(); + for (getters) |t| + t.wait(); std.debug.assert(context.put_sum == context.get_sum); std.debug.assert(context.get_count == puts_per_thread * put_thread_count); diff --git a/std/atomic/stack.zig b/std/atomic/stack.zig index 4a3dbef32b..400a1a3c4f 100644 --- a/std/atomic/stack.zig +++ b/std/atomic/stack.zig @@ -14,9 +14,7 @@ pub fn Stack(comptime T: type) type { }; pub fn init() Self { - return Self { - .root = null, - }; + return Self{ .root = null }; } /// push operation, but only if you are the first item in the stack. if you did not succeed in @@ -75,7 +73,7 @@ test "std.atomic.stack" { var a = &fixed_buffer_allocator.allocator; var stack = Stack(i32).init(); - var context = Context { + var context = Context{ .allocator = a, .stack = &stack, .put_sum = 0, @@ -86,16 +84,18 @@ test "std.atomic.stack" { var putters: [put_thread_count]&std.os.Thread = undefined; for (putters) |*t| { - *t = try std.os.spawnThread(&context, startPuts); + t.* = try std.os.spawnThread(&context, startPuts); } var getters: [put_thread_count]&std.os.Thread = undefined; for (getters) |*t| { - *t = try std.os.spawnThread(&context, startGets); + t.* = try std.os.spawnThread(&context, startGets); } - for (putters) |t| t.wait(); + for (putters) |t| + t.wait(); _ = @atomicRmw(u8, &context.puts_done, builtin.AtomicRmwOp.Xchg, 1, AtomicOrder.SeqCst); - for (getters) |t| t.wait(); + for (getters) |t| + t.wait(); std.debug.assert(context.put_sum == context.get_sum); std.debug.assert(context.get_count == puts_per_thread * put_thread_count); diff --git a/std/buffer.zig b/std/buffer.zig index 041d891dec..cf530c3c9e 100644 --- a/std/buffer.zig +++ b/std/buffer.zig @@ -31,9 +31,7 @@ pub const Buffer = struct { /// * ::replaceContentsBuffer /// * ::resize pub fn initNull(allocator: &Allocator) Buffer { - return Buffer { - .list = ArrayList(u8).init(allocator), - }; + return Buffer{ .list = ArrayList(u8).init(allocator) }; } /// Must deinitialize with deinit. @@ -45,9 +43,7 @@ pub const Buffer = struct { /// allocated with `allocator`. /// Must deinitialize with deinit. pub fn fromOwnedSlice(allocator: &Allocator, slice: []u8) Buffer { - var self = Buffer { - .list = ArrayList(u8).fromOwnedSlice(allocator, slice), - }; + var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) }; self.list.append(0); return self; } @@ -57,11 +53,10 @@ pub const Buffer = struct { pub fn toOwnedSlice(self: &Buffer) []u8 { const allocator = self.list.allocator; const result = allocator.shrink(u8, self.list.items, self.len()); - *self = initNull(allocator); + self.* = initNull(allocator); return result; } - pub fn deinit(self: &Buffer) void { self.list.deinit(); } diff --git a/std/build.zig b/std/build.zig index a312b28a6f..276176c63c 100644 --- a/std/build.zig +++ b/std/build.zig @@ -82,10 +82,8 @@ pub const Builder = struct { description: []const u8, }; - pub fn init(allocator: &Allocator, zig_exe: []const u8, build_root: []const u8, - cache_root: []const u8) Builder - { - var self = Builder { + pub fn init(allocator: &Allocator, zig_exe: []const u8, build_root: []const u8, cache_root: []const u8) Builder { + var self = Builder{ .zig_exe = zig_exe, .build_root = build_root, .cache_root = os.path.relative(allocator, build_root, cache_root) catch unreachable, @@ -112,12 +110,12 @@ pub const Builder = struct { .lib_dir = undefined, .exe_dir = undefined, .installed_files = ArrayList([]const u8).init(allocator), - .uninstall_tls = TopLevelStep { + .uninstall_tls = TopLevelStep{ .step = Step.init("uninstall", allocator, makeUninstall), .description = "Remove build artifacts from prefix path", }, .have_uninstall_step = false, - .install_tls = TopLevelStep { + .install_tls = TopLevelStep{ .step = Step.initNoOp("install", allocator), .description = "Copy build artifacts to prefix path", }, @@ -151,9 +149,7 @@ pub const Builder = struct { return LibExeObjStep.createObject(self, name, root_src); } - pub fn addSharedLibrary(self: &Builder, name: []const u8, root_src: ?[]const u8, - ver: &const Version) &LibExeObjStep - { + pub fn addSharedLibrary(self: &Builder, name: []const u8, root_src: ?[]const u8, ver: &const Version) &LibExeObjStep { return LibExeObjStep.createSharedLibrary(self, name, root_src, ver); } @@ -163,7 +159,7 @@ pub const Builder = struct { pub fn addTest(self: &Builder, root_src: []const u8) &TestStep { const test_step = self.allocator.create(TestStep) catch unreachable; - *test_step = TestStep.init(self, root_src); + test_step.* = TestStep.init(self, root_src); return test_step; } @@ -190,33 +186,31 @@ pub const Builder = struct { } /// ::argv is copied. - pub fn addCommand(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, - argv: []const []const u8) &CommandStep - { + pub fn addCommand(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) &CommandStep { return CommandStep.create(self, cwd, env_map, argv); } pub fn addWriteFile(self: &Builder, file_path: []const u8, data: []const u8) &WriteFileStep { const write_file_step = self.allocator.create(WriteFileStep) catch unreachable; - *write_file_step = WriteFileStep.init(self, file_path, data); + write_file_step.* = WriteFileStep.init(self, file_path, data); return write_file_step; } pub fn addLog(self: &Builder, comptime format: []const u8, args: ...) &LogStep { const data = self.fmt(format, args); const log_step = self.allocator.create(LogStep) catch unreachable; - *log_step = LogStep.init(self, data); + log_step.* = LogStep.init(self, data); return log_step; } pub fn addRemoveDirTree(self: &Builder, dir_path: []const u8) &RemoveDirStep { const remove_dir_step = self.allocator.create(RemoveDirStep) catch unreachable; - *remove_dir_step = RemoveDirStep.init(self, dir_path); + remove_dir_step.* = RemoveDirStep.init(self, dir_path); return remove_dir_step; } pub fn version(self: &const Builder, major: u32, minor: u32, patch: u32) Version { - return Version { + return Version{ .major = major, .minor = minor, .patch = patch, @@ -254,8 +248,7 @@ pub const Builder = struct { } pub fn getInstallStep(self: &Builder) &Step { - if (self.have_install_step) - return &self.install_tls.step; + if (self.have_install_step) return &self.install_tls.step; self.top_level_steps.append(&self.install_tls) catch unreachable; self.have_install_step = true; @@ -263,8 +256,7 @@ pub const Builder = struct { } pub fn getUninstallStep(self: &Builder) &Step { - if (self.have_uninstall_step) - return &self.uninstall_tls.step; + if (self.have_uninstall_step) return &self.uninstall_tls.step; self.top_level_steps.append(&self.uninstall_tls) catch unreachable; self.have_uninstall_step = true; @@ -360,7 +352,7 @@ pub const Builder = struct { pub fn option(self: &Builder, comptime T: type, name: []const u8, description: []const u8) ?T { const type_id = comptime typeToEnum(T); - const available_option = AvailableOption { + const available_option = AvailableOption{ .name = name, .type_id = type_id, .description = description, @@ -413,7 +405,7 @@ pub const Builder = struct { pub fn step(self: &Builder, name: []const u8, description: []const u8) &Step { const step_info = self.allocator.create(TopLevelStep) catch unreachable; - *step_info = TopLevelStep { + step_info.* = TopLevelStep{ .step = Step.initNoOp(name, self.allocator), .description = description, }; @@ -446,9 +438,9 @@ pub const Builder = struct { } pub fn addUserInputOption(self: &Builder, name: []const u8, value: []const u8) bool { - if (self.user_input_options.put(name, UserInputOption { + if (self.user_input_options.put(name, UserInputOption{ .name = name, - .value = UserValue { .Scalar = value }, + .value = UserValue{ .Scalar = value }, .used = false, }) catch unreachable) |*prev_value| { // option already exists @@ -458,18 +450,18 @@ pub const Builder = struct { var list = ArrayList([]const u8).init(self.allocator); list.append(s) catch unreachable; list.append(value) catch unreachable; - _ = self.user_input_options.put(name, UserInputOption { + _ = self.user_input_options.put(name, UserInputOption{ .name = name, - .value = UserValue { .List = list }, + .value = UserValue{ .List = list }, .used = false, }) catch unreachable; }, UserValue.List => |*list| { // append to the list list.append(value) catch unreachable; - _ = self.user_input_options.put(name, UserInputOption { + _ = self.user_input_options.put(name, UserInputOption{ .name = name, - .value = UserValue { .List = *list }, + .value = UserValue{ .List = list.* }, .used = false, }) catch unreachable; }, @@ -483,9 +475,9 @@ pub const Builder = struct { } pub fn addUserInputFlag(self: &Builder, name: []const u8) bool { - if (self.user_input_options.put(name, UserInputOption { + if (self.user_input_options.put(name, UserInputOption{ .name = name, - .value = UserValue {.Flag = {} }, + .value = UserValue{ .Flag = {} }, .used = false, }) catch unreachable) |*prev_value| { switch (prev_value.value) { @@ -556,9 +548,7 @@ pub const Builder = struct { warn("\n"); } - fn spawnChildEnvMap(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, - argv: []const []const u8) !void - { + fn spawnChildEnvMap(self: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) !void { if (self.verbose) { printCmd(cwd, argv); } @@ -617,7 +607,7 @@ pub const Builder = struct { self.pushInstalledFile(full_dest_path); const install_step = self.allocator.create(InstallFileStep) catch unreachable; - *install_step = InstallFileStep.init(self, src_path, full_dest_path); + install_step.* = InstallFileStep.init(self, src_path, full_dest_path); return install_step; } @@ -659,25 +649,23 @@ pub const Builder = struct { if (builtin.environ == builtin.Environ.msvc) { return "cl.exe"; } else { - return os.getEnvVarOwned(self.allocator, "CC") catch |err| + return os.getEnvVarOwned(self.allocator, "CC") catch |err| if (err == error.EnvironmentVariableNotFound) ([]const u8)("cc") else - debug.panic("Unable to get environment variable: {}", err) - ; + debug.panic("Unable to get environment variable: {}", err); } } pub fn findProgram(self: &Builder, names: []const []const u8, paths: []const []const u8) ![]const u8 { // TODO report error for ambiguous situations - const exe_extension = (Target { .Native = {}}).exeFileExt(); + const exe_extension = (Target{ .Native = {} }).exeFileExt(); for (self.search_prefixes.toSliceConst()) |search_prefix| { for (names) |name| { if (os.path.isAbsolute(name)) { return name; } - const full_path = try os.path.join(self.allocator, search_prefix, "bin", - self.fmt("{}{}", name, exe_extension)); + const full_path = try os.path.join(self.allocator, search_prefix, "bin", self.fmt("{}{}", name, exe_extension)); if (os.path.real(self.allocator, full_path)) |real_path| { return real_path; } else |_| { @@ -761,7 +749,7 @@ pub const Target = union(enum) { Cross: CrossTarget, pub fn oFileExt(self: &const Target) []const u8 { - const environ = switch (*self) { + const environ = switch (self.*) { Target.Native => builtin.environ, Target.Cross => |t| t.environ, }; @@ -786,7 +774,7 @@ pub const Target = union(enum) { } pub fn getOs(self: &const Target) builtin.Os { - return switch (*self) { + return switch (self.*) { Target.Native => builtin.os, Target.Cross => |t| t.os, }; @@ -794,7 +782,8 @@ pub const Target = union(enum) { pub fn isDarwin(self: &const Target) bool { return switch (self.getOs()) { - builtin.Os.ios, builtin.Os.macosx => true, + builtin.Os.ios, + builtin.Os.macosx => true, else => false, }; } @@ -860,61 +849,57 @@ pub const LibExeObjStep = struct { Obj, }; - pub fn createSharedLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8, - ver: &const Version) &LibExeObjStep - { + pub fn createSharedLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8, ver: &const Version) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initExtraArgs(builder, name, root_src, Kind.Lib, false, ver); + self.* = initExtraArgs(builder, name, root_src, Kind.Lib, false, ver); return self; } pub fn createCSharedLibrary(builder: &Builder, name: []const u8, version: &const Version) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initC(builder, name, Kind.Lib, version, false); + self.* = initC(builder, name, Kind.Lib, version, false); return self; } pub fn createStaticLibrary(builder: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initExtraArgs(builder, name, root_src, Kind.Lib, true, builder.version(0, 0, 0)); + self.* = initExtraArgs(builder, name, root_src, Kind.Lib, true, builder.version(0, 0, 0)); return self; } pub fn createCStaticLibrary(builder: &Builder, name: []const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initC(builder, name, Kind.Lib, builder.version(0, 0, 0), true); + self.* = initC(builder, name, Kind.Lib, builder.version(0, 0, 0), true); return self; } pub fn createObject(builder: &Builder, name: []const u8, root_src: []const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initExtraArgs(builder, name, root_src, Kind.Obj, false, builder.version(0, 0, 0)); + self.* = initExtraArgs(builder, name, root_src, Kind.Obj, false, builder.version(0, 0, 0)); return self; } pub fn createCObject(builder: &Builder, name: []const u8, src: []const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initC(builder, name, Kind.Obj, builder.version(0, 0, 0), false); + self.* = initC(builder, name, Kind.Obj, builder.version(0, 0, 0), false); self.object_src = src; return self; } pub fn createExecutable(builder: &Builder, name: []const u8, root_src: ?[]const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initExtraArgs(builder, name, root_src, Kind.Exe, false, builder.version(0, 0, 0)); + self.* = initExtraArgs(builder, name, root_src, Kind.Exe, false, builder.version(0, 0, 0)); return self; } pub fn createCExecutable(builder: &Builder, name: []const u8) &LibExeObjStep { const self = builder.allocator.create(LibExeObjStep) catch unreachable; - *self = initC(builder, name, Kind.Exe, builder.version(0, 0, 0), false); + self.* = initC(builder, name, Kind.Exe, builder.version(0, 0, 0), false); return self; } - fn initExtraArgs(builder: &Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, - static: bool, ver: &const Version) LibExeObjStep - { - var self = LibExeObjStep { + fn initExtraArgs(builder: &Builder, name: []const u8, root_src: ?[]const u8, kind: Kind, static: bool, ver: &const Version) LibExeObjStep { + var self = LibExeObjStep{ .strip = false, .builder = builder, .verbose_link = false, @@ -930,7 +915,7 @@ pub const LibExeObjStep = struct { .step = Step.init(name, builder.allocator, make), .output_path = null, .output_h_path = null, - .version = *ver, + .version = ver.*, .out_filename = undefined, .out_h_filename = builder.fmt("{}.h", name), .major_only_filename = undefined, @@ -953,11 +938,11 @@ pub const LibExeObjStep = struct { } fn initC(builder: &Builder, name: []const u8, kind: Kind, version: &const Version, static: bool) LibExeObjStep { - var self = LibExeObjStep { + var self = LibExeObjStep{ .builder = builder, .name = name, .kind = kind, - .version = *version, + .version = version.*, .static = static, .target = Target.Native, .cflags = ArrayList([]const u8).init(builder.allocator), @@ -1005,9 +990,9 @@ pub const LibExeObjStep = struct { self.out_filename = self.builder.fmt("lib{}.a", self.name); } else { switch (self.target.getOs()) { - builtin.Os.ios, builtin.Os.macosx => { - self.out_filename = self.builder.fmt("lib{}.{d}.{d}.{d}.dylib", - self.name, self.version.major, self.version.minor, self.version.patch); + builtin.Os.ios, + builtin.Os.macosx => { + self.out_filename = self.builder.fmt("lib{}.{d}.{d}.{d}.dylib", self.name, self.version.major, self.version.minor, self.version.patch); self.major_only_filename = self.builder.fmt("lib{}.{d}.dylib", self.name, self.version.major); self.name_only_filename = self.builder.fmt("lib{}.dylib", self.name); }, @@ -1015,8 +1000,7 @@ pub const LibExeObjStep = struct { self.out_filename = self.builder.fmt("{}.dll", self.name); }, else => { - self.out_filename = self.builder.fmt("lib{}.so.{d}.{d}.{d}", - self.name, self.version.major, self.version.minor, self.version.patch); + self.out_filename = self.builder.fmt("lib{}.so.{d}.{d}.{d}", self.name, self.version.major, self.version.minor, self.version.patch); self.major_only_filename = self.builder.fmt("lib{}.so.{d}", self.name, self.version.major); self.name_only_filename = self.builder.fmt("lib{}.so", self.name); }, @@ -1026,16 +1010,12 @@ pub const LibExeObjStep = struct { } } - pub fn setTarget(self: &LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, - target_environ: builtin.Environ) void - { - self.target = Target { - .Cross = CrossTarget { - .arch = target_arch, - .os = target_os, - .environ = target_environ, - } - }; + pub fn setTarget(self: &LibExeObjStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { + self.target = Target{ .Cross = CrossTarget{ + .arch = target_arch, + .os = target_os, + .environ = target_environ, + } }; self.computeOutFileNames(); } @@ -1159,7 +1139,7 @@ pub const LibExeObjStep = struct { pub fn addPackagePath(self: &LibExeObjStep, name: []const u8, pkg_index_path: []const u8) void { assert(self.is_zig); - self.packages.append(Pkg { + self.packages.append(Pkg{ .name = name, .path = pkg_index_path, }) catch unreachable; @@ -1343,8 +1323,7 @@ pub const LibExeObjStep = struct { try builder.spawnChild(zig_args.toSliceConst()); if (self.kind == Kind.Lib and !self.static and self.target.wantSharedLibSymLinks()) { - try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename, - self.name_only_filename); + try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename, self.name_only_filename); } } @@ -1373,7 +1352,8 @@ pub const LibExeObjStep = struct { args.append("ssp-buffer-size=4") catch unreachable; } }, - builtin.Mode.ReleaseFast, builtin.Mode.ReleaseSmall => { + builtin.Mode.ReleaseFast, + builtin.Mode.ReleaseSmall => { args.append("-O2") catch unreachable; args.append("-fno-stack-protector") catch unreachable; }, @@ -1505,8 +1485,7 @@ pub const LibExeObjStep = struct { } if (!is_darwin) { - const rpath_arg = builder.fmt("-Wl,-rpath,{}", - os.path.real(builder.allocator, builder.pathFromRoot(builder.cache_root)) catch unreachable); + const rpath_arg = builder.fmt("-Wl,-rpath,{}", os.path.real(builder.allocator, builder.pathFromRoot(builder.cache_root)) catch unreachable); defer builder.allocator.free(rpath_arg); cc_args.append(rpath_arg) catch unreachable; @@ -1535,8 +1514,7 @@ pub const LibExeObjStep = struct { try builder.spawnChild(cc_args.toSliceConst()); if (self.target.wantSharedLibSymLinks()) { - try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename, - self.name_only_filename); + try doAtomicSymLinks(builder.allocator, output_path, self.major_only_filename, self.name_only_filename); } } }, @@ -1581,8 +1559,7 @@ pub const LibExeObjStep = struct { cc_args.append("-o") catch unreachable; cc_args.append(output_path) catch unreachable; - const rpath_arg = builder.fmt("-Wl,-rpath,{}", - os.path.real(builder.allocator, builder.pathFromRoot(builder.cache_root)) catch unreachable); + const rpath_arg = builder.fmt("-Wl,-rpath,{}", os.path.real(builder.allocator, builder.pathFromRoot(builder.cache_root)) catch unreachable); defer builder.allocator.free(rpath_arg); cc_args.append(rpath_arg) catch unreachable; @@ -1635,7 +1612,7 @@ pub const TestStep = struct { pub fn init(builder: &Builder, root_src: []const u8) TestStep { const step_name = builder.fmt("test {}", root_src); - return TestStep { + return TestStep{ .step = Step.init(step_name, builder.allocator, make), .builder = builder, .root_src = root_src, @@ -1644,7 +1621,7 @@ pub const TestStep = struct { .name_prefix = "", .filter = null, .link_libs = BufSet.init(builder.allocator), - .target = Target { .Native = {} }, + .target = Target{ .Native = {} }, .exec_cmd_args = null, .include_dirs = ArrayList([]const u8).init(builder.allocator), }; @@ -1674,16 +1651,12 @@ pub const TestStep = struct { self.filter = text; } - pub fn setTarget(self: &TestStep, target_arch: builtin.Arch, target_os: builtin.Os, - target_environ: builtin.Environ) void - { - self.target = Target { - .Cross = CrossTarget { - .arch = target_arch, - .os = target_os, - .environ = target_environ, - } - }; + pub fn setTarget(self: &TestStep, target_arch: builtin.Arch, target_os: builtin.Os, target_environ: builtin.Environ) void { + self.target = Target{ .Cross = CrossTarget{ + .arch = target_arch, + .os = target_os, + .environ = target_environ, + } }; } pub fn setExecCmd(self: &TestStep, args: []const ?[]const u8) void { @@ -1789,11 +1762,9 @@ pub const CommandStep = struct { env_map: &const BufMap, /// ::argv is copied. - pub fn create(builder: &Builder, cwd: ?[]const u8, env_map: &const BufMap, - argv: []const []const u8) &CommandStep - { + pub fn create(builder: &Builder, cwd: ?[]const u8, env_map: &const BufMap, argv: []const []const u8) &CommandStep { const self = builder.allocator.create(CommandStep) catch unreachable; - *self = CommandStep { + self.* = CommandStep{ .builder = builder, .step = Step.init(argv[0], builder.allocator, make), .argv = builder.allocator.alloc([]u8, argv.len) catch unreachable, @@ -1828,7 +1799,7 @@ const InstallArtifactStep = struct { LibExeObjStep.Kind.Exe => builder.exe_dir, LibExeObjStep.Kind.Lib => builder.lib_dir, }; - *self = Self { + self.* = Self{ .builder = builder, .step = Step.init(builder.fmt("install {}", artifact.step.name), builder.allocator, make), .artifact = artifact, @@ -1837,10 +1808,8 @@ const InstallArtifactStep = struct { self.step.dependOn(&artifact.step); builder.pushInstalledFile(self.dest_file); if (self.artifact.kind == LibExeObjStep.Kind.Lib and !self.artifact.static) { - builder.pushInstalledFile(os.path.join(builder.allocator, builder.lib_dir, - artifact.major_only_filename) catch unreachable); - builder.pushInstalledFile(os.path.join(builder.allocator, builder.lib_dir, - artifact.name_only_filename) catch unreachable); + builder.pushInstalledFile(os.path.join(builder.allocator, builder.lib_dir, artifact.major_only_filename) catch unreachable); + builder.pushInstalledFile(os.path.join(builder.allocator, builder.lib_dir, artifact.name_only_filename) catch unreachable); } return self; } @@ -1859,8 +1828,7 @@ const InstallArtifactStep = struct { }; try builder.copyFileMode(self.artifact.getOutputPath(), self.dest_file, mode); if (self.artifact.kind == LibExeObjStep.Kind.Lib and !self.artifact.static) { - try doAtomicSymLinks(builder.allocator, self.dest_file, - self.artifact.major_only_filename, self.artifact.name_only_filename); + try doAtomicSymLinks(builder.allocator, self.dest_file, self.artifact.major_only_filename, self.artifact.name_only_filename); } } }; @@ -1872,7 +1840,7 @@ pub const InstallFileStep = struct { dest_path: []const u8, pub fn init(builder: &Builder, src_path: []const u8, dest_path: []const u8) InstallFileStep { - return InstallFileStep { + return InstallFileStep{ .builder = builder, .step = Step.init(builder.fmt("install {}", src_path), builder.allocator, make), .src_path = src_path, @@ -1893,7 +1861,7 @@ pub const WriteFileStep = struct { data: []const u8, pub fn init(builder: &Builder, file_path: []const u8, data: []const u8) WriteFileStep { - return WriteFileStep { + return WriteFileStep{ .builder = builder, .step = Step.init(builder.fmt("writefile {}", file_path), builder.allocator, make), .file_path = file_path, @@ -1922,7 +1890,7 @@ pub const LogStep = struct { data: []const u8, pub fn init(builder: &Builder, data: []const u8) LogStep { - return LogStep { + return LogStep{ .builder = builder, .step = Step.init(builder.fmt("log {}", data), builder.allocator, make), .data = data, @@ -1941,7 +1909,7 @@ pub const RemoveDirStep = struct { dir_path: []const u8, pub fn init(builder: &Builder, dir_path: []const u8) RemoveDirStep { - return RemoveDirStep { + return RemoveDirStep{ .builder = builder, .step = Step.init(builder.fmt("RemoveDir {}", dir_path), builder.allocator, make), .dir_path = dir_path, @@ -1966,8 +1934,8 @@ pub const Step = struct { loop_flag: bool, done_flag: bool, - pub fn init(name: []const u8, allocator: &Allocator, makeFn: fn (&Step)error!void) Step { - return Step { + pub fn init(name: []const u8, allocator: &Allocator, makeFn: fn(&Step) error!void) Step { + return Step{ .name = name, .makeFn = makeFn, .dependencies = ArrayList(&Step).init(allocator), @@ -1980,8 +1948,7 @@ pub const Step = struct { } pub fn make(self: &Step) !void { - if (self.done_flag) - return; + if (self.done_flag) return; try self.makeFn(self); self.done_flag = true; @@ -1994,9 +1961,7 @@ pub const Step = struct { fn makeNoOp(self: &Step) error!void {} }; -fn doAtomicSymLinks(allocator: &Allocator, output_path: []const u8, filename_major_only: []const u8, - filename_name_only: []const u8) !void -{ +fn doAtomicSymLinks(allocator: &Allocator, output_path: []const u8, filename_major_only: []const u8, filename_name_only: []const u8) !void { const out_dir = os.path.dirname(output_path); const out_basename = os.path.basename(output_path); // sym link for libfoo.so.1 to libfoo.so.1.2.3 diff --git a/std/crypto/blake2.zig b/std/crypto/blake2.zig index 99f0e629cd..18025d08eb 100644 --- a/std/crypto/blake2.zig +++ b/std/crypto/blake2.zig @@ -6,11 +6,23 @@ const builtin = @import("builtin"); const htest = @import("test.zig"); const RoundParam = struct { - a: usize, b: usize, c: usize, d: usize, x: usize, y: usize, + a: usize, + b: usize, + c: usize, + d: usize, + x: usize, + y: usize, }; fn Rp(a: usize, b: usize, c: usize, d: usize, x: usize, y: usize) RoundParam { - return RoundParam { .a = a, .b = b, .c = c, .d = d, .x = x, .y = y, }; + return RoundParam{ + .a = a, + .b = b, + .c = c, + .d = d, + .x = x, + .y = y, + }; } ///////////////////// @@ -19,145 +31,153 @@ fn Rp(a: usize, b: usize, c: usize, d: usize, x: usize, y: usize) RoundParam { pub const Blake2s224 = Blake2s(224); pub const Blake2s256 = Blake2s(256); -fn Blake2s(comptime out_len: usize) type { return struct { - const Self = this; - const block_size = 64; - const digest_size = out_len / 8; +fn Blake2s(comptime out_len: usize) type { + return struct { + const Self = this; + const block_size = 64; + const digest_size = out_len / 8; + + const iv = [8]u32{ + 0x6A09E667, + 0xBB67AE85, + 0x3C6EF372, + 0xA54FF53A, + 0x510E527F, + 0x9B05688C, + 0x1F83D9AB, + 0x5BE0CD19, + }; - const iv = [8]u32 { - 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, - 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, - }; + const sigma = [10][16]u8{ + []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + }; - const sigma = [10][16]u8 { - []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, - []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, - []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, - []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, - []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, - []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, - []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, - []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, - }; + h: [8]u32, + t: u64, + // Streaming cache + buf: [64]u8, + buf_len: u8, - h: [8]u32, - t: u64, - // Streaming cache - buf: [64]u8, - buf_len: u8, - - pub fn init() Self { - debug.assert(8 <= out_len and out_len <= 512); - - var s: Self = undefined; - s.reset(); - return s; - } - - pub fn reset(d: &Self) void { - mem.copy(u32, d.h[0..], iv[0..]); - - // No key plus default parameters - d.h[0] ^= 0x01010000 ^ u32(out_len >> 3); - d.t = 0; - d.buf_len = 0; - } - - pub fn hash(b: []const u8, out: []u8) void { - var d = Self.init(); - d.update(b); - d.final(out); - } - - pub fn update(d: &Self, b: []const u8) void { - var off: usize = 0; - - // Partial buffer exists from previous update. Copy into buffer then hash. - if (d.buf_len != 0 and d.buf_len + b.len > 64) { - off += 64 - d.buf_len; - mem.copy(u8, d.buf[d.buf_len..], b[0..off]); - d.t += 64; - d.round(d.buf[0..], false); - d.buf_len = 0; + pub fn init() Self { + debug.assert(8 <= out_len and out_len <= 512); + + var s: Self = undefined; + s.reset(); + return s; } - // Full middle blocks. - while (off + 64 <= b.len) : (off += 64) { - d.t += 64; - d.round(b[off..off + 64], false); + pub fn reset(d: &Self) void { + mem.copy(u32, d.h[0..], iv[0..]); + + // No key plus default parameters + d.h[0] ^= 0x01010000 ^ u32(out_len >> 3); + d.t = 0; + d.buf_len = 0; } - // Copy any remainder for next pass. - mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); - } + pub fn hash(b: []const u8, out: []u8) void { + var d = Self.init(); + d.update(b); + d.final(out); + } - pub fn final(d: &Self, out: []u8) void { - debug.assert(out.len >= out_len / 8); + pub fn update(d: &Self, b: []const u8) void { + var off: usize = 0; - mem.set(u8, d.buf[d.buf_len..], 0); - d.t += d.buf_len; - d.round(d.buf[0..], true); + // Partial buffer exists from previous update. Copy into buffer then hash. + if (d.buf_len != 0 and d.buf_len + b.len > 64) { + off += 64 - d.buf_len; + mem.copy(u8, d.buf[d.buf_len..], b[0..off]); + d.t += 64; + d.round(d.buf[0..], false); + d.buf_len = 0; + } - const rr = d.h[0 .. out_len / 32]; + // Full middle blocks. + while (off + 64 <= b.len) : (off += 64) { + d.t += 64; + d.round(b[off..off + 64], false); + } - for (rr) |s, j| { - mem.writeInt(out[4*j .. 4*j + 4], s, builtin.Endian.Little); + // Copy any remainder for next pass. + mem.copy(u8, d.buf[d.buf_len..], b[off..]); + d.buf_len += u8(b[off..].len); } - } - fn round(d: &Self, b: []const u8, last: bool) void { - debug.assert(b.len == 64); + pub fn final(d: &Self, out: []u8) void { + debug.assert(out.len >= out_len / 8); - var m: [16]u32 = undefined; - var v: [16]u32 = undefined; + mem.set(u8, d.buf[d.buf_len..], 0); + d.t += d.buf_len; + d.round(d.buf[0..], true); - for (m) |*r, i| { - *r = mem.readIntLE(u32, b[4*i .. 4*i + 4]); - } + const rr = d.h[0..out_len / 32]; - var k: usize = 0; - while (k < 8) : (k += 1) { - v[k] = d.h[k]; - v[k+8] = iv[k]; + for (rr) |s, j| { + mem.writeInt(out[4 * j..4 * j + 4], s, builtin.Endian.Little); + } } - v[12] ^= @truncate(u32, d.t); - v[13] ^= u32(d.t >> 32); - if (last) v[14] = ~v[14]; - - const rounds = comptime []RoundParam { - Rp(0, 4, 8, 12, 0, 1), - Rp(1, 5, 9, 13, 2, 3), - Rp(2, 6, 10, 14, 4, 5), - Rp(3, 7, 11, 15, 6, 7), - Rp(0, 5, 10, 15, 8, 9), - Rp(1, 6, 11, 12, 10, 11), - Rp(2, 7, 8, 13, 12, 13), - Rp(3, 4, 9, 14, 14, 15), - }; + fn round(d: &Self, b: []const u8, last: bool) void { + debug.assert(b.len == 64); - comptime var j: usize = 0; - inline while (j < 10) : (j += 1) { - inline for (rounds) |r| { - v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; - v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(16)); - v[r.c] = v[r.c] +% v[r.d]; - v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(12)); - v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; - v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(8)); - v[r.c] = v[r.c] +% v[r.d]; - v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(7)); + var m: [16]u32 = undefined; + var v: [16]u32 = undefined; + + for (m) |*r, i| { + r.* = mem.readIntLE(u32, b[4 * i..4 * i + 4]); } - } - for (d.h) |*r, i| { - *r ^= v[i] ^ v[i + 8]; + var k: usize = 0; + while (k < 8) : (k += 1) { + v[k] = d.h[k]; + v[k + 8] = iv[k]; + } + + v[12] ^= @truncate(u32, d.t); + v[13] ^= u32(d.t >> 32); + if (last) v[14] = ~v[14]; + + const rounds = comptime []RoundParam{ + Rp(0, 4, 8, 12, 0, 1), + Rp(1, 5, 9, 13, 2, 3), + Rp(2, 6, 10, 14, 4, 5), + Rp(3, 7, 11, 15, 6, 7), + Rp(0, 5, 10, 15, 8, 9), + Rp(1, 6, 11, 12, 10, 11), + Rp(2, 7, 8, 13, 12, 13), + Rp(3, 4, 9, 14, 14, 15), + }; + + comptime var j: usize = 0; + inline while (j < 10) : (j += 1) { + inline for (rounds) |r| { + v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; + v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(16)); + v[r.c] = v[r.c] +% v[r.d]; + v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(12)); + v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; + v[r.d] = math.rotr(u32, v[r.d] ^ v[r.a], usize(8)); + v[r.c] = v[r.c] +% v[r.d]; + v[r.b] = math.rotr(u32, v[r.b] ^ v[r.c], usize(7)); + } + } + + for (d.h) |*r, i| { + r.* ^= v[i] ^ v[i + 8]; + } } - } -};} + }; +} test "blake2s224 single" { const h1 = "1fa1291e65248b37b3433475b2a0dd63d54a11ecc4e3e034e7bc1ef4"; @@ -230,7 +250,7 @@ test "blake2s256 streaming" { } test "blake2s256 aligned final" { - var block = []u8 {0} ** Blake2s256.block_size; + var block = []u8{0} ** Blake2s256.block_size; var out: [Blake2s256.digest_size]u8 = undefined; var h = Blake2s256.init(); @@ -238,154 +258,363 @@ test "blake2s256 aligned final" { h.final(out[0..]); } - ///////////////////// // Blake2b pub const Blake2b384 = Blake2b(384); pub const Blake2b512 = Blake2b(512); -fn Blake2b(comptime out_len: usize) type { return struct { - const Self = this; - const block_size = 128; - const digest_size = out_len / 8; +fn Blake2b(comptime out_len: usize) type { + return struct { + const Self = this; + const block_size = 128; + const digest_size = out_len / 8; + + const iv = [8]u64{ + 0x6a09e667f3bcc908, + 0xbb67ae8584caa73b, + 0x3c6ef372fe94f82b, + 0xa54ff53a5f1d36f1, + 0x510e527fade682d1, + 0x9b05688c2b3e6c1f, + 0x1f83d9abfb41bd6b, + 0x5be0cd19137e2179, + }; - const iv = [8]u64 { - 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, - 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, - 0x510e527fade682d1, 0x9b05688c2b3e6c1f, - 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, - }; + const sigma = [12][16]u8{ + []const u8{ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }, + []const u8{ + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3, + }, + []const u8{ + 11, + 8, + 12, + 0, + 5, + 2, + 15, + 13, + 10, + 14, + 3, + 6, + 7, + 1, + 9, + 4, + }, + []const u8{ + 7, + 9, + 3, + 1, + 13, + 12, + 11, + 14, + 2, + 6, + 5, + 10, + 4, + 0, + 15, + 8, + }, + []const u8{ + 9, + 0, + 5, + 7, + 2, + 4, + 10, + 15, + 14, + 1, + 11, + 12, + 6, + 8, + 3, + 13, + }, + []const u8{ + 2, + 12, + 6, + 10, + 0, + 11, + 8, + 3, + 4, + 13, + 7, + 5, + 15, + 14, + 1, + 9, + }, + []const u8{ + 12, + 5, + 1, + 15, + 14, + 13, + 4, + 10, + 0, + 7, + 6, + 3, + 9, + 2, + 8, + 11, + }, + []const u8{ + 13, + 11, + 7, + 14, + 12, + 1, + 3, + 9, + 5, + 0, + 15, + 4, + 8, + 6, + 2, + 10, + }, + []const u8{ + 6, + 15, + 14, + 9, + 11, + 3, + 0, + 8, + 12, + 2, + 13, + 7, + 1, + 4, + 10, + 5, + }, + []const u8{ + 10, + 2, + 8, + 4, + 7, + 6, + 1, + 5, + 15, + 11, + 9, + 14, + 3, + 12, + 13, + 0, + }, + []const u8{ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }, + []const u8{ + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3, + }, + }; - const sigma = [12][16]u8 { - []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - []const u8 { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, - []const u8 { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, - []const u8 { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, - []const u8 { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, - []const u8 { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, - []const u8 { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, - []const u8 { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, - []const u8 { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 }, - []const u8 { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, - []const u8 { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, - }; + h: [8]u64, + t: u128, + // Streaming cache + buf: [128]u8, + buf_len: u8, - h: [8]u64, - t: u128, - // Streaming cache - buf: [128]u8, - buf_len: u8, - - pub fn init() Self { - debug.assert(8 <= out_len and out_len <= 512); - - var s: Self = undefined; - s.reset(); - return s; - } - - pub fn reset(d: &Self) void { - mem.copy(u64, d.h[0..], iv[0..]); - - // No key plus default parameters - d.h[0] ^= 0x01010000 ^ (out_len >> 3); - d.t = 0; - d.buf_len = 0; - } - - pub fn hash(b: []const u8, out: []u8) void { - var d = Self.init(); - d.update(b); - d.final(out); - } - - pub fn update(d: &Self, b: []const u8) void { - var off: usize = 0; - - // Partial buffer exists from previous update. Copy into buffer then hash. - if (d.buf_len != 0 and d.buf_len + b.len > 128) { - off += 128 - d.buf_len; - mem.copy(u8, d.buf[d.buf_len..], b[0..off]); - d.t += 128; - d.round(d.buf[0..], false); + pub fn init() Self { + debug.assert(8 <= out_len and out_len <= 512); + + var s: Self = undefined; + s.reset(); + return s; + } + + pub fn reset(d: &Self) void { + mem.copy(u64, d.h[0..], iv[0..]); + + // No key plus default parameters + d.h[0] ^= 0x01010000 ^ (out_len >> 3); + d.t = 0; d.buf_len = 0; } - // Full middle blocks. - while (off + 128 <= b.len) : (off += 128) { - d.t += 128; - d.round(b[off..off + 128], false); + pub fn hash(b: []const u8, out: []u8) void { + var d = Self.init(); + d.update(b); + d.final(out); } - // Copy any remainder for next pass. - mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); - } + pub fn update(d: &Self, b: []const u8) void { + var off: usize = 0; - pub fn final(d: &Self, out: []u8) void { - mem.set(u8, d.buf[d.buf_len..], 0); - d.t += d.buf_len; - d.round(d.buf[0..], true); + // Partial buffer exists from previous update. Copy into buffer then hash. + if (d.buf_len != 0 and d.buf_len + b.len > 128) { + off += 128 - d.buf_len; + mem.copy(u8, d.buf[d.buf_len..], b[0..off]); + d.t += 128; + d.round(d.buf[0..], false); + d.buf_len = 0; + } - const rr = d.h[0 .. out_len / 64]; + // Full middle blocks. + while (off + 128 <= b.len) : (off += 128) { + d.t += 128; + d.round(b[off..off + 128], false); + } - for (rr) |s, j| { - mem.writeInt(out[8*j .. 8*j + 8], s, builtin.Endian.Little); + // Copy any remainder for next pass. + mem.copy(u8, d.buf[d.buf_len..], b[off..]); + d.buf_len += u8(b[off..].len); } - } - fn round(d: &Self, b: []const u8, last: bool) void { - debug.assert(b.len == 128); + pub fn final(d: &Self, out: []u8) void { + mem.set(u8, d.buf[d.buf_len..], 0); + d.t += d.buf_len; + d.round(d.buf[0..], true); - var m: [16]u64 = undefined; - var v: [16]u64 = undefined; + const rr = d.h[0..out_len / 64]; - for (m) |*r, i| { - *r = mem.readIntLE(u64, b[8*i .. 8*i + 8]); + for (rr) |s, j| { + mem.writeInt(out[8 * j..8 * j + 8], s, builtin.Endian.Little); + } } - var k: usize = 0; - while (k < 8) : (k += 1) { - v[k] = d.h[k]; - v[k+8] = iv[k]; - } + fn round(d: &Self, b: []const u8, last: bool) void { + debug.assert(b.len == 128); - v[12] ^= @truncate(u64, d.t); - v[13] ^= u64(d.t >> 64); - if (last) v[14] = ~v[14]; - - const rounds = comptime []RoundParam { - Rp(0, 4, 8, 12, 0, 1), - Rp(1, 5, 9, 13, 2, 3), - Rp(2, 6, 10, 14, 4, 5), - Rp(3, 7, 11, 15, 6, 7), - Rp(0, 5, 10, 15, 8, 9), - Rp(1, 6, 11, 12, 10, 11), - Rp(2, 7, 8, 13, 12, 13), - Rp(3, 4, 9, 14, 14, 15), - }; + var m: [16]u64 = undefined; + var v: [16]u64 = undefined; - comptime var j: usize = 0; - inline while (j < 12) : (j += 1) { - inline for (rounds) |r| { - v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; - v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(32)); - v[r.c] = v[r.c] +% v[r.d]; - v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(24)); - v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; - v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(16)); - v[r.c] = v[r.c] +% v[r.d]; - v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(63)); + for (m) |*r, i| { + r.* = mem.readIntLE(u64, b[8 * i..8 * i + 8]); + } + + var k: usize = 0; + while (k < 8) : (k += 1) { + v[k] = d.h[k]; + v[k + 8] = iv[k]; } - } - for (d.h) |*r, i| { - *r ^= v[i] ^ v[i + 8]; + v[12] ^= @truncate(u64, d.t); + v[13] ^= u64(d.t >> 64); + if (last) v[14] = ~v[14]; + + const rounds = comptime []RoundParam{ + Rp(0, 4, 8, 12, 0, 1), + Rp(1, 5, 9, 13, 2, 3), + Rp(2, 6, 10, 14, 4, 5), + Rp(3, 7, 11, 15, 6, 7), + Rp(0, 5, 10, 15, 8, 9), + Rp(1, 6, 11, 12, 10, 11), + Rp(2, 7, 8, 13, 12, 13), + Rp(3, 4, 9, 14, 14, 15), + }; + + comptime var j: usize = 0; + inline while (j < 12) : (j += 1) { + inline for (rounds) |r| { + v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.x]]; + v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(32)); + v[r.c] = v[r.c] +% v[r.d]; + v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(24)); + v[r.a] = v[r.a] +% v[r.b] +% m[sigma[j][r.y]]; + v[r.d] = math.rotr(u64, v[r.d] ^ v[r.a], usize(16)); + v[r.c] = v[r.c] +% v[r.d]; + v[r.b] = math.rotr(u64, v[r.b] ^ v[r.c], usize(63)); + } + } + + for (d.h) |*r, i| { + r.* ^= v[i] ^ v[i + 8]; + } } - } -};} + }; +} test "blake2b384 single" { const h1 = "b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100"; @@ -458,7 +687,7 @@ test "blake2b512 streaming" { } test "blake2b512 aligned final" { - var block = []u8 {0} ** Blake2b512.block_size; + var block = []u8{0} ** Blake2b512.block_size; var out: [Blake2b512.digest_size]u8 = undefined; var h = Blake2b512.init(); diff --git a/std/crypto/hmac.zig b/std/crypto/hmac.zig index 2a36f15b71..1415e88cf4 100644 --- a/std/crypto/hmac.zig +++ b/std/crypto/hmac.zig @@ -29,12 +29,12 @@ pub fn Hmac(comptime H: type) type { var o_key_pad: [H.block_size]u8 = undefined; for (o_key_pad) |*b, i| { - *b = scratch[i] ^ 0x5c; + b.* = scratch[i] ^ 0x5c; } var i_key_pad: [H.block_size]u8 = undefined; for (i_key_pad) |*b, i| { - *b = scratch[i] ^ 0x36; + b.* = scratch[i] ^ 0x36; } // HMAC(k, m) = H(o_key_pad | H(i_key_pad | message)) where | is concatenation diff --git a/std/crypto/sha3.zig b/std/crypto/sha3.zig index f92f56d68f..73b6415e1d 100644 --- a/std/crypto/sha3.zig +++ b/std/crypto/sha3.zig @@ -10,148 +10,228 @@ pub const Sha3_256 = Keccak(256, 0x06); pub const Sha3_384 = Keccak(384, 0x06); pub const Sha3_512 = Keccak(512, 0x06); -fn Keccak(comptime bits: usize, comptime delim: u8) type { return struct { - const Self = this; - const block_size = 200; - const digest_size = bits / 8; - - s: [200]u8, - offset: usize, - rate: usize, - - pub fn init() Self { - var d: Self = undefined; - d.reset(); - return d; - } +fn Keccak(comptime bits: usize, comptime delim: u8) type { + return struct { + const Self = this; + const block_size = 200; + const digest_size = bits / 8; + + s: [200]u8, + offset: usize, + rate: usize, + + pub fn init() Self { + var d: Self = undefined; + d.reset(); + return d; + } - pub fn reset(d: &Self) void { - mem.set(u8, d.s[0..], 0); - d.offset = 0; - d.rate = 200 - (bits / 4); - } + pub fn reset(d: &Self) void { + mem.set(u8, d.s[0..], 0); + d.offset = 0; + d.rate = 200 - (bits / 4); + } - pub fn hash(b: []const u8, out: []u8) void { - var d = Self.init(); - d.update(b); - d.final(out); - } + pub fn hash(b: []const u8, out: []u8) void { + var d = Self.init(); + d.update(b); + d.final(out); + } - pub fn update(d: &Self, b: []const u8) void { - var ip: usize = 0; - var len = b.len; - var rate = d.rate - d.offset; - var offset = d.offset; + pub fn update(d: &Self, b: []const u8) void { + var ip: usize = 0; + var len = b.len; + var rate = d.rate - d.offset; + var offset = d.offset; - // absorb - while (len >= rate) { - for (d.s[offset .. offset + rate]) |*r, i| - *r ^= b[ip..][i]; + // absorb + while (len >= rate) { + for (d.s[offset..offset + rate]) |*r, i| + r.* ^= b[ip..][i]; - keccak_f(1600, d.s[0..]); + keccak_f(1600, d.s[0..]); - ip += rate; - len -= rate; - rate = d.rate; - offset = 0; - } + ip += rate; + len -= rate; + rate = d.rate; + offset = 0; + } - for (d.s[offset .. offset + len]) |*r, i| - *r ^= b[ip..][i]; + for (d.s[offset..offset + len]) |*r, i| + r.* ^= b[ip..][i]; - d.offset = offset + len; - } + d.offset = offset + len; + } - pub fn final(d: &Self, out: []u8) void { - // padding - d.s[d.offset] ^= delim; - d.s[d.rate - 1] ^= 0x80; + pub fn final(d: &Self, out: []u8) void { + // padding + d.s[d.offset] ^= delim; + d.s[d.rate - 1] ^= 0x80; - keccak_f(1600, d.s[0..]); + keccak_f(1600, d.s[0..]); - // squeeze - var op: usize = 0; - var len: usize = bits / 8; + // squeeze + var op: usize = 0; + var len: usize = bits / 8; - while (len >= d.rate) { - mem.copy(u8, out[op..], d.s[0..d.rate]); - keccak_f(1600, d.s[0..]); - op += d.rate; - len -= d.rate; + while (len >= d.rate) { + mem.copy(u8, out[op..], d.s[0..d.rate]); + keccak_f(1600, d.s[0..]); + op += d.rate; + len -= d.rate; + } + + mem.copy(u8, out[op..], d.s[0..len]); } + }; +} - mem.copy(u8, out[op..], d.s[0..len]); - } -};} - -const RC = []const u64 { - 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, - 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, - 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, - 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, - 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, - 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, +const RC = []const u64{ + 0x0000000000000001, + 0x0000000000008082, + 0x800000000000808a, + 0x8000000080008000, + 0x000000000000808b, + 0x0000000080000001, + 0x8000000080008081, + 0x8000000000008009, + 0x000000000000008a, + 0x0000000000000088, + 0x0000000080008009, + 0x000000008000000a, + 0x000000008000808b, + 0x800000000000008b, + 0x8000000000008089, + 0x8000000000008003, + 0x8000000000008002, + 0x8000000000000080, + 0x000000000000800a, + 0x800000008000000a, + 0x8000000080008081, + 0x8000000000008080, + 0x0000000080000001, + 0x8000000080008008, }; -const ROTC = []const usize { - 1, 3, 6, 10, 15, 21, 28, 36, - 45, 55, 2, 14, 27, 41, 56, 8, - 25, 43, 62, 18, 39, 61, 20, 44 +const ROTC = []const usize{ + 1, + 3, + 6, + 10, + 15, + 21, + 28, + 36, + 45, + 55, + 2, + 14, + 27, + 41, + 56, + 8, + 25, + 43, + 62, + 18, + 39, + 61, + 20, + 44, }; -const PIL = []const usize { - 10, 7, 11, 17, 18, 3, 5, 16, - 8, 21, 24, 4, 15, 23, 19, 13, - 12, 2, 20, 14, 22, 9, 6, 1 +const PIL = []const usize{ + 10, + 7, + 11, + 17, + 18, + 3, + 5, + 16, + 8, + 21, + 24, + 4, + 15, + 23, + 19, + 13, + 12, + 2, + 20, + 14, + 22, + 9, + 6, + 1, }; -const M5 = []const usize { - 0, 1, 2, 3, 4, 0, 1, 2, 3, 4 +const M5 = []const usize{ + 0, + 1, + 2, + 3, + 4, + 0, + 1, + 2, + 3, + 4, }; fn keccak_f(comptime F: usize, d: []u8) void { debug.assert(d.len == F / 8); const B = F / 25; - const no_rounds = comptime x: { break :x 12 + 2 * math.log2(B); }; + const no_rounds = comptime x: { + break :x 12 + 2 * math.log2(B); + }; - var s = []const u64 {0} ** 25; - var t = []const u64 {0} ** 1; - var c = []const u64 {0} ** 5; + var s = []const u64{0} ** 25; + var t = []const u64{0} ** 1; + var c = []const u64{0} ** 5; for (s) |*r, i| { - *r = mem.readIntLE(u64, d[8*i .. 8*i + 8]); + r.* = mem.readIntLE(u64, d[8 * i..8 * i + 8]); } comptime var x: usize = 0; comptime var y: usize = 0; for (RC[0..no_rounds]) |round| { // theta - x = 0; inline while (x < 5) : (x += 1) { - c[x] = s[x] ^ s[x+5] ^ s[x+10] ^ s[x+15] ^ s[x+20]; + x = 0; + inline while (x < 5) : (x += 1) { + c[x] = s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]; } - x = 0; inline while (x < 5) : (x += 1) { - t[0] = c[M5[x+4]] ^ math.rotl(u64, c[M5[x+1]], usize(1)); - y = 0; inline while (y < 5) : (y += 1) { - s[x + y*5] ^= t[0]; + x = 0; + inline while (x < 5) : (x += 1) { + t[0] = c[M5[x + 4]] ^ math.rotl(u64, c[M5[x + 1]], usize(1)); + y = 0; + inline while (y < 5) : (y += 1) { + s[x + y * 5] ^= t[0]; } } // rho+pi t[0] = s[1]; - x = 0; inline while (x < 24) : (x += 1) { + x = 0; + inline while (x < 24) : (x += 1) { c[0] = s[PIL[x]]; s[PIL[x]] = math.rotl(u64, t[0], ROTC[x]); t[0] = c[0]; } // chi - y = 0; inline while (y < 5) : (y += 1) { - x = 0; inline while (x < 5) : (x += 1) { - c[x] = s[x + y*5]; + y = 0; + inline while (y < 5) : (y += 1) { + x = 0; + inline while (x < 5) : (x += 1) { + c[x] = s[x + y * 5]; } - x = 0; inline while (x < 5) : (x += 1) { - s[x + y*5] = c[x] ^ (~c[M5[x+1]] & c[M5[x+2]]); + x = 0; + inline while (x < 5) : (x += 1) { + s[x + y * 5] = c[x] ^ (~c[M5[x + 1]] & c[M5[x + 2]]); } } @@ -160,11 +240,10 @@ fn keccak_f(comptime F: usize, d: []u8) void { } for (s) |r, i| { - mem.writeInt(d[8*i .. 8*i + 8], r, builtin.Endian.Little); + mem.writeInt(d[8 * i..8 * i + 8], r, builtin.Endian.Little); } } - test "sha3-224 single" { htest.assertEqualHash(Sha3_224, "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", ""); htest.assertEqualHash(Sha3_224, "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", "abc"); @@ -192,7 +271,7 @@ test "sha3-224 streaming" { } test "sha3-256 single" { - htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a" , ""); + htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", ""); htest.assertEqualHash(Sha3_256, "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", "abc"); htest.assertEqualHash(Sha3_256, "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } @@ -218,7 +297,7 @@ test "sha3-256 streaming" { } test "sha3-256 aligned final" { - var block = []u8 {0} ** Sha3_256.block_size; + var block = []u8{0} ** Sha3_256.block_size; var out: [Sha3_256.digest_size]u8 = undefined; var h = Sha3_256.init(); @@ -228,7 +307,7 @@ test "sha3-256 aligned final" { test "sha3-384 single" { const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004"; - htest.assertEqualHash(Sha3_384, h1 , ""); + htest.assertEqualHash(Sha3_384, h1, ""); const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25"; htest.assertEqualHash(Sha3_384, h2, "abc"); const h3 = "79407d3b5916b59c3e30b09822974791c313fb9ecc849e406f23592d04f625dc8c709b98b43b3852b337216179aa7fc7"; @@ -259,7 +338,7 @@ test "sha3-384 streaming" { test "sha3-512 single" { const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"; - htest.assertEqualHash(Sha3_512, h1 , ""); + htest.assertEqualHash(Sha3_512, h1, ""); const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"; htest.assertEqualHash(Sha3_512, h2, "abc"); const h3 = "afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185"; @@ -289,7 +368,7 @@ test "sha3-512 streaming" { } test "sha3-512 aligned final" { - var block = []u8 {0} ** Sha3_512.block_size; + var block = []u8{0} ** Sha3_512.block_size; var out: [Sha3_512.digest_size]u8 = undefined; var h = Sha3_512.init(); diff --git a/std/event.zig b/std/event.zig index bdad7fcc18..b2e7e3ae38 100644 --- a/std/event.zig +++ b/std/event.zig @@ -6,7 +6,7 @@ const mem = std.mem; const posix = std.os.posix; pub const TcpServer = struct { - handleRequestFn: async<&mem.Allocator> fn (&TcpServer, &const std.net.Address, &const std.os.File) void, + handleRequestFn: async<&mem.Allocator> fn(&TcpServer, &const std.net.Address, &const std.os.File) void, loop: &Loop, sockfd: i32, @@ -18,13 +18,11 @@ pub const TcpServer = struct { const PromiseNode = std.LinkedList(promise).Node; pub fn init(loop: &Loop) !TcpServer { - const sockfd = try std.os.posixSocket(posix.AF_INET, - posix.SOCK_STREAM|posix.SOCK_CLOEXEC|posix.SOCK_NONBLOCK, - posix.PROTO_tcp); + const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); errdefer std.os.close(sockfd); // TODO can't initialize handler coroutine here because we need well defined copy elision - return TcpServer { + return TcpServer{ .loop = loop, .sockfd = sockfd, .accept_coro = null, @@ -34,9 +32,7 @@ pub const TcpServer = struct { }; } - pub fn listen(self: &TcpServer, address: &const std.net.Address, - handleRequestFn: async<&mem.Allocator> fn (&TcpServer, &const std.net.Address, &const std.os.File)void) !void - { + pub fn listen(self: &TcpServer, address: &const std.net.Address, handleRequestFn: async<&mem.Allocator> fn(&TcpServer, &const std.net.Address, &const std.os.File) void) !void { self.handleRequestFn = handleRequestFn; try std.os.posixBind(self.sockfd, &address.os_addr); @@ -48,7 +44,6 @@ pub const TcpServer = struct { try self.loop.addFd(self.sockfd, ??self.accept_coro); errdefer self.loop.removeFd(self.sockfd); - } pub fn deinit(self: &TcpServer) void { @@ -60,9 +55,7 @@ pub const TcpServer = struct { pub async fn handler(self: &TcpServer) void { while (true) { var accepted_addr: std.net.Address = undefined; - if (std.os.posixAccept(self.sockfd, &accepted_addr.os_addr, - posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| - { + if (std.os.posixAccept(self.sockfd, &accepted_addr.os_addr, posix.SOCK_NONBLOCK | posix.SOCK_CLOEXEC)) |accepted_fd| { var socket = std.os.File.openHandle(accepted_fd); _ = async self.handleRequestFn(self, accepted_addr, socket) catch |err| switch (err) { error.OutOfMemory => { @@ -110,7 +103,7 @@ pub const Loop = struct { fn init(allocator: &mem.Allocator) !Loop { const epollfd = try std.os.linuxEpollCreate(std.os.linux.EPOLL_CLOEXEC); - return Loop { + return Loop{ .keep_running = true, .allocator = allocator, .epollfd = epollfd, @@ -118,11 +111,9 @@ pub const Loop = struct { } pub fn addFd(self: &Loop, fd: i32, prom: promise) !void { - var ev = std.os.linux.epoll_event { - .events = std.os.linux.EPOLLIN|std.os.linux.EPOLLOUT|std.os.linux.EPOLLET, - .data = std.os.linux.epoll_data { - .ptr = @ptrToInt(prom), - }, + var ev = std.os.linux.epoll_event{ + .events = std.os.linux.EPOLLIN | std.os.linux.EPOLLOUT | std.os.linux.EPOLLET, + .data = std.os.linux.epoll_data{ .ptr = @ptrToInt(prom) }, }; try std.os.linuxEpollCtl(self.epollfd, std.os.linux.EPOLL_CTL_ADD, fd, &ev); } @@ -157,9 +148,9 @@ pub const Loop = struct { }; pub async fn connect(loop: &Loop, _address: &const std.net.Address) !std.os.File { - var address = *_address; // TODO https://github.com/zig-lang/zig/issues/733 + var address = _address.*; // TODO https://github.com/zig-lang/zig/issues/733 - const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM|posix.SOCK_CLOEXEC|posix.SOCK_NONBLOCK, posix.PROTO_tcp); + const sockfd = try std.os.posixSocket(posix.AF_INET, posix.SOCK_STREAM | posix.SOCK_CLOEXEC | posix.SOCK_NONBLOCK, posix.PROTO_tcp); errdefer std.os.close(sockfd); try std.os.posixConnectAsync(sockfd, &address.os_addr); @@ -179,11 +170,9 @@ test "listen on a port, send bytes, receive bytes" { const Self = this; - async<&mem.Allocator> fn handler(tcp_server: &TcpServer, _addr: &const std.net.Address, - _socket: &const std.os.File) void - { + async<&mem.Allocator> fn handler(tcp_server: &TcpServer, _addr: &const std.net.Address, _socket: &const std.os.File) void { const self = @fieldParentPtr(Self, "tcp_server", tcp_server); - var socket = *_socket; // TODO https://github.com/zig-lang/zig/issues/733 + var socket = _socket.*; // TODO https://github.com/zig-lang/zig/issues/733 defer socket.close(); const next_handler = async errorableHandler(self, _addr, socket) catch |err| switch (err) { error.OutOfMemory => @panic("unable to handle connection: out of memory"), @@ -191,14 +180,14 @@ test "listen on a port, send bytes, receive bytes" { (await next_handler) catch |err| { std.debug.panic("unable to handle connection: {}\n", err); }; - suspend |p| { cancel p; } + suspend |p| { + cancel p; + } } - async fn errorableHandler(self: &Self, _addr: &const std.net.Address, - _socket: &const std.os.File) !void - { - const addr = *_addr; // TODO https://github.com/zig-lang/zig/issues/733 - var socket = *_socket; // TODO https://github.com/zig-lang/zig/issues/733 + async fn errorableHandler(self: &Self, _addr: &const std.net.Address, _socket: &const std.os.File) !void { + const addr = _addr.*; // TODO https://github.com/zig-lang/zig/issues/733 + var socket = _socket.*; // TODO https://github.com/zig-lang/zig/issues/733 var adapter = std.io.FileOutStream.init(&socket); var stream = &adapter.stream; @@ -210,9 +199,7 @@ test "listen on a port, send bytes, receive bytes" { const addr = std.net.Address.initIp4(ip4addr, 0); var loop = try Loop.init(std.debug.global_allocator); - var server = MyServer { - .tcp_server = try TcpServer.init(&loop), - }; + var server = MyServer{ .tcp_server = try TcpServer.init(&loop) }; defer server.tcp_server.deinit(); try server.tcp_server.listen(addr, MyServer.handler); diff --git a/std/hash/crc.zig b/std/hash/crc.zig index f88069ce3c..e4c1405a1c 100644 --- a/std/hash/crc.zig +++ b/std/hash/crc.zig @@ -9,9 +9,9 @@ const std = @import("../index.zig"); const debug = std.debug; pub const Polynomial = struct { - const IEEE = 0xedb88320; + const IEEE = 0xedb88320; const Castagnoli = 0x82f63b78; - const Koopman = 0xeb31d82e; + const Koopman = 0xeb31d82e; }; // IEEE is by far the most common CRC and so is aliased by default. @@ -27,20 +27,22 @@ pub fn Crc32WithPoly(comptime poly: u32) type { for (tables[0]) |*e, i| { var crc = u32(i); - var j: usize = 0; while (j < 8) : (j += 1) { + var j: usize = 0; + while (j < 8) : (j += 1) { if (crc & 1 == 1) { crc = (crc >> 1) ^ poly; } else { crc = (crc >> 1); } } - *e = crc; + e.* = crc; } var i: usize = 0; while (i < 256) : (i += 1) { var crc = tables[0][i]; - var j: usize = 1; while (j < 8) : (j += 1) { + var j: usize = 1; + while (j < 8) : (j += 1) { const index = @truncate(u8, crc); crc = tables[0][index] ^ (crc >> 8); tables[j][i] = crc; @@ -53,22 +55,21 @@ pub fn Crc32WithPoly(comptime poly: u32) type { crc: u32, pub fn init() Self { - return Self { - .crc = 0xffffffff, - }; + return Self{ .crc = 0xffffffff }; } pub fn update(self: &Self, input: []const u8) void { var i: usize = 0; while (i + 8 <= input.len) : (i += 8) { - const p = input[i..i+8]; + const p = input[i..i + 8]; // Unrolling this way gives ~50Mb/s increase - self.crc ^= (u32(p[0]) << 0); - self.crc ^= (u32(p[1]) << 8); + self.crc ^= (u32(p[0]) << 0); + self.crc ^= (u32(p[1]) << 8); self.crc ^= (u32(p[2]) << 16); self.crc ^= (u32(p[3]) << 24); + self.crc = lookup_tables[0][p[7]] ^ lookup_tables[1][p[6]] ^ @@ -123,14 +124,15 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type { for (table) |*e, i| { var crc = u32(i * 16); - var j: usize = 0; while (j < 8) : (j += 1) { + var j: usize = 0; + while (j < 8) : (j += 1) { if (crc & 1 == 1) { crc = (crc >> 1) ^ poly; } else { crc = (crc >> 1); } } - *e = crc; + e.* = crc; } break :block table; @@ -139,9 +141,7 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type { crc: u32, pub fn init() Self { - return Self { - .crc = 0xffffffff, - }; + return Self{ .crc = 0xffffffff }; } pub fn update(self: &Self, input: []const u8) void { diff --git a/std/hash_map.zig b/std/hash_map.zig index 2a178d9d44..e3b86f8a3b 100644 --- a/std/hash_map.zig +++ b/std/hash_map.zig @@ -9,10 +9,7 @@ const builtin = @import("builtin"); const want_modification_safety = builtin.mode != builtin.Mode.ReleaseFast; const debug_u32 = if (want_modification_safety) u32 else void; -pub fn HashMap(comptime K: type, comptime V: type, - comptime hash: fn(key: K)u32, - comptime eql: fn(a: K, b: K)bool) type -{ +pub fn HashMap(comptime K: type, comptime V: type, comptime hash: fn(key: K) u32, comptime eql: fn(a: K, b: K) bool) type { return struct { entries: []Entry, size: usize, @@ -65,7 +62,7 @@ pub fn HashMap(comptime K: type, comptime V: type, }; pub fn init(allocator: &Allocator) Self { - return Self { + return Self{ .entries = []Entry{}, .allocator = allocator, .size = 0, @@ -129,34 +126,36 @@ pub fn HashMap(comptime K: type, comptime V: type, if (hm.entries.len == 0) return null; hm.incrementModificationCount(); const start_index = hm.keyToIndex(key); - {var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { - const index = (start_index + roll_over) % hm.entries.len; - var entry = &hm.entries[index]; - - if (!entry.used) - return null; - - if (!eql(entry.key, key)) continue; - - while (roll_over < hm.entries.len) : (roll_over += 1) { - const next_index = (start_index + roll_over + 1) % hm.entries.len; - const next_entry = &hm.entries[next_index]; - if (!next_entry.used or next_entry.distance_from_start_index == 0) { - entry.used = false; - hm.size -= 1; - return entry; + { + var roll_over: usize = 0; + while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { + const index = (start_index + roll_over) % hm.entries.len; + var entry = &hm.entries[index]; + + if (!entry.used) return null; + + if (!eql(entry.key, key)) continue; + + while (roll_over < hm.entries.len) : (roll_over += 1) { + const next_index = (start_index + roll_over + 1) % hm.entries.len; + const next_entry = &hm.entries[next_index]; + if (!next_entry.used or next_entry.distance_from_start_index == 0) { + entry.used = false; + hm.size -= 1; + return entry; + } + entry.* = next_entry.*; + entry.distance_from_start_index -= 1; + entry = next_entry; } - *entry = *next_entry; - entry.distance_from_start_index -= 1; - entry = next_entry; + unreachable; // shifting everything in the table } - unreachable; // shifting everything in the table - }} + } return null; } pub fn iterator(hm: &const Self) Iterator { - return Iterator { + return Iterator{ .hm = hm, .count = 0, .index = 0, @@ -182,21 +181,23 @@ pub fn HashMap(comptime K: type, comptime V: type, /// Returns the value that was already there. fn internalPut(hm: &Self, orig_key: K, orig_value: &const V) ?V { var key = orig_key; - var value = *orig_value; + var value = orig_value.*; const start_index = hm.keyToIndex(key); var roll_over: usize = 0; var distance_from_start_index: usize = 0; - while (roll_over < hm.entries.len) : ({roll_over += 1; distance_from_start_index += 1;}) { + while (roll_over < hm.entries.len) : ({ + roll_over += 1; + distance_from_start_index += 1; + }) { const index = (start_index + roll_over) % hm.entries.len; const entry = &hm.entries[index]; if (entry.used and !eql(entry.key, key)) { if (entry.distance_from_start_index < distance_from_start_index) { // robin hood to the rescue - const tmp = *entry; - hm.max_distance_from_start_index = math.max(hm.max_distance_from_start_index, - distance_from_start_index); - *entry = Entry { + const tmp = entry.*; + hm.max_distance_from_start_index = math.max(hm.max_distance_from_start_index, distance_from_start_index); + entry.* = Entry{ .used = true, .distance_from_start_index = distance_from_start_index, .key = key, @@ -219,7 +220,7 @@ pub fn HashMap(comptime K: type, comptime V: type, } hm.max_distance_from_start_index = math.max(distance_from_start_index, hm.max_distance_from_start_index); - *entry = Entry { + entry.* = Entry{ .used = true, .distance_from_start_index = distance_from_start_index, .key = key, @@ -232,13 +233,16 @@ pub fn HashMap(comptime K: type, comptime V: type, fn internalGet(hm: &const Self, key: K) ?&Entry { const start_index = hm.keyToIndex(key); - {var roll_over: usize = 0; while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { - const index = (start_index + roll_over) % hm.entries.len; - const entry = &hm.entries[index]; - - if (!entry.used) return null; - if (eql(entry.key, key)) return entry; - }} + { + var roll_over: usize = 0; + while (roll_over <= hm.max_distance_from_start_index) : (roll_over += 1) { + const index = (start_index + roll_over) % hm.entries.len; + const entry = &hm.entries[index]; + + if (!entry.used) return null; + if (eql(entry.key, key)) return entry; + } + } return null; } @@ -282,11 +286,19 @@ test "iterator hash map" { assert((reset_map.put(2, 22) catch unreachable) == null); assert((reset_map.put(3, 33) catch unreachable) == null); - var keys = []i32 { 1, 2, 3 }; - var values = []i32 { 11, 22, 33 }; + var keys = []i32{ + 1, + 2, + 3, + }; + var values = []i32{ + 11, + 22, + 33, + }; var it = reset_map.iterator(); - var count : usize = 0; + var count: usize = 0; while (it.next()) |next| { assert(next.key == keys[count]); assert(next.value == values[count]); @@ -305,7 +317,7 @@ test "iterator hash map" { } it.reset(); - var entry = ?? it.next(); + var entry = ??it.next(); assert(entry.key == keys[0]); assert(entry.value == values[0]); } diff --git a/std/json.zig b/std/json.zig index 6f853501ed..2ea9083e2f 100644 --- a/std/json.zig +++ b/std/json.zig @@ -35,7 +35,7 @@ pub const Token = struct { }; pub fn init(id: Id, count: usize, offset: u1) Token { - return Token { + return Token{ .id = id, .offset = offset, .string_has_escape = false, @@ -45,7 +45,7 @@ pub const Token = struct { } pub fn initString(count: usize, has_unicode_escape: bool) Token { - return Token { + return Token{ .id = Id.String, .offset = 0, .string_has_escape = has_unicode_escape, @@ -55,7 +55,7 @@ pub const Token = struct { } pub fn initNumber(count: usize, number_is_integer: bool) Token { - return Token { + return Token{ .id = Id.Number, .offset = 0, .string_has_escape = false, @@ -66,7 +66,7 @@ pub const Token = struct { // A marker token is a zero-length pub fn initMarker(id: Id) Token { - return Token { + return Token{ .id = id, .offset = 0, .string_has_escape = false, @@ -77,7 +77,7 @@ pub const Token = struct { // Slice into the underlying input string. pub fn slice(self: &const Token, input: []const u8, i: usize) []const u8 { - return input[i + self.offset - self.count .. i + self.offset]; + return input[i + self.offset - self.count..i + self.offset]; } }; @@ -105,8 +105,8 @@ const StreamingJsonParser = struct { stack: u256, stack_used: u8, - const object_bit = 0; - const array_bit = 1; + const object_bit = 0; + const array_bit = 1; const max_stack_size = @maxValue(u8); pub fn init() StreamingJsonParser { @@ -120,7 +120,7 @@ const StreamingJsonParser = struct { p.count = 0; // Set before ever read in main transition function p.after_string_state = undefined; - p.after_value_state = State.ValueEnd; // handle end of values normally + p.after_value_state = State.ValueEnd; // handle end of values normally p.stack = 0; p.stack_used = 0; p.complete = false; @@ -181,7 +181,7 @@ const StreamingJsonParser = struct { } }; - pub const Error = error { + pub const Error = error{ InvalidTopLevel, TooManyNestedItems, TooManyClosingItems, @@ -206,8 +206,8 @@ const StreamingJsonParser = struct { // // There is currently no error recovery on a bad stream. pub fn feed(p: &StreamingJsonParser, c: u8, token1: &?Token, token2: &?Token) Error!void { - *token1 = null; - *token2 = null; + token1.* = null; + token2.* = null; p.count += 1; // unlikely @@ -228,7 +228,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; - *token = Token.initMarker(Token.Id.ObjectBegin); + token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { p.stack <<= 1; @@ -238,7 +238,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; - *token = Token.initMarker(Token.Id.ArrayBegin); + token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.number_is_integer = true; @@ -281,7 +281,10 @@ const StreamingJsonParser = struct { p.after_value_state = State.TopLevelEnd; p.count = 0; }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -290,7 +293,10 @@ const StreamingJsonParser = struct { }, State.TopLevelEnd => switch (c) { - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -324,7 +330,7 @@ const StreamingJsonParser = struct { else => {}, } - *token = Token.initMarker(Token.Id.ObjectEnd); + token.* = Token.initMarker(Token.Id.ObjectEnd); }, ']' => { if (p.stack & 1 != array_bit) { @@ -348,7 +354,7 @@ const StreamingJsonParser = struct { else => {}, } - *token = Token.initMarker(Token.Id.ArrayEnd); + token.* = Token.initMarker(Token.Id.ArrayEnd); }, '{' => { if (p.stack_used == max_stack_size) { @@ -362,7 +368,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; - *token = Token.initMarker(Token.Id.ObjectBegin); + token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { if (p.stack_used == max_stack_size) { @@ -376,7 +382,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; - *token = Token.initMarker(Token.Id.ArrayBegin); + token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.state = State.Number; @@ -406,7 +412,10 @@ const StreamingJsonParser = struct { p.state = State.NullLiteral1; p.count = 0; }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -428,7 +437,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; - *token = Token.initMarker(Token.Id.ObjectBegin); + token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { if (p.stack_used == max_stack_size) { @@ -442,7 +451,7 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; - *token = Token.initMarker(Token.Id.ArrayBegin); + token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.state = State.Number; @@ -472,7 +481,10 @@ const StreamingJsonParser = struct { p.state = State.NullLiteral1; p.count = 0; }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -501,7 +513,7 @@ const StreamingJsonParser = struct { p.state = State.TopLevelEnd; } - *token = Token.initMarker(Token.Id.ArrayEnd); + token.* = Token.initMarker(Token.Id.ArrayEnd); }, '}' => { if (p.stack_used == 0) { @@ -519,9 +531,12 @@ const StreamingJsonParser = struct { p.state = State.TopLevelEnd; } - *token = Token.initMarker(Token.Id.ObjectEnd); + token.* = Token.initMarker(Token.Id.ObjectEnd); }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -534,7 +549,10 @@ const StreamingJsonParser = struct { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; }, - 0x09, 0x0A, 0x0D, 0x20 => { + 0x09, + 0x0A, + 0x0D, + 0x20 => { // whitespace }, else => { @@ -553,12 +571,15 @@ const StreamingJsonParser = struct { p.complete = true; } - *token = Token.initString(p.count - 1, p.string_has_escape); + token.* = Token.initString(p.count - 1, p.string_has_escape); }, '\\' => { p.state = State.StringEscapeCharacter; }, - 0x20, 0x21, 0x23 ... 0x5B, 0x5D ... 0x7F => { + 0x20, + 0x21, + 0x23 ... 0x5B, + 0x5D ... 0x7F => { // non-control ascii }, 0xC0 ... 0xDF => { @@ -599,7 +620,14 @@ const StreamingJsonParser = struct { // The current JSONTestSuite tests rely on both of this behaviour being present // however, so we default to the status quo where both are accepted until this // is further clarified. - '"', '\\', '/', 'b', 'f', 'n', 'r', 't' => { + '"', + '\\', + '/', + 'b', + 'f', + 'n', + 'r', + 't' => { p.string_has_escape = true; p.state = State.String; }, @@ -613,28 +641,36 @@ const StreamingJsonParser = struct { }, State.StringEscapeHexUnicode4 => switch (c) { - '0' ... '9', 'A' ... 'F', 'a' ... 'f' => { + '0' ... '9', + 'A' ... 'F', + 'a' ... 'f' => { p.state = State.StringEscapeHexUnicode3; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode3 => switch (c) { - '0' ... '9', 'A' ... 'F', 'a' ... 'f' => { + '0' ... '9', + 'A' ... 'F', + 'a' ... 'f' => { p.state = State.StringEscapeHexUnicode2; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode2 => switch (c) { - '0' ... '9', 'A' ... 'F', 'a' ... 'f' => { + '0' ... '9', + 'A' ... 'F', + 'a' ... 'f' => { p.state = State.StringEscapeHexUnicode1; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode1 => switch (c) { - '0' ... '9', 'A' ... 'F', 'a' ... 'f' => { + '0' ... '9', + 'A' ... 'F', + 'a' ... 'f' => { p.state = State.String; }, else => return error.InvalidUnicodeHexSymbol, @@ -662,13 +698,14 @@ const StreamingJsonParser = struct { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, - 'e', 'E' => { + 'e', + 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } @@ -681,7 +718,8 @@ const StreamingJsonParser = struct { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, - 'e', 'E' => { + 'e', + 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, @@ -690,7 +728,7 @@ const StreamingJsonParser = struct { }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } @@ -714,13 +752,14 @@ const StreamingJsonParser = struct { '0' ... '9' => { // another digit }, - 'e', 'E' => { + 'e', + 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } @@ -729,20 +768,22 @@ const StreamingJsonParser = struct { State.NumberMaybeExponent => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { - 'e', 'E' => { + 'e', + 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } }, State.NumberExponent => switch (c) { - '-', '+', => { + '-', + '+' => { p.complete = false; p.state = State.NumberExponentDigitsRequired; }, @@ -773,7 +814,7 @@ const StreamingJsonParser = struct { }, else => { p.state = p.after_value_state; - *token = Token.initNumber(p.count, p.number_is_integer); + token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } @@ -793,7 +834,7 @@ const StreamingJsonParser = struct { 'e' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; - *token = Token.init(Token.Id.True, p.count + 1, 1); + token.* = Token.init(Token.Id.True, p.count + 1, 1); }, else => { return error.InvalidLiteral; @@ -819,7 +860,7 @@ const StreamingJsonParser = struct { 'e' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; - *token = Token.init(Token.Id.False, p.count + 1, 1); + token.* = Token.init(Token.Id.False, p.count + 1, 1); }, else => { return error.InvalidLiteral; @@ -840,7 +881,7 @@ const StreamingJsonParser = struct { 'l' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; - *token = Token.init(Token.Id.Null, p.count + 1, 1); + token.* = Token.init(Token.Id.Null, p.count + 1, 1); }, else => { return error.InvalidLiteral; @@ -895,7 +936,7 @@ pub const Value = union(enum) { Object: ObjectMap, pub fn dump(self: &const Value) void { - switch (*self) { + switch (self.*) { Value.Null => { std.debug.warn("null"); }, @@ -950,7 +991,7 @@ pub const Value = union(enum) { } fn dumpIndentLevel(self: &const Value, indent: usize, level: usize) void { - switch (*self) { + switch (self.*) { Value.Null => { std.debug.warn("null"); }, @@ -1027,7 +1068,7 @@ const JsonParser = struct { }; pub fn init(allocator: &Allocator, copy_strings: bool) JsonParser { - return JsonParser { + return JsonParser{ .allocator = allocator, .state = State.Simple, .copy_strings = copy_strings, @@ -1082,7 +1123,7 @@ const JsonParser = struct { std.debug.assert(p.stack.len == 1); - return ValueTree { + return ValueTree{ .arena = arena, .root = p.stack.at(0), }; @@ -1115,11 +1156,11 @@ const JsonParser = struct { switch (token.id) { Token.Id.ObjectBegin => { - try p.stack.append(Value { .Object = ObjectMap.init(allocator) }); + try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { - try p.stack.append(Value { .Array = ArrayList(Value).init(allocator) }); + try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { @@ -1133,12 +1174,12 @@ const JsonParser = struct { p.state = State.ObjectKey; }, Token.Id.True => { - _ = try object.put(key, Value { .Bool = true }); + _ = try object.put(key, Value{ .Bool = true }); _ = p.stack.pop(); p.state = State.ObjectKey; }, Token.Id.False => { - _ = try object.put(key, Value { .Bool = false }); + _ = try object.put(key, Value{ .Bool = false }); _ = p.stack.pop(); p.state = State.ObjectKey; }, @@ -1165,11 +1206,11 @@ const JsonParser = struct { try p.pushToParent(value); }, Token.Id.ObjectBegin => { - try p.stack.append(Value { .Object = ObjectMap.init(allocator) }); + try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { - try p.stack.append(Value { .Array = ArrayList(Value).init(allocator) }); + try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { @@ -1179,10 +1220,10 @@ const JsonParser = struct { try array.append(try p.parseNumber(token, input, i)); }, Token.Id.True => { - try array.append(Value { .Bool = true }); + try array.append(Value{ .Bool = true }); }, Token.Id.False => { - try array.append(Value { .Bool = false }); + try array.append(Value{ .Bool = false }); }, Token.Id.Null => { try array.append(Value.Null); @@ -1194,11 +1235,11 @@ const JsonParser = struct { }, State.Simple => switch (token.id) { Token.Id.ObjectBegin => { - try p.stack.append(Value { .Object = ObjectMap.init(allocator) }); + try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { - try p.stack.append(Value { .Array = ArrayList(Value).init(allocator) }); + try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { @@ -1208,15 +1249,16 @@ const JsonParser = struct { try p.stack.append(try p.parseNumber(token, input, i)); }, Token.Id.True => { - try p.stack.append(Value { .Bool = true }); + try p.stack.append(Value{ .Bool = true }); }, Token.Id.False => { - try p.stack.append(Value { .Bool = false }); + try p.stack.append(Value{ .Bool = false }); }, Token.Id.Null => { try p.stack.append(Value.Null); }, - Token.Id.ObjectEnd, Token.Id.ArrayEnd => { + Token.Id.ObjectEnd, + Token.Id.ArrayEnd => { unreachable; }, }, @@ -1248,15 +1290,14 @@ const JsonParser = struct { // TODO: We don't strictly have to copy values which do not contain any escape // characters if flagged with the option. const slice = token.slice(input, i); - return Value { .String = try mem.dupe(p.allocator, u8, slice) }; + return Value{ .String = try mem.dupe(p.allocator, u8, slice) }; } fn parseNumber(p: &JsonParser, token: &const Token, input: []const u8, i: usize) !Value { return if (token.number_is_integer) - Value { .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) } + Value{ .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) } else - @panic("TODO: fmt.parseFloat not yet implemented") - ; + @panic("TODO: fmt.parseFloat not yet implemented"); } }; @@ -1267,21 +1308,21 @@ test "json parser dynamic" { defer p.deinit(); const s = - \\{ - \\ "Image": { - \\ "Width": 800, - \\ "Height": 600, - \\ "Title": "View from 15th Floor", - \\ "Thumbnail": { - \\ "Url": "http://www.example.com/image/481989943", - \\ "Height": 125, - \\ "Width": 100 - \\ }, - \\ "Animated" : false, - \\ "IDs": [116, 943, 234, 38793] - \\ } - \\} - ; + \\{ + \\ "Image": { + \\ "Width": 800, + \\ "Height": 600, + \\ "Title": "View from 15th Floor", + \\ "Thumbnail": { + \\ "Url": "http://www.example.com/image/481989943", + \\ "Height": 125, + \\ "Width": 100 + \\ }, + \\ "Animated" : false, + \\ "IDs": [116, 943, 234, 38793] + \\ } + \\} + ; var tree = try p.parse(s); defer tree.deinit(); diff --git a/std/math/acos.zig b/std/math/acos.zig index a4f08af306..284f73fc91 100644 --- a/std/math/acos.zig +++ b/std/math/acos.zig @@ -16,7 +16,7 @@ pub fn acos(x: var) @typeOf(x) { } fn r32(z: f32) f32 { - const pS0 = 1.6666586697e-01; + const pS0 = 1.6666586697e-01; const pS1 = -4.2743422091e-02; const pS2 = -8.6563630030e-03; const qS1 = -7.0662963390e-01; @@ -74,16 +74,16 @@ fn acos32(x: f32) f32 { } fn r64(z: f64) f64 { - const pS0: f64 = 1.66666666666666657415e-01; + const pS0: f64 = 1.66666666666666657415e-01; const pS1: f64 = -3.25565818622400915405e-01; - const pS2: f64 = 2.01212532134862925881e-01; + const pS2: f64 = 2.01212532134862925881e-01; const pS3: f64 = -4.00555345006794114027e-02; - const pS4: f64 = 7.91534994289814532176e-04; - const pS5: f64 = 3.47933107596021167570e-05; + const pS4: f64 = 7.91534994289814532176e-04; + const pS5: f64 = 3.47933107596021167570e-05; const qS1: f64 = -2.40339491173441421878e+00; - const qS2: f64 = 2.02094576023350569471e+00; + const qS2: f64 = 2.02094576023350569471e+00; const qS3: f64 = -6.88283971605453293030e-01; - const qS4: f64 = 7.70381505559019352791e-02; + const qS4: f64 = 7.70381505559019352791e-02; const p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); const q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); diff --git a/std/math/asin.zig b/std/math/asin.zig index 9fa5a80ea5..2ee3aa6048 100644 --- a/std/math/asin.zig +++ b/std/math/asin.zig @@ -17,7 +17,7 @@ pub fn asin(x: var) @typeOf(x) { } fn r32(z: f32) f32 { - const pS0 = 1.6666586697e-01; + const pS0 = 1.6666586697e-01; const pS1 = -4.2743422091e-02; const pS2 = -8.6563630030e-03; const qS1 = -7.0662963390e-01; @@ -37,9 +37,9 @@ fn asin32(x: f32) f32 { if (ix >= 0x3F800000) { // |x| >= 1 if (ix == 0x3F800000) { - return x * pio2 + 0x1.0p-120; // asin(+-1) = +-pi/2 with inexact + return x * pio2 + 0x1.0p-120; // asin(+-1) = +-pi/2 with inexact } else { - return math.nan(f32); // asin(|x| > 1) is nan + return math.nan(f32); // asin(|x| > 1) is nan } } @@ -66,16 +66,16 @@ fn asin32(x: f32) f32 { } fn r64(z: f64) f64 { - const pS0: f64 = 1.66666666666666657415e-01; + const pS0: f64 = 1.66666666666666657415e-01; const pS1: f64 = -3.25565818622400915405e-01; - const pS2: f64 = 2.01212532134862925881e-01; + const pS2: f64 = 2.01212532134862925881e-01; const pS3: f64 = -4.00555345006794114027e-02; - const pS4: f64 = 7.91534994289814532176e-04; - const pS5: f64 = 3.47933107596021167570e-05; + const pS4: f64 = 7.91534994289814532176e-04; + const pS5: f64 = 3.47933107596021167570e-05; const qS1: f64 = -2.40339491173441421878e+00; - const qS2: f64 = 2.02094576023350569471e+00; + const qS2: f64 = 2.02094576023350569471e+00; const qS3: f64 = -6.88283971605453293030e-01; - const qS4: f64 = 7.70381505559019352791e-02; + const qS4: f64 = 7.70381505559019352791e-02; const p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5))))); const q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4))); diff --git a/std/math/atan2.zig b/std/math/atan2.zig index 37c520da46..0892f0b438 100644 --- a/std/math/atan2.zig +++ b/std/math/atan2.zig @@ -31,7 +31,7 @@ pub fn atan2(comptime T: type, x: T, y: T) T { } fn atan2_32(y: f32, x: f32) f32 { - const pi: f32 = 3.1415927410e+00; + const pi: f32 = 3.1415927410e+00; const pi_lo: f32 = -8.7422776573e-08; if (math.isNan(x) or math.isNan(y)) { @@ -53,9 +53,10 @@ fn atan2_32(y: f32, x: f32) f32 { if (iy == 0) { switch (m) { - 0, 1 => return y, // atan(+-0, +...) - 2 => return pi, // atan(+0, -...) - 3 => return -pi, // atan(-0, -...) + 0, + 1 => return y, // atan(+-0, +...) + 2 => return pi, // atan(+0, -...) + 3 => return -pi, // atan(-0, -...) else => unreachable, } } @@ -71,18 +72,18 @@ fn atan2_32(y: f32, x: f32) f32 { if (ix == 0x7F800000) { if (iy == 0x7F800000) { switch (m) { - 0 => return pi / 4, // atan(+inf, +inf) - 1 => return -pi / 4, // atan(-inf, +inf) - 2 => return 3*pi / 4, // atan(+inf, -inf) - 3 => return -3*pi / 4, // atan(-inf, -inf) + 0 => return pi / 4, // atan(+inf, +inf) + 1 => return -pi / 4, // atan(-inf, +inf) + 2 => return 3 * pi / 4, // atan(+inf, -inf) + 3 => return -3 * pi / 4, // atan(-inf, -inf) else => unreachable, } } else { switch (m) { - 0 => return 0.0, // atan(+..., +inf) - 1 => return -0.0, // atan(-..., +inf) - 2 => return pi, // atan(+..., -inf) - 3 => return -pi, // atan(-...f, -inf) + 0 => return 0.0, // atan(+..., +inf) + 1 => return -0.0, // atan(-..., +inf) + 2 => return pi, // atan(+..., -inf) + 3 => return -pi, // atan(-...f, -inf) else => unreachable, } } @@ -107,16 +108,16 @@ fn atan2_32(y: f32, x: f32) f32 { }; switch (m) { - 0 => return z, // atan(+, +) - 1 => return -z, // atan(-, +) - 2 => return pi - (z - pi_lo), // atan(+, -) - 3 => return (z - pi_lo) - pi, // atan(-, -) + 0 => return z, // atan(+, +) + 1 => return -z, // atan(-, +) + 2 => return pi - (z - pi_lo), // atan(+, -) + 3 => return (z - pi_lo) - pi, // atan(-, -) else => unreachable, } } fn atan2_64(y: f64, x: f64) f64 { - const pi: f64 = 3.1415926535897931160E+00; + const pi: f64 = 3.1415926535897931160E+00; const pi_lo: f64 = 1.2246467991473531772E-16; if (math.isNan(x) or math.isNan(y)) { @@ -143,9 +144,10 @@ fn atan2_64(y: f64, x: f64) f64 { if (iy | ly == 0) { switch (m) { - 0, 1 => return y, // atan(+-0, +...) - 2 => return pi, // atan(+0, -...) - 3 => return -pi, // atan(-0, -...) + 0, + 1 => return y, // atan(+-0, +...) + 2 => return pi, // atan(+0, -...) + 3 => return -pi, // atan(-0, -...) else => unreachable, } } @@ -161,18 +163,18 @@ fn atan2_64(y: f64, x: f64) f64 { if (ix == 0x7FF00000) { if (iy == 0x7FF00000) { switch (m) { - 0 => return pi / 4, // atan(+inf, +inf) - 1 => return -pi / 4, // atan(-inf, +inf) - 2 => return 3*pi / 4, // atan(+inf, -inf) - 3 => return -3*pi / 4, // atan(-inf, -inf) + 0 => return pi / 4, // atan(+inf, +inf) + 1 => return -pi / 4, // atan(-inf, +inf) + 2 => return 3 * pi / 4, // atan(+inf, -inf) + 3 => return -3 * pi / 4, // atan(-inf, -inf) else => unreachable, } } else { switch (m) { - 0 => return 0.0, // atan(+..., +inf) - 1 => return -0.0, // atan(-..., +inf) - 2 => return pi, // atan(+..., -inf) - 3 => return -pi, // atan(-...f, -inf) + 0 => return 0.0, // atan(+..., +inf) + 1 => return -0.0, // atan(-..., +inf) + 2 => return pi, // atan(+..., -inf) + 3 => return -pi, // atan(-...f, -inf) else => unreachable, } } @@ -197,10 +199,10 @@ fn atan2_64(y: f64, x: f64) f64 { }; switch (m) { - 0 => return z, // atan(+, +) - 1 => return -z, // atan(-, +) - 2 => return pi - (z - pi_lo), // atan(+, -) - 3 => return (z - pi_lo) - pi, // atan(-, -) + 0 => return z, // atan(+, +) + 1 => return -z, // atan(-, +) + 2 => return pi - (z - pi_lo), // atan(+, -) + 3 => return (z - pi_lo) - pi, // atan(-, -) else => unreachable, } } diff --git a/std/math/cbrt.zig b/std/math/cbrt.zig index a265392ff7..cd3b71ca8a 100644 --- a/std/math/cbrt.zig +++ b/std/math/cbrt.zig @@ -58,15 +58,15 @@ fn cbrt32(x: f32) f32 { } fn cbrt64(x: f64) f64 { - const B1: u32 = 715094163; // (1023 - 1023 / 3 - 0.03306235651 * 2^20 - const B2: u32 = 696219795; // (1023 - 1023 / 3 - 54 / 3 - 0.03306235651 * 2^20 + const B1: u32 = 715094163; // (1023 - 1023 / 3 - 0.03306235651 * 2^20 + const B2: u32 = 696219795; // (1023 - 1023 / 3 - 54 / 3 - 0.03306235651 * 2^20 // |1 / cbrt(x) - p(x)| < 2^(23.5) - const P0: f64 = 1.87595182427177009643; + const P0: f64 = 1.87595182427177009643; const P1: f64 = -1.88497979543377169875; - const P2: f64 = 1.621429720105354466140; + const P2: f64 = 1.621429720105354466140; const P3: f64 = -0.758397934778766047437; - const P4: f64 = 0.145996192886612446982; + const P4: f64 = 0.145996192886612446982; var u = @bitCast(u64, x); var hx = u32(u >> 32) & 0x7FFFFFFF; diff --git a/std/math/ceil.zig b/std/math/ceil.zig index 5bdb84ca00..a189bb66d2 100644 --- a/std/math/ceil.zig +++ b/std/math/ceil.zig @@ -56,7 +56,7 @@ fn ceil64(x: f64) f64 { const e = (u >> 52) & 0x7FF; var y: f64 = undefined; - if (e >= 0x3FF+52 or x == 0) { + if (e >= 0x3FF + 52 or x == 0) { return x; } @@ -68,7 +68,7 @@ fn ceil64(x: f64) f64 { y = x + math.f64_toint - math.f64_toint - x; } - if (e <= 0x3FF-1) { + if (e <= 0x3FF - 1) { math.forceEval(y); if (u >> 63 != 0) { return -0.0; diff --git a/std/math/cos.zig b/std/math/cos.zig index bb405b0d10..5e5ec4f1cb 100644 --- a/std/math/cos.zig +++ b/std/math/cos.zig @@ -18,20 +18,20 @@ pub fn cos(x: var) @typeOf(x) { } // sin polynomial coefficients -const S0 = 1.58962301576546568060E-10; +const S0 = 1.58962301576546568060E-10; const S1 = -2.50507477628578072866E-8; -const S2 = 2.75573136213857245213E-6; +const S2 = 2.75573136213857245213E-6; const S3 = -1.98412698295895385996E-4; -const S4 = 8.33333333332211858878E-3; +const S4 = 8.33333333332211858878E-3; const S5 = -1.66666666666666307295E-1; // cos polynomial coeffiecients const C0 = -1.13585365213876817300E-11; -const C1 = 2.08757008419747316778E-9; +const C1 = 2.08757008419747316778E-9; const C2 = -2.75573141792967388112E-7; -const C3 = 2.48015872888517045348E-5; +const C3 = 2.48015872888517045348E-5; const C4 = -1.38888888888730564116E-3; -const C5 = 4.16666666666665929218E-2; +const C5 = 4.16666666666665929218E-2; // NOTE: This is taken from the go stdlib. The musl implementation is much more complex. // diff --git a/std/math/floor.zig b/std/math/floor.zig index 1b8e2dfeed..7d5364787f 100644 --- a/std/math/floor.zig +++ b/std/math/floor.zig @@ -57,7 +57,7 @@ fn floor64(x: f64) f64 { const e = (u >> 52) & 0x7FF; var y: f64 = undefined; - if (e >= 0x3FF+52 or x == 0) { + if (e >= 0x3FF + 52 or x == 0) { return x; } @@ -69,7 +69,7 @@ fn floor64(x: f64) f64 { y = x + math.f64_toint - math.f64_toint - x; } - if (e <= 0x3FF-1) { + if (e <= 0x3FF - 1) { math.forceEval(y); if (u >> 63 != 0) { return -1.0; diff --git a/std/math/fma.zig b/std/math/fma.zig index e8d146db34..3e9214f35b 100644 --- a/std/math/fma.zig +++ b/std/math/fma.zig @@ -5,7 +5,7 @@ const assert = std.debug.assert; pub fn fma(comptime T: type, x: T, y: T, z: T) T { return switch (T) { f32 => fma32(x, y, z), - f64 => fma64(x, y ,z), + f64 => fma64(x, y, z), else => @compileError("fma not implemented for " ++ @typeName(T)), }; } @@ -71,7 +71,10 @@ fn fma64(x: f64, y: f64, z: f64) f64 { } } -const dd = struct { hi: f64, lo: f64, }; +const dd = struct { + hi: f64, + lo: f64, +}; fn dd_add(a: f64, b: f64) dd { var ret: dd = undefined; diff --git a/std/math/hypot.zig b/std/math/hypot.zig index 06427d0865..fe0de3a1ea 100644 --- a/std/math/hypot.zig +++ b/std/math/hypot.zig @@ -39,11 +39,11 @@ fn hypot32(x: f32, y: f32) f32 { } var z: f32 = 1.0; - if (ux >= (0x7F+60) << 23) { + if (ux >= (0x7F + 60) << 23) { z = 0x1.0p90; xx *= 0x1.0p-90; yy *= 0x1.0p-90; - } else if (uy < (0x7F-60) << 23) { + } else if (uy < (0x7F - 60) << 23) { z = 0x1.0p-90; xx *= 0x1.0p-90; yy *= 0x1.0p-90; @@ -57,8 +57,8 @@ fn sq(hi: &f64, lo: &f64, x: f64) void { const xc = x * split; const xh = x - xc + xc; const xl = x - xh; - *hi = x * x; - *lo = xh * xh - *hi + 2 * xh * xl + xl * xl; + hi.* = x * x; + lo.* = xh * xh - hi.* + 2 * xh * xl + xl * xl; } fn hypot64(x: f64, y: f64) f64 { diff --git a/std/math/ln.zig b/std/math/ln.zig index d09494b998..263e5955cb 100644 --- a/std/math/ln.zig +++ b/std/math/ln.zig @@ -120,11 +120,9 @@ pub fn ln_64(x_: f64) f64 { k -= 54; x *= 0x1.0p54; hx = u32(@bitCast(u64, ix) >> 32); - } - else if (hx >= 0x7FF00000) { + } else if (hx >= 0x7FF00000) { return x; - } - else if (hx == 0x3FF00000 and ix << 32 == 0) { + } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } diff --git a/std/math/log10.zig b/std/math/log10.zig index aa74caa901..d9fa1dcb02 100644 --- a/std/math/log10.zig +++ b/std/math/log10.zig @@ -35,10 +35,10 @@ pub fn log10(x: var) @typeOf(x) { } pub fn log10_32(x_: f32) f32 { - const ivln10hi: f32 = 4.3432617188e-01; - const ivln10lo: f32 = -3.1689971365e-05; - const log10_2hi: f32 = 3.0102920532e-01; - const log10_2lo: f32 = 7.9034151668e-07; + const ivln10hi: f32 = 4.3432617188e-01; + const ivln10lo: f32 = -3.1689971365e-05; + const log10_2hi: f32 = 3.0102920532e-01; + const log10_2lo: f32 = 7.9034151668e-07; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; const Lg3: f32 = 0x91e9ee.0p-25; @@ -95,8 +95,8 @@ pub fn log10_32(x_: f32) f32 { } pub fn log10_64(x_: f64) f64 { - const ivln10hi: f64 = 4.34294481878168880939e-01; - const ivln10lo: f64 = 2.50829467116452752298e-11; + const ivln10hi: f64 = 4.34294481878168880939e-01; + const ivln10lo: f64 = 2.50829467116452752298e-11; const log10_2hi: f64 = 3.01029995663611771306e-01; const log10_2lo: f64 = 3.69423907715893078616e-13; const Lg1: f64 = 6.666666666666735130e-01; @@ -126,11 +126,9 @@ pub fn log10_64(x_: f64) f64 { k -= 54; x *= 0x1.0p54; hx = u32(@bitCast(u64, x) >> 32); - } - else if (hx >= 0x7FF00000) { + } else if (hx >= 0x7FF00000) { return x; - } - else if (hx == 0x3FF00000 and ix << 32 == 0) { + } else if (hx == 0x3FF00000 and ix << 32 == 0) { return 0; } diff --git a/std/math/log2.zig b/std/math/log2.zig index d5bbe385c2..22cc8082b3 100644 --- a/std/math/log2.zig +++ b/std/math/log2.zig @@ -27,7 +27,10 @@ pub fn log2(x: var) @typeOf(x) { TypeId.IntLiteral => comptime { var result = 0; var x_shifted = x; - while (b: {x_shifted >>= 1; break :b x_shifted != 0;}) : (result += 1) {} + while (b: { + x_shifted >>= 1; + break :b x_shifted != 0; + }) : (result += 1) {} return result; }, TypeId.Int => { @@ -38,7 +41,7 @@ pub fn log2(x: var) @typeOf(x) { } pub fn log2_32(x_: f32) f32 { - const ivln2hi: f32 = 1.4428710938e+00; + const ivln2hi: f32 = 1.4428710938e+00; const ivln2lo: f32 = -1.7605285393e-04; const Lg1: f32 = 0xaaaaaa.0p-24; const Lg2: f32 = 0xccce13.0p-25; diff --git a/std/math/round.zig b/std/math/round.zig index c16190da21..c8d9eb4fd4 100644 --- a/std/math/round.zig +++ b/std/math/round.zig @@ -24,13 +24,13 @@ fn round32(x_: f32) f32 { const e = (u >> 23) & 0xFF; var y: f32 = undefined; - if (e >= 0x7F+23) { + if (e >= 0x7F + 23) { return x; } if (u >> 31 != 0) { x = -x; } - if (e < 0x7F-1) { + if (e < 0x7F - 1) { math.forceEval(x + math.f32_toint); return 0 * @bitCast(f32, u); } @@ -61,13 +61,13 @@ fn round64(x_: f64) f64 { const e = (u >> 52) & 0x7FF; var y: f64 = undefined; - if (e >= 0x3FF+52) { + if (e >= 0x3FF + 52) { return x; } if (u >> 63 != 0) { x = -x; } - if (e < 0x3ff-1) { + if (e < 0x3ff - 1) { math.forceEval(x + math.f64_toint); return 0 * @bitCast(f64, u); } diff --git a/std/math/sin.zig b/std/math/sin.zig index 5dd869545b..21c324e444 100644 --- a/std/math/sin.zig +++ b/std/math/sin.zig @@ -19,20 +19,20 @@ pub fn sin(x: var) @typeOf(x) { } // sin polynomial coefficients -const S0 = 1.58962301576546568060E-10; +const S0 = 1.58962301576546568060E-10; const S1 = -2.50507477628578072866E-8; -const S2 = 2.75573136213857245213E-6; +const S2 = 2.75573136213857245213E-6; const S3 = -1.98412698295895385996E-4; -const S4 = 8.33333333332211858878E-3; +const S4 = 8.33333333332211858878E-3; const S5 = -1.66666666666666307295E-1; // cos polynomial coeffiecients const C0 = -1.13585365213876817300E-11; -const C1 = 2.08757008419747316778E-9; +const C1 = 2.08757008419747316778E-9; const C2 = -2.75573141792967388112E-7; -const C3 = 2.48015872888517045348E-5; +const C3 = 2.48015872888517045348E-5; const C4 = -1.38888888888730564116E-3; -const C5 = 4.16666666666665929218E-2; +const C5 = 4.16666666666665929218E-2; // NOTE: This is taken from the go stdlib. The musl implementation is much more complex. // diff --git a/std/math/tan.zig b/std/math/tan.zig index 11428b6e8b..f578cf8156 100644 --- a/std/math/tan.zig +++ b/std/math/tan.zig @@ -19,12 +19,12 @@ pub fn tan(x: var) @typeOf(x) { } const Tp0 = -1.30936939181383777646E4; -const Tp1 = 1.15351664838587416140E6; +const Tp1 = 1.15351664838587416140E6; const Tp2 = -1.79565251976484877988E7; -const Tq1 = 1.36812963470692954678E4; +const Tq1 = 1.36812963470692954678E4; const Tq2 = -1.32089234440210967447E6; -const Tq3 = 2.50083801823357915839E7; +const Tq3 = 2.50083801823357915839E7; const Tq4 = -5.38695755929454629881E7; // NOTE: This is taken from the go stdlib. The musl implementation is much more complex. diff --git a/std/net.zig b/std/net.zig index 8e1b8d97b2..b1e291ab92 100644 --- a/std/net.zig +++ b/std/net.zig @@ -19,37 +19,29 @@ pub const Address = struct { os_addr: OsAddress, pub fn initIp4(ip4: u32, port: u16) Address { - return Address { - .os_addr = posix.sockaddr { - .in = posix.sockaddr_in { - .family = posix.AF_INET, - .port = std.mem.endianSwapIfLe(u16, port), - .addr = ip4, - .zero = []u8{0} ** 8, - }, - }, - }; + return Address{ .os_addr = posix.sockaddr{ .in = posix.sockaddr_in{ + .family = posix.AF_INET, + .port = std.mem.endianSwapIfLe(u16, port), + .addr = ip4, + .zero = []u8{0} ** 8, + } } }; } pub fn initIp6(ip6: &const Ip6Addr, port: u16) Address { - return Address { + return Address{ .family = posix.AF_INET6, - .os_addr = posix.sockaddr { - .in6 = posix.sockaddr_in6 { - .family = posix.AF_INET6, - .port = std.mem.endianSwapIfLe(u16, port), - .flowinfo = 0, - .addr = ip6.addr, - .scope_id = ip6.scope_id, - }, - }, + .os_addr = posix.sockaddr{ .in6 = posix.sockaddr_in6{ + .family = posix.AF_INET6, + .port = std.mem.endianSwapIfLe(u16, port), + .flowinfo = 0, + .addr = ip6.addr, + .scope_id = ip6.scope_id, + } }, }; } pub fn initPosix(addr: &const posix.sockaddr) Address { - return Address { - .os_addr = *addr, - }; + return Address{ .os_addr = addr.* }; } pub fn format(self: &const Address, out_stream: var) !void { @@ -98,7 +90,7 @@ pub fn parseIp4(buf: []const u8) !u32 { } } else { return error.InvalidCharacter; - } + } } if (index == 3 and saw_any_digits) { out_ptr[index] = x; diff --git a/std/os/child_process.zig b/std/os/child_process.zig index 8bb8b2d7e7..6c0c21f64a 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -49,7 +49,7 @@ pub const ChildProcess = struct { err_pipe: if (is_windows) void else [2]i32, llnode: if (is_windows) void else LinkedList(&ChildProcess).Node, - pub const SpawnError = error { + pub const SpawnError = error{ ProcessFdQuotaExceeded, Unexpected, NotDir, @@ -88,7 +88,7 @@ pub const ChildProcess = struct { const child = try allocator.create(ChildProcess); errdefer allocator.destroy(child); - *child = ChildProcess { + child.* = ChildProcess{ .allocator = allocator, .argv = argv, .pid = undefined, @@ -99,8 +99,10 @@ pub const ChildProcess = struct { .term = null, .env_map = null, .cwd = null, - .uid = if (is_windows) {} else null, - .gid = if (is_windows) {} else null, + .uid = if (is_windows) {} else + null, + .gid = if (is_windows) {} else + null, .stdin = null, .stdout = null, .stderr = null, @@ -193,9 +195,7 @@ pub const ChildProcess = struct { /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns. /// If it succeeds, the caller owns result.stdout and result.stderr memory. - pub fn exec(allocator: &mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, - env_map: ?&const BufMap, max_output_size: usize) !ExecResult - { + pub fn exec(allocator: &mem.Allocator, argv: []const []const u8, cwd: ?[]const u8, env_map: ?&const BufMap, max_output_size: usize) !ExecResult { const child = try ChildProcess.init(argv, allocator); defer child.deinit(); @@ -218,7 +218,7 @@ pub const ChildProcess = struct { try stdout_file_in_stream.stream.readAllBuffer(&stdout, max_output_size); try stderr_file_in_stream.stream.readAllBuffer(&stderr, max_output_size); - return ExecResult { + return ExecResult{ .term = try child.wait(), .stdout = stdout.toOwnedSlice(), .stderr = stderr.toOwnedSlice(), @@ -255,9 +255,9 @@ pub const ChildProcess = struct { self.term = (SpawnError!Term)(x: { var exit_code: windows.DWORD = undefined; if (windows.GetExitCodeProcess(self.handle, &exit_code) == 0) { - break :x Term { .Unknown = 0 }; + break :x Term{ .Unknown = 0 }; } else { - break :x Term { .Exited = @bitCast(i32, exit_code)}; + break :x Term{ .Exited = @bitCast(i32, exit_code) }; } }); @@ -288,9 +288,18 @@ pub const ChildProcess = struct { } fn cleanupStreams(self: &ChildProcess) void { - if (self.stdin) |*stdin| { stdin.close(); self.stdin = null; } - if (self.stdout) |*stdout| { stdout.close(); self.stdout = null; } - if (self.stderr) |*stderr| { stderr.close(); self.stderr = null; } + if (self.stdin) |*stdin| { + stdin.close(); + self.stdin = null; + } + if (self.stdout) |*stdout| { + stdout.close(); + self.stdout = null; + } + if (self.stderr) |*stderr| { + stderr.close(); + self.stderr = null; + } } fn cleanupAfterWait(self: &ChildProcess, status: i32) !Term { @@ -317,25 +326,30 @@ pub const ChildProcess = struct { fn statusToTerm(status: i32) Term { return if (posix.WIFEXITED(status)) - Term { .Exited = posix.WEXITSTATUS(status) } + Term{ .Exited = posix.WEXITSTATUS(status) } else if (posix.WIFSIGNALED(status)) - Term { .Signal = posix.WTERMSIG(status) } + Term{ .Signal = posix.WTERMSIG(status) } else if (posix.WIFSTOPPED(status)) - Term { .Stopped = posix.WSTOPSIG(status) } + Term{ .Stopped = posix.WSTOPSIG(status) } else - Term { .Unknown = status } - ; + Term{ .Unknown = status }; } fn spawnPosix(self: &ChildProcess) !void { const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try makePipe() else undefined; - errdefer if (self.stdin_behavior == StdIo.Pipe) { destroyPipe(stdin_pipe); }; + errdefer if (self.stdin_behavior == StdIo.Pipe) { + destroyPipe(stdin_pipe); + }; const stdout_pipe = if (self.stdout_behavior == StdIo.Pipe) try makePipe() else undefined; - errdefer if (self.stdout_behavior == StdIo.Pipe) { destroyPipe(stdout_pipe); }; + errdefer if (self.stdout_behavior == StdIo.Pipe) { + destroyPipe(stdout_pipe); + }; const stderr_pipe = if (self.stderr_behavior == StdIo.Pipe) try makePipe() else undefined; - errdefer if (self.stderr_behavior == StdIo.Pipe) { destroyPipe(stderr_pipe); }; + errdefer if (self.stderr_behavior == StdIo.Pipe) { + destroyPipe(stderr_pipe); + }; const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const dev_null_fd = if (any_ignore) blk: { @@ -346,7 +360,9 @@ pub const ChildProcess = struct { } else blk: { break :blk undefined; }; - defer { if (any_ignore) os.close(dev_null_fd); } + defer { + if (any_ignore) os.close(dev_null_fd); + } var env_map_owned: BufMap = undefined; var we_own_env_map: bool = undefined; @@ -358,7 +374,9 @@ pub const ChildProcess = struct { env_map_owned = try os.getEnvMap(self.allocator); break :x &env_map_owned; }; - defer { if (we_own_env_map) env_map_owned.deinit(); } + defer { + if (we_own_env_map) env_map_owned.deinit(); + } // This pipe is used to communicate errors between the time of fork // and execve from the child process to the parent process. @@ -369,23 +387,21 @@ pub const ChildProcess = struct { const pid_err = posix.getErrno(pid_result); if (pid_err > 0) { return switch (pid_err) { - posix.EAGAIN, posix.ENOMEM, posix.ENOSYS => error.SystemResources, + posix.EAGAIN, + posix.ENOMEM, + posix.ENOSYS => error.SystemResources, else => os.unexpectedErrorPosix(pid_err), }; } if (pid_result == 0) { // we are the child - setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch - |err| forkChildErrReport(err_pipe[1], err); - setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch - |err| forkChildErrReport(err_pipe[1], err); - setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch - |err| forkChildErrReport(err_pipe[1], err); + setUpChildIo(self.stdin_behavior, stdin_pipe[0], posix.STDIN_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); + setUpChildIo(self.stdout_behavior, stdout_pipe[1], posix.STDOUT_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); + setUpChildIo(self.stderr_behavior, stderr_pipe[1], posix.STDERR_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); if (self.cwd) |cwd| { - os.changeCurDir(self.allocator, cwd) catch - |err| forkChildErrReport(err_pipe[1], err); + os.changeCurDir(self.allocator, cwd) catch |err| forkChildErrReport(err_pipe[1], err); } if (self.gid) |gid| { @@ -396,8 +412,7 @@ pub const ChildProcess = struct { os.posix_setreuid(uid, uid) catch |err| forkChildErrReport(err_pipe[1], err); } - os.posixExecve(self.argv, env_map, self.allocator) catch - |err| forkChildErrReport(err_pipe[1], err); + os.posixExecve(self.argv, env_map, self.allocator) catch |err| forkChildErrReport(err_pipe[1], err); } // we are the parent @@ -423,37 +438,41 @@ pub const ChildProcess = struct { self.llnode = LinkedList(&ChildProcess).Node.init(self); self.term = null; - if (self.stdin_behavior == StdIo.Pipe) { os.close(stdin_pipe[0]); } - if (self.stdout_behavior == StdIo.Pipe) { os.close(stdout_pipe[1]); } - if (self.stderr_behavior == StdIo.Pipe) { os.close(stderr_pipe[1]); } + if (self.stdin_behavior == StdIo.Pipe) { + os.close(stdin_pipe[0]); + } + if (self.stdout_behavior == StdIo.Pipe) { + os.close(stdout_pipe[1]); + } + if (self.stderr_behavior == StdIo.Pipe) { + os.close(stderr_pipe[1]); + } } fn spawnWindows(self: &ChildProcess) !void { - const saAttr = windows.SECURITY_ATTRIBUTES { + const saAttr = windows.SECURITY_ATTRIBUTES{ .nLength = @sizeOf(windows.SECURITY_ATTRIBUTES), .bInheritHandle = windows.TRUE, .lpSecurityDescriptor = null, }; - const any_ignore = (self.stdin_behavior == StdIo.Ignore or - self.stdout_behavior == StdIo.Ignore or - self.stderr_behavior == StdIo.Ignore); + const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const nul_handle = if (any_ignore) blk: { const nul_file_path = "NUL"; var fixed_buffer_mem: [nul_file_path.len + 1]u8 = undefined; var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]); - break :blk try os.windowsOpen(&fixed_allocator.allocator, "NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ, - windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL); + break :blk try os.windowsOpen(&fixed_allocator.allocator, "NUL", windows.GENERIC_READ, windows.FILE_SHARE_READ, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL); } else blk: { break :blk undefined; }; - defer { if (any_ignore) os.close(nul_handle); } + defer { + if (any_ignore) os.close(nul_handle); + } if (any_ignore) { try windowsSetHandleInfo(nul_handle, windows.HANDLE_FLAG_INHERIT, 0); } - var g_hChildStd_IN_Rd: ?windows.HANDLE = null; var g_hChildStd_IN_Wr: ?windows.HANDLE = null; switch (self.stdin_behavior) { @@ -470,7 +489,9 @@ pub const ChildProcess = struct { g_hChildStd_IN_Rd = null; }, } - errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_IN_Rd, g_hChildStd_IN_Wr); }; + errdefer if (self.stdin_behavior == StdIo.Pipe) { + windowsDestroyPipe(g_hChildStd_IN_Rd, g_hChildStd_IN_Wr); + }; var g_hChildStd_OUT_Rd: ?windows.HANDLE = null; var g_hChildStd_OUT_Wr: ?windows.HANDLE = null; @@ -488,7 +509,9 @@ pub const ChildProcess = struct { g_hChildStd_OUT_Wr = null; }, } - errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_OUT_Rd, g_hChildStd_OUT_Wr); }; + errdefer if (self.stdin_behavior == StdIo.Pipe) { + windowsDestroyPipe(g_hChildStd_OUT_Rd, g_hChildStd_OUT_Wr); + }; var g_hChildStd_ERR_Rd: ?windows.HANDLE = null; var g_hChildStd_ERR_Wr: ?windows.HANDLE = null; @@ -506,12 +529,14 @@ pub const ChildProcess = struct { g_hChildStd_ERR_Wr = null; }, } - errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_ERR_Rd, g_hChildStd_ERR_Wr); }; + errdefer if (self.stdin_behavior == StdIo.Pipe) { + windowsDestroyPipe(g_hChildStd_ERR_Rd, g_hChildStd_ERR_Wr); + }; const cmd_line = try windowsCreateCommandLine(self.allocator, self.argv); defer self.allocator.free(cmd_line); - var siStartInfo = windows.STARTUPINFOA { + var siStartInfo = windows.STARTUPINFOA{ .cb = @sizeOf(windows.STARTUPINFOA), .hStdError = g_hChildStd_ERR_Wr, .hStdOutput = g_hChildStd_OUT_Wr, @@ -534,19 +559,11 @@ pub const ChildProcess = struct { }; var piProcInfo: windows.PROCESS_INFORMATION = undefined; - const cwd_slice = if (self.cwd) |cwd| - try cstr.addNullByte(self.allocator, cwd) - else - null - ; + const cwd_slice = if (self.cwd) |cwd| try cstr.addNullByte(self.allocator, cwd) else null; defer if (cwd_slice) |cwd| self.allocator.free(cwd); const cwd_ptr = if (cwd_slice) |cwd| cwd.ptr else null; - const maybe_envp_buf = if (self.env_map) |env_map| - try os.createWindowsEnvBlock(self.allocator, env_map) - else - null - ; + const maybe_envp_buf = if (self.env_map) |env_map| try os.createWindowsEnvBlock(self.allocator, env_map) else null; defer if (maybe_envp_buf) |envp_buf| self.allocator.free(envp_buf); const envp_ptr = if (maybe_envp_buf) |envp_buf| envp_buf.ptr else null; @@ -563,11 +580,8 @@ pub const ChildProcess = struct { }; defer self.allocator.free(app_name); - windowsCreateProcess(app_name.ptr, cmd_line.ptr, envp_ptr, cwd_ptr, - &siStartInfo, &piProcInfo) catch |no_path_err| - { - if (no_path_err != error.FileNotFound) - return no_path_err; + windowsCreateProcess(app_name.ptr, cmd_line.ptr, envp_ptr, cwd_ptr, &siStartInfo, &piProcInfo) catch |no_path_err| { + if (no_path_err != error.FileNotFound) return no_path_err; const PATH = try os.getEnvVarOwned(self.allocator, "PATH"); defer self.allocator.free(PATH); @@ -577,9 +591,7 @@ pub const ChildProcess = struct { const joined_path = try os.path.join(self.allocator, search_path, app_name); defer self.allocator.free(joined_path); - if (windowsCreateProcess(joined_path.ptr, cmd_line.ptr, envp_ptr, cwd_ptr, - &siStartInfo, &piProcInfo)) |_| - { + if (windowsCreateProcess(joined_path.ptr, cmd_line.ptr, envp_ptr, cwd_ptr, &siStartInfo, &piProcInfo)) |_| { break; } else |err| if (err == error.FileNotFound) { continue; @@ -609,9 +621,15 @@ pub const ChildProcess = struct { self.thread_handle = piProcInfo.hThread; self.term = null; - if (self.stdin_behavior == StdIo.Pipe) { os.close(??g_hChildStd_IN_Rd); } - if (self.stderr_behavior == StdIo.Pipe) { os.close(??g_hChildStd_ERR_Wr); } - if (self.stdout_behavior == StdIo.Pipe) { os.close(??g_hChildStd_OUT_Wr); } + if (self.stdin_behavior == StdIo.Pipe) { + os.close(??g_hChildStd_IN_Rd); + } + if (self.stderr_behavior == StdIo.Pipe) { + os.close(??g_hChildStd_ERR_Wr); + } + if (self.stdout_behavior == StdIo.Pipe) { + os.close(??g_hChildStd_OUT_Wr); + } } fn setUpChildIo(stdio: StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) !void { @@ -622,18 +640,14 @@ pub const ChildProcess = struct { StdIo.Ignore => try os.posixDup2(dev_null_fd, std_fileno), } } - }; -fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?&u8, - lpStartupInfo: &windows.STARTUPINFOA, lpProcessInformation: &windows.PROCESS_INFORMATION) !void -{ - if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, - @ptrCast(?&c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) - { +fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ?&u8, lpStartupInfo: &windows.STARTUPINFOA, lpProcessInformation: &windows.PROCESS_INFORMATION) !void { + if (windows.CreateProcessA(app_name, cmd_line, null, null, windows.TRUE, 0, @ptrCast(?&c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation) == 0) { const err = windows.GetLastError(); return switch (err) { - windows.ERROR.FILE_NOT_FOUND, windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, + windows.ERROR.FILE_NOT_FOUND, + windows.ERROR.PATH_NOT_FOUND => error.FileNotFound, windows.ERROR.INVALID_PARAMETER => unreachable, windows.ERROR.INVALID_NAME => error.InvalidName, else => os.unexpectedErrorWindows(err), @@ -641,9 +655,6 @@ fn windowsCreateProcess(app_name: &u8, cmd_line: &u8, envp_ptr: ?&u8, cwd_ptr: ? } } - - - /// Caller must dealloc. /// Guarantees a null byte at result[result.len]. fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) ![]u8 { @@ -651,8 +662,7 @@ fn windowsCreateCommandLine(allocator: &mem.Allocator, argv: []const []const u8) defer buf.deinit(); for (argv) |arg, arg_i| { - if (arg_i != 0) - try buf.appendByte(' '); + if (arg_i != 0) try buf.appendByte(' '); if (mem.indexOfAny(u8, arg, " \t\n\"") == null) { try buf.append(arg); continue; @@ -686,7 +696,6 @@ fn windowsDestroyPipe(rd: ?windows.HANDLE, wr: ?windows.HANDLE) void { if (wr) |h| os.close(h); } - // TODO: workaround for bug where the `const` from `&const` is dropped when the type is // a namespace field lookup const SECURITY_ATTRIBUTES = windows.SECURITY_ATTRIBUTES; @@ -715,8 +724,8 @@ fn windowsMakePipeIn(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const S try windowsMakePipe(&rd_h, &wr_h, sattr); errdefer windowsDestroyPipe(rd_h, wr_h); try windowsSetHandleInfo(wr_h, windows.HANDLE_FLAG_INHERIT, 0); - *rd = rd_h; - *wr = wr_h; + rd.* = rd_h; + wr.* = wr_h; } fn windowsMakePipeOut(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const SECURITY_ATTRIBUTES) !void { @@ -725,8 +734,8 @@ fn windowsMakePipeOut(rd: &?windows.HANDLE, wr: &?windows.HANDLE, sattr: &const try windowsMakePipe(&rd_h, &wr_h, sattr); errdefer windowsDestroyPipe(rd_h, wr_h); try windowsSetHandleInfo(rd_h, windows.HANDLE_FLAG_INHERIT, 0); - *rd = rd_h; - *wr = wr_h; + rd.* = rd_h; + wr.* = wr_h; } fn makePipe() ![2]i32 { @@ -734,7 +743,8 @@ fn makePipe() ![2]i32 { const err = posix.getErrno(posix.pipe(&fds)); if (err > 0) { return switch (err) { - posix.EMFILE, posix.ENFILE => error.SystemResources, + posix.EMFILE, + posix.ENFILE => error.SystemResources, else => os.unexpectedErrorPosix(err), }; } @@ -742,8 +752,8 @@ fn makePipe() ![2]i32 { } fn destroyPipe(pipe: &const [2]i32) void { - os.close((*pipe)[0]); - os.close((*pipe)[1]); + os.close((pipe.*)[0]); + os.close((pipe.*)[1]); } // Child of fork calls this to report an error to the fork parent. diff --git a/std/segmented_list.zig b/std/segmented_list.zig index 6c7c879919..e9abc7adf9 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -93,7 +93,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type /// Deinitialize with `deinit` pub fn init(allocator: &Allocator) Self { - return Self { + return Self{ .allocator = allocator, .len = 0, .prealloc_segment = undefined, @@ -104,7 +104,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type pub fn deinit(self: &Self) void { self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0); self.allocator.free(self.dynamic_segments); - *self = undefined; + self.* = undefined; } pub fn at(self: &Self, i: usize) &T { @@ -118,7 +118,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type pub fn push(self: &Self, item: &const T) !void { const new_item_ptr = try self.addOne(); - *new_item_ptr = *item; + new_item_ptr.* = item.*; } pub fn pushMany(self: &Self, items: []const T) !void { @@ -128,11 +128,10 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } pub fn pop(self: &Self) ?T { - if (self.len == 0) - return null; + if (self.len == 0) return null; const index = self.len - 1; - const result = *self.uncheckedAt(index); + const result = self.uncheckedAt(index).*; self.len = index; return result; } @@ -245,8 +244,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type shelf_size: usize, pub fn next(it: &Iterator) ?&T { - if (it.index >= it.list.len) - return null; + if (it.index >= it.list.len) return null; if (it.index < prealloc_item_count) { const ptr = &it.list.prealloc_segment[it.index]; it.index += 1; @@ -270,12 +268,10 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } pub fn prev(it: &Iterator) ?&T { - if (it.index == 0) - return null; + if (it.index == 0) return null; it.index -= 1; - if (it.index < prealloc_item_count) - return &it.list.prealloc_segment[it.index]; + if (it.index < prealloc_item_count) return &it.list.prealloc_segment[it.index]; if (it.box_index == 0) { it.shelf_index -= 1; @@ -290,7 +286,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type }; pub fn iterator(self: &Self, start_index: usize) Iterator { - var it = Iterator { + var it = Iterator{ .list = self, .index = start_index, .shelf_index = undefined, @@ -324,25 +320,31 @@ fn testSegmentedList(comptime prealloc: usize, allocator: &Allocator) !void { var list = SegmentedList(i32, prealloc).init(allocator); defer list.deinit(); - {var i: usize = 0; while (i < 100) : (i += 1) { - try list.push(i32(i + 1)); - assert(list.len == i + 1); - }} + { + var i: usize = 0; + while (i < 100) : (i += 1) { + try list.push(i32(i + 1)); + assert(list.len == i + 1); + } + } - {var i: usize = 0; while (i < 100) : (i += 1) { - assert(*list.at(i) == i32(i + 1)); - }} + { + var i: usize = 0; + while (i < 100) : (i += 1) { + assert(list.at(i).* == i32(i + 1)); + } + } { var it = list.iterator(0); var x: i32 = 0; while (it.next()) |item| { x += 1; - assert(*item == x); + assert(item.* == x); } assert(x == 100); while (it.prev()) |item| : (x -= 1) { - assert(*item == x); + assert(item.* == x); } assert(x == 0); } @@ -350,14 +352,18 @@ fn testSegmentedList(comptime prealloc: usize, allocator: &Allocator) !void { assert(??list.pop() == 100); assert(list.len == 99); - try list.pushMany([]i32 { 1, 2, 3 }); + try list.pushMany([]i32{ + 1, + 2, + 3, + }); assert(list.len == 102); assert(??list.pop() == 3); assert(??list.pop() == 2); assert(??list.pop() == 1); assert(list.len == 99); - try list.pushMany([]const i32 {}); + try list.pushMany([]const i32{}); assert(list.len == 99); var i: i32 = 99; diff --git a/std/sort.zig b/std/sort.zig index 0f83df7bb4..4cc7ad503a 100644 --- a/std/sort.zig +++ b/std/sort.zig @@ -5,15 +5,18 @@ const math = std.math; const builtin = @import("builtin"); /// Stable in-place sort. O(n) best case, O(pow(n, 2)) worst case. O(1) memory (no allocator required). -pub fn insertionSort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool) void { - {var i: usize = 1; while (i < items.len) : (i += 1) { - const x = items[i]; - var j: usize = i; - while (j > 0 and lessThan(x, items[j - 1])) : (j -= 1) { - items[j] = items[j - 1]; +pub fn insertionSort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) void { + { + var i: usize = 1; + while (i < items.len) : (i += 1) { + const x = items[i]; + var j: usize = i; + while (j > 0 and lessThan(x, items[j - 1])) : (j -= 1) { + items[j] = items[j - 1]; + } + items[j] = x; } - items[j] = x; - }} + } } const Range = struct { @@ -21,7 +24,10 @@ const Range = struct { end: usize, fn init(start: usize, end: usize) Range { - return Range { .start = start, .end = end }; + return Range{ + .start = start, + .end = end, + }; } fn length(self: &const Range) usize { @@ -29,7 +35,6 @@ const Range = struct { } }; - const Iterator = struct { size: usize, power_of_two: usize, @@ -42,7 +47,7 @@ const Iterator = struct { fn init(size2: usize, min_level: usize) Iterator { const power_of_two = math.floorPowerOfTwo(usize, size2); const denominator = power_of_two / min_level; - return Iterator { + return Iterator{ .numerator = 0, .decimal = 0, .size = size2, @@ -68,7 +73,10 @@ const Iterator = struct { self.decimal += 1; } - return Range {.start = start, .end = self.decimal}; + return Range{ + .start = start, + .end = self.decimal, + }; } fn finished(self: &Iterator) bool { @@ -100,7 +108,7 @@ const Pull = struct { /// Stable in-place sort. O(n) best case, O(n*log(n)) worst case and average case. O(1) memory (no allocator required). /// Currently implemented as block sort. -pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool) void { +pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) void { // Implementation ported from https://github.com/BonzaiThePenguin/WikiSort/blob/master/WikiSort.c var cache: [512]T = undefined; @@ -123,7 +131,16 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // http://pages.ripco.net/~jgamble/nw.html var iterator = Iterator.init(items.len, 4); while (!iterator.finished()) { - var order = []u8{0, 1, 2, 3, 4, 5, 6, 7}; + var order = []u8{ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; const range = iterator.nextRange(); const sliced_items = items[range.start..]; @@ -149,56 +166,56 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons swap(T, sliced_items, lessThan, &order, 3, 5); swap(T, sliced_items, lessThan, &order, 3, 4); }, - 7 => { - swap(T, sliced_items, lessThan, &order, 1, 2); - swap(T, sliced_items, lessThan, &order, 3, 4); - swap(T, sliced_items, lessThan, &order, 5, 6); - swap(T, sliced_items, lessThan, &order, 0, 2); - swap(T, sliced_items, lessThan, &order, 3, 5); - swap(T, sliced_items, lessThan, &order, 4, 6); - swap(T, sliced_items, lessThan, &order, 0, 1); - swap(T, sliced_items, lessThan, &order, 4, 5); - swap(T, sliced_items, lessThan, &order, 2, 6); - swap(T, sliced_items, lessThan, &order, 0, 4); - swap(T, sliced_items, lessThan, &order, 1, 5); - swap(T, sliced_items, lessThan, &order, 0, 3); - swap(T, sliced_items, lessThan, &order, 2, 5); - swap(T, sliced_items, lessThan, &order, 1, 3); - swap(T, sliced_items, lessThan, &order, 2, 4); - swap(T, sliced_items, lessThan, &order, 2, 3); - }, - 6 => { - swap(T, sliced_items, lessThan, &order, 1, 2); - swap(T, sliced_items, lessThan, &order, 4, 5); - swap(T, sliced_items, lessThan, &order, 0, 2); - swap(T, sliced_items, lessThan, &order, 3, 5); - swap(T, sliced_items, lessThan, &order, 0, 1); - swap(T, sliced_items, lessThan, &order, 3, 4); - swap(T, sliced_items, lessThan, &order, 2, 5); - swap(T, sliced_items, lessThan, &order, 0, 3); - swap(T, sliced_items, lessThan, &order, 1, 4); - swap(T, sliced_items, lessThan, &order, 2, 4); - swap(T, sliced_items, lessThan, &order, 1, 3); - swap(T, sliced_items, lessThan, &order, 2, 3); - }, - 5 => { - swap(T, sliced_items, lessThan, &order, 0, 1); - swap(T, sliced_items, lessThan, &order, 3, 4); - swap(T, sliced_items, lessThan, &order, 2, 4); - swap(T, sliced_items, lessThan, &order, 2, 3); - swap(T, sliced_items, lessThan, &order, 1, 4); - swap(T, sliced_items, lessThan, &order, 0, 3); - swap(T, sliced_items, lessThan, &order, 0, 2); - swap(T, sliced_items, lessThan, &order, 1, 3); - swap(T, sliced_items, lessThan, &order, 1, 2); - }, - 4 => { - swap(T, sliced_items, lessThan, &order, 0, 1); - swap(T, sliced_items, lessThan, &order, 2, 3); - swap(T, sliced_items, lessThan, &order, 0, 2); - swap(T, sliced_items, lessThan, &order, 1, 3); - swap(T, sliced_items, lessThan, &order, 1, 2); - }, + 7 => { + swap(T, sliced_items, lessThan, &order, 1, 2); + swap(T, sliced_items, lessThan, &order, 3, 4); + swap(T, sliced_items, lessThan, &order, 5, 6); + swap(T, sliced_items, lessThan, &order, 0, 2); + swap(T, sliced_items, lessThan, &order, 3, 5); + swap(T, sliced_items, lessThan, &order, 4, 6); + swap(T, sliced_items, lessThan, &order, 0, 1); + swap(T, sliced_items, lessThan, &order, 4, 5); + swap(T, sliced_items, lessThan, &order, 2, 6); + swap(T, sliced_items, lessThan, &order, 0, 4); + swap(T, sliced_items, lessThan, &order, 1, 5); + swap(T, sliced_items, lessThan, &order, 0, 3); + swap(T, sliced_items, lessThan, &order, 2, 5); + swap(T, sliced_items, lessThan, &order, 1, 3); + swap(T, sliced_items, lessThan, &order, 2, 4); + swap(T, sliced_items, lessThan, &order, 2, 3); + }, + 6 => { + swap(T, sliced_items, lessThan, &order, 1, 2); + swap(T, sliced_items, lessThan, &order, 4, 5); + swap(T, sliced_items, lessThan, &order, 0, 2); + swap(T, sliced_items, lessThan, &order, 3, 5); + swap(T, sliced_items, lessThan, &order, 0, 1); + swap(T, sliced_items, lessThan, &order, 3, 4); + swap(T, sliced_items, lessThan, &order, 2, 5); + swap(T, sliced_items, lessThan, &order, 0, 3); + swap(T, sliced_items, lessThan, &order, 1, 4); + swap(T, sliced_items, lessThan, &order, 2, 4); + swap(T, sliced_items, lessThan, &order, 1, 3); + swap(T, sliced_items, lessThan, &order, 2, 3); + }, + 5 => { + swap(T, sliced_items, lessThan, &order, 0, 1); + swap(T, sliced_items, lessThan, &order, 3, 4); + swap(T, sliced_items, lessThan, &order, 2, 4); + swap(T, sliced_items, lessThan, &order, 2, 3); + swap(T, sliced_items, lessThan, &order, 1, 4); + swap(T, sliced_items, lessThan, &order, 0, 3); + swap(T, sliced_items, lessThan, &order, 0, 2); + swap(T, sliced_items, lessThan, &order, 1, 3); + swap(T, sliced_items, lessThan, &order, 1, 2); + }, + 4 => { + swap(T, sliced_items, lessThan, &order, 0, 1); + swap(T, sliced_items, lessThan, &order, 2, 3); + swap(T, sliced_items, lessThan, &order, 0, 2); + swap(T, sliced_items, lessThan, &order, 1, 3); + swap(T, sliced_items, lessThan, &order, 1, 2); + }, else => {}, } } @@ -273,7 +290,6 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // we merged two levels at the same time, so we're done with this level already // (iterator.nextLevel() is called again at the bottom of this outer merge loop) _ = iterator.nextLevel(); - } else { iterator.begin(); while (!iterator.finished()) { @@ -303,7 +319,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // 8. redistribute the two internal buffers back into the items var block_size: usize = math.sqrt(iterator.length()); - var buffer_size = iterator.length()/block_size + 1; + var buffer_size = iterator.length() / block_size + 1; // as an optimization, we really only need to pull out the internal buffers once for each level of merges // after that we can reuse the same buffers over and over, then redistribute it when we're finished with this level @@ -316,8 +332,18 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons var start: usize = 0; var pull_index: usize = 0; var pull = []Pull{ - Pull {.from = 0, .to = 0, .count = 0, .range = Range.init(0, 0),}, - Pull {.from = 0, .to = 0, .count = 0, .range = Range.init(0, 0),}, + Pull{ + .from = 0, + .to = 0, + .count = 0, + .range = Range.init(0, 0), + }, + Pull{ + .from = 0, + .to = 0, + .count = 0, + .range = Range.init(0, 0), + }, }; var buffer1 = Range.init(0, 0); @@ -355,7 +381,10 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // these values will be pulled out to the start of A last = A.start; count = 1; - while (count < find) : ({last = index; count += 1;}) { + while (count < find) : ({ + last = index; + count += 1; + }) { index = findLastForward(T, items, items[last], Range.init(last + 1, A.end), lessThan, find - count); if (index == A.end) break; } @@ -363,7 +392,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons if (count >= buffer_size) { // keep track of the range within the items where we'll need to "pull out" these values to create the internal buffer - pull[pull_index] = Pull { + pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, @@ -398,7 +427,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons } else if (pull_index == 0 and count > buffer1.length()) { // keep track of the largest buffer we were able to find buffer1 = Range.init(A.start, A.start + count); - pull[pull_index] = Pull { + pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, @@ -410,7 +439,10 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // these values will be pulled out to the end of B last = B.end - 1; count = 1; - while (count < find) : ({last = index - 1; count += 1;}) { + while (count < find) : ({ + last = index - 1; + count += 1; + }) { index = findFirstBackward(T, items, items[last], Range.init(B.start, last), lessThan, find - count); if (index == B.start) break; } @@ -418,7 +450,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons if (count >= buffer_size) { // keep track of the range within the items where we'll need to "pull out" these values to create the internal buffe - pull[pull_index] = Pull { + pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, @@ -457,7 +489,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons } else if (pull_index == 0 and count > buffer1.length()) { // keep track of the largest buffer we were able to find buffer1 = Range.init(B.end - count, B.end); - pull[pull_index] = Pull { + pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, @@ -496,7 +528,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // adjust block_size and buffer_size based on the values we were able to pull out buffer_size = buffer1.length(); - block_size = iterator.length()/buffer_size + 1; + block_size = iterator.length() / buffer_size + 1; // the first buffer NEEDS to be large enough to tag each of the evenly sized A blocks, // so this was originally here to test the math for adjusting block_size above @@ -547,7 +579,10 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // swap the first value of each A block with the value in buffer1 var indexA = buffer1.start; index = firstA.end; - while (index < blockA.end) : ({indexA += 1; index += block_size;}) { + while (index < blockA.end) : ({ + indexA += 1; + index += block_size; + }) { mem.swap(T, &items[indexA], &items[index]); } @@ -626,9 +661,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons // if there are no more A blocks remaining, this step is finished! blockA.start += block_size; - if (blockA.length() == 0) - break; - + if (blockA.length() == 0) break; } else if (blockB.length() < block_size) { // move the last B block, which is unevenly sized, to before the remaining A blocks, by using a rotation // the cache is disabled here since it might contain the contents of the previous A block @@ -709,7 +742,7 @@ pub fn sort(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &cons } // merge operation without a buffer -fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const Range, lessThan: fn(&const T,&const T)bool) void { +fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const Range, lessThan: fn(&const T, &const T) bool) void { if (A_arg.length() == 0 or B_arg.length() == 0) return; // this just repeatedly binary searches into B and rotates A into position. @@ -730,8 +763,8 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const // again, this is NOT a general-purpose solution – it only works well in this case! // kind of like how the O(n^2) insertion sort is used in some places - var A = *A_arg; - var B = *B_arg; + var A = A_arg.*; + var B = B_arg.*; while (true) { // find the first place in B where the first item in A needs to be inserted @@ -751,7 +784,7 @@ fn mergeInPlace(comptime T: type, items: []T, A_arg: &const Range, B_arg: &const } // merge operation using an internal buffer -fn mergeInternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T,&const T)bool, buffer: &const Range) void { +fn mergeInternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, buffer: &const Range) void { // whenever we find a value to add to the final array, swap it with the value that's already in that spot // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order var A_count: usize = 0; @@ -787,9 +820,9 @@ fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_s // combine a linear search with a binary search to reduce the number of comparisons in situations // where have some idea as to how many unique values there are and where the next value might be -fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool, unique: usize) usize { +fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length()/unique, usize(1)); + const skip = math.max(range.length() / unique, usize(1)); var index = range.start + skip; while (lessThan(items[index - 1], value)) : (index += skip) { @@ -801,9 +834,9 @@ fn findFirstForward(comptime T: type, items: []T, value: &const T, range: &const return binaryFirst(T, items, value, Range.init(index - skip, index), lessThan); } -fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool, unique: usize) usize { +fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length()/unique, usize(1)); + const skip = math.max(range.length() / unique, usize(1)); var index = range.end - skip; while (index > range.start and !lessThan(items[index - 1], value)) : (index -= skip) { @@ -815,9 +848,9 @@ fn findFirstBackward(comptime T: type, items: []T, value: &const T, range: &cons return binaryFirst(T, items, value, Range.init(index, index + skip), lessThan); } -fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool, unique: usize) usize { +fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length()/unique, usize(1)); + const skip = math.max(range.length() / unique, usize(1)); var index = range.start + skip; while (!lessThan(value, items[index - 1])) : (index += skip) { @@ -829,9 +862,9 @@ fn findLastForward(comptime T: type, items: []T, value: &const T, range: &const return binaryLast(T, items, value, Range.init(index - skip, index), lessThan); } -fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool, unique: usize) usize { +fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool, unique: usize) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length()/unique, usize(1)); + const skip = math.max(range.length() / unique, usize(1)); var index = range.end - skip; while (index > range.start and lessThan(value, items[index - 1])) : (index -= skip) { @@ -843,12 +876,12 @@ fn findLastBackward(comptime T: type, items: []T, value: &const T, range: &const return binaryLast(T, items, value, Range.init(index, index + skip), lessThan); } -fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool) usize { +fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool) usize { var start = range.start; var end = range.end - 1; if (range.start >= range.end) return range.end; while (start < end) { - const mid = start + (end - start)/2; + const mid = start + (end - start) / 2; if (lessThan(items[mid], value)) { start = mid + 1; } else { @@ -861,12 +894,12 @@ fn binaryFirst(comptime T: type, items: []T, value: &const T, range: &const Rang return start; } -fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T,&const T)bool) usize { +fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range, lessThan: fn(&const T, &const T) bool) usize { var start = range.start; var end = range.end - 1; if (range.start >= range.end) return range.end; while (start < end) { - const mid = start + (end - start)/2; + const mid = start + (end - start) / 2; if (!lessThan(value, items[mid])) { start = mid + 1; } else { @@ -879,7 +912,7 @@ fn binaryLast(comptime T: type, items: []T, value: &const T, range: &const Range return start; } -fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, lessThan: fn(&const T,&const T)bool, into: []T) void { +fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, into: []T) void { var A_index: usize = A.start; var B_index: usize = B.start; const A_last = A.end; @@ -909,7 +942,7 @@ fn mergeInto(comptime T: type, from: []T, A: &const Range, B: &const Range, less } } -fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T,&const T)bool, cache: []T) void { +fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, lessThan: fn(&const T, &const T) bool, cache: []T) void { // A fits into the cache, so use that instead of the internal buffer var A_index: usize = 0; var B_index: usize = B.start; @@ -937,29 +970,27 @@ fn mergeExternal(comptime T: type, items: []T, A: &const Range, B: &const Range, mem.copy(T, items[insert_index..], cache[A_index..A_last]); } -fn swap(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool, order: &[8]u8, x: usize, y: usize) void { - if (lessThan(items[y], items[x]) or - ((*order)[x] > (*order)[y] and !lessThan(items[x], items[y]))) - { +fn swap(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool, order: &[8]u8, x: usize, y: usize) void { + if (lessThan(items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(items[x], items[y]))) { mem.swap(T, &items[x], &items[y]); - mem.swap(u8, &(*order)[x], &(*order)[y]); + mem.swap(u8, &(order.*)[x], &(order.*)[y]); } } fn i32asc(lhs: &const i32, rhs: &const i32) bool { - return *lhs < *rhs; + return lhs.* < rhs.*; } fn i32desc(lhs: &const i32, rhs: &const i32) bool { - return *rhs < *lhs; + return rhs.* < lhs.*; } fn u8asc(lhs: &const u8, rhs: &const u8) bool { - return *lhs < *rhs; + return lhs.* < rhs.*; } fn u8desc(lhs: &const u8, rhs: &const u8) bool { - return *rhs < *lhs; + return rhs.* < lhs.*; } test "stable sort" { @@ -967,44 +998,125 @@ test "stable sort" { comptime testStableSort(); } fn testStableSort() void { - var expected = []IdAndValue { - IdAndValue{.id = 0, .value = 0}, - IdAndValue{.id = 1, .value = 0}, - IdAndValue{.id = 2, .value = 0}, - IdAndValue{.id = 0, .value = 1}, - IdAndValue{.id = 1, .value = 1}, - IdAndValue{.id = 2, .value = 1}, - IdAndValue{.id = 0, .value = 2}, - IdAndValue{.id = 1, .value = 2}, - IdAndValue{.id = 2, .value = 2}, + var expected = []IdAndValue{ + IdAndValue{ + .id = 0, + .value = 0, + }, + IdAndValue{ + .id = 1, + .value = 0, + }, + IdAndValue{ + .id = 2, + .value = 0, + }, + IdAndValue{ + .id = 0, + .value = 1, + }, + IdAndValue{ + .id = 1, + .value = 1, + }, + IdAndValue{ + .id = 2, + .value = 1, + }, + IdAndValue{ + .id = 0, + .value = 2, + }, + IdAndValue{ + .id = 1, + .value = 2, + }, + IdAndValue{ + .id = 2, + .value = 2, + }, }; - var cases = [][9]IdAndValue { - []IdAndValue { - IdAndValue{.id = 0, .value = 0}, - IdAndValue{.id = 0, .value = 1}, - IdAndValue{.id = 0, .value = 2}, - IdAndValue{.id = 1, .value = 0}, - IdAndValue{.id = 1, .value = 1}, - IdAndValue{.id = 1, .value = 2}, - IdAndValue{.id = 2, .value = 0}, - IdAndValue{.id = 2, .value = 1}, - IdAndValue{.id = 2, .value = 2}, + var cases = [][9]IdAndValue{ + []IdAndValue{ + IdAndValue{ + .id = 0, + .value = 0, + }, + IdAndValue{ + .id = 0, + .value = 1, + }, + IdAndValue{ + .id = 0, + .value = 2, + }, + IdAndValue{ + .id = 1, + .value = 0, + }, + IdAndValue{ + .id = 1, + .value = 1, + }, + IdAndValue{ + .id = 1, + .value = 2, + }, + IdAndValue{ + .id = 2, + .value = 0, + }, + IdAndValue{ + .id = 2, + .value = 1, + }, + IdAndValue{ + .id = 2, + .value = 2, + }, }, - []IdAndValue { - IdAndValue{.id = 0, .value = 2}, - IdAndValue{.id = 0, .value = 1}, - IdAndValue{.id = 0, .value = 0}, - IdAndValue{.id = 1, .value = 2}, - IdAndValue{.id = 1, .value = 1}, - IdAndValue{.id = 1, .value = 0}, - IdAndValue{.id = 2, .value = 2}, - IdAndValue{.id = 2, .value = 1}, - IdAndValue{.id = 2, .value = 0}, + []IdAndValue{ + IdAndValue{ + .id = 0, + .value = 2, + }, + IdAndValue{ + .id = 0, + .value = 1, + }, + IdAndValue{ + .id = 0, + .value = 0, + }, + IdAndValue{ + .id = 1, + .value = 2, + }, + IdAndValue{ + .id = 1, + .value = 1, + }, + IdAndValue{ + .id = 1, + .value = 0, + }, + IdAndValue{ + .id = 2, + .value = 2, + }, + IdAndValue{ + .id = 2, + .value = 1, + }, + IdAndValue{ + .id = 2, + .value = 0, + }, }, }; for (cases) |*case| { - insertionSort(IdAndValue, (*case)[0..], cmpByValue); - for (*case) |item, i| { + insertionSort(IdAndValue, (case.*)[0..], cmpByValue); + for (case.*) |item, i| { assert(item.id == expected[i].id); assert(item.value == expected[i].value); } @@ -1019,13 +1131,31 @@ fn cmpByValue(a: &const IdAndValue, b: &const IdAndValue) bool { } test "std.sort" { - const u8cases = [][]const []const u8 { - [][]const u8{"", ""}, - [][]const u8{"a", "a"}, - [][]const u8{"az", "az"}, - [][]const u8{"za", "az"}, - [][]const u8{"asdf", "adfs"}, - [][]const u8{"one", "eno"}, + const u8cases = [][]const []const u8{ + [][]const u8{ + "", + "", + }, + [][]const u8{ + "a", + "a", + }, + [][]const u8{ + "az", + "az", + }, + [][]const u8{ + "za", + "az", + }, + [][]const u8{ + "asdf", + "adfs", + }, + [][]const u8{ + "one", + "eno", + }, }; for (u8cases) |case| { @@ -1036,13 +1166,59 @@ test "std.sort" { assert(mem.eql(u8, slice, case[1])); } - const i32cases = [][]const []const i32 { - [][]const i32{[]i32{}, []i32{}}, - [][]const i32{[]i32{1}, []i32{1}}, - [][]const i32{[]i32{0, 1}, []i32{0, 1}}, - [][]const i32{[]i32{1, 0}, []i32{0, 1}}, - [][]const i32{[]i32{1, -1, 0}, []i32{-1, 0, 1}}, - [][]const i32{[]i32{2, 1, 3}, []i32{1, 2, 3}}, + const i32cases = [][]const []const i32{ + [][]const i32{ + []i32{}, + []i32{}, + }, + [][]const i32{ + []i32{1}, + []i32{1}, + }, + [][]const i32{ + []i32{ + 0, + 1, + }, + []i32{ + 0, + 1, + }, + }, + [][]const i32{ + []i32{ + 1, + 0, + }, + []i32{ + 0, + 1, + }, + }, + [][]const i32{ + []i32{ + 1, + -1, + 0, + }, + []i32{ + -1, + 0, + 1, + }, + }, + [][]const i32{ + []i32{ + 2, + 1, + 3, + }, + []i32{ + 1, + 2, + 3, + }, + }, }; for (i32cases) |case| { @@ -1055,13 +1231,59 @@ test "std.sort" { } test "std.sort descending" { - const rev_cases = [][]const []const i32 { - [][]const i32{[]i32{}, []i32{}}, - [][]const i32{[]i32{1}, []i32{1}}, - [][]const i32{[]i32{0, 1}, []i32{1, 0}}, - [][]const i32{[]i32{1, 0}, []i32{1, 0}}, - [][]const i32{[]i32{1, -1, 0}, []i32{1, 0, -1}}, - [][]const i32{[]i32{2, 1, 3}, []i32{3, 2, 1}}, + const rev_cases = [][]const []const i32{ + [][]const i32{ + []i32{}, + []i32{}, + }, + [][]const i32{ + []i32{1}, + []i32{1}, + }, + [][]const i32{ + []i32{ + 0, + 1, + }, + []i32{ + 1, + 0, + }, + }, + [][]const i32{ + []i32{ + 1, + 0, + }, + []i32{ + 1, + 0, + }, + }, + [][]const i32{ + []i32{ + 1, + -1, + 0, + }, + []i32{ + 1, + 0, + -1, + }, + }, + [][]const i32{ + []i32{ + 2, + 1, + 3, + }, + []i32{ + 3, + 2, + 1, + }, + }, }; for (rev_cases) |case| { @@ -1074,10 +1296,22 @@ test "std.sort descending" { } test "another sort case" { - var arr = []i32{ 5, 3, 1, 2, 4 }; + var arr = []i32{ + 5, + 3, + 1, + 2, + 4, + }; sort(i32, arr[0..], i32asc); - assert(mem.eql(i32, arr, []i32{ 1, 2, 3, 4, 5 })); + assert(mem.eql(i32, arr, []i32{ + 1, + 2, + 3, + 4, + 5, + })); } test "sort fuzz testing" { @@ -1112,7 +1346,7 @@ fn fuzzTest(rng: &std.rand.Random) void { } } -pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool) T { +pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) T { var i: usize = 0; var smallest = items[0]; for (items[1..]) |item| { @@ -1123,7 +1357,7 @@ pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const return smallest; } -pub fn max(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)bool) T { +pub fn max(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T) bool) T { var i: usize = 0; var biggest = items[0]; for (items[1..]) |item| { -- cgit v1.2.3 From 02cb220faf0d527b656a3a87ec96e6738770c8e6 Mon Sep 17 00:00:00 2001 From: Jimmi HC Date: Tue, 5 Jun 2018 11:14:43 +0200 Subject: Renamed "(int/float literal)" to "comptime_int/float" --- doc/langref.html.in | 18 ++-- src/all_types.hpp | 4 +- src/analyze.cpp | 94 ++++++++++---------- src/codegen.cpp | 38 ++++---- src/ir.cpp | 230 ++++++++++++++++++++++++------------------------ std/math/ln.zig | 4 +- std/math/log.zig | 6 +- std/math/log10.zig | 4 +- std/math/log2.zig | 4 +- std/math/sqrt.zig | 4 +- test/cases/math.zig | 24 +++-- test/cases/misc.zig | 4 +- test/compile_errors.zig | 12 +-- 13 files changed, 230 insertions(+), 216 deletions(-) (limited to 'std/math/log2.zig') diff --git a/doc/langref.html.in b/doc/langref.html.in index 28fdf4d8b9..0689baa6f9 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -4893,8 +4893,8 @@ pub const TypeId = enum { Pointer, Array, Struct, - FloatLiteral, - IntLiteral, + ComptimeFloat, + ComptimeInt, UndefinedLiteral, NullLiteral, Nullable, @@ -4927,8 +4927,8 @@ pub const TypeInfo = union(TypeId) { Pointer: Pointer, Array: Array, Struct: Struct, - FloatLiteral: void, - IntLiteral: void, + ComptimeFloat: void, + ComptimeInt: void, UndefinedLiteral: void, NullLiteral: void, Nullable: Nullable, @@ -5685,8 +5685,8 @@ pub const TypeId = enum { Pointer, Array, Struct, - FloatLiteral, - IntLiteral, + ComptimeFloat, + ComptimeInt, UndefinedLiteral, NullLiteral, Nullable, @@ -5713,10 +5713,10 @@ pub const TypeInfo = union(TypeId) { Pointer: Pointer, Array: Array, Struct: Struct, - FloatLiteral: void, - IntLiteral: void, + ComptimeFloat: void, + ComptimeInt: void, UndefinedLiteral: void, - NullLiteral: void, + Null: void, Nullable: Nullable, ErrorUnion: ErrorUnion, ErrorSet: ErrorSet, diff --git a/src/all_types.hpp b/src/all_types.hpp index d237eb00bb..bf635eae7c 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -1159,8 +1159,8 @@ enum TypeTableEntryId { TypeTableEntryIdPointer, TypeTableEntryIdArray, TypeTableEntryIdStruct, - TypeTableEntryIdNumLitFloat, - TypeTableEntryIdNumLitInt, + TypeTableEntryIdComptimeFloat, + TypeTableEntryIdComptimeInt, TypeTableEntryIdUndefLit, TypeTableEntryIdNullLit, TypeTableEntryIdMaybe, diff --git a/src/analyze.cpp b/src/analyze.cpp index 31c0726459..21841d45b6 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -232,8 +232,8 @@ bool type_is_complete(TypeTableEntry *type_entry) { case TypeTableEntryIdFloat: case TypeTableEntryIdPointer: case TypeTableEntryIdArray: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -268,8 +268,8 @@ bool type_has_zero_bits_known(TypeTableEntry *type_entry) { case TypeTableEntryIdFloat: case TypeTableEntryIdPointer: case TypeTableEntryIdArray: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -1333,8 +1333,8 @@ static bool type_allowed_in_packed_struct(TypeTableEntry *type_entry) { zig_unreachable(); case TypeTableEntryIdMetaType: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdErrorUnion: @@ -1374,8 +1374,8 @@ static bool type_allowed_in_extern(CodeGen *g, TypeTableEntry *type_entry) { case TypeTableEntryIdInvalid: zig_unreachable(); case TypeTableEntryIdMetaType: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdErrorUnion: @@ -1518,8 +1518,8 @@ static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *c add_node_error(g, param_node->data.param_decl.type, buf_sprintf("parameter of type '%s' not allowed", buf_ptr(&type_entry->name))); return g->builtin_types.entry_invalid; - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdNamespace: case TypeTableEntryIdBlock: case TypeTableEntryIdBoundFn: @@ -1607,8 +1607,8 @@ static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *c buf_sprintf("return type '%s' not allowed", buf_ptr(&fn_type_id.return_type->name))); return g->builtin_types.entry_invalid; - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdNamespace: case TypeTableEntryIdBlock: case TypeTableEntryIdBoundFn: @@ -3337,8 +3337,6 @@ TypeTableEntry *validate_var_type(CodeGen *g, AstNode *source_node, TypeTableEnt case TypeTableEntryIdInvalid: return g->builtin_types.entry_invalid; case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdBlock: @@ -3347,6 +3345,8 @@ TypeTableEntry *validate_var_type(CodeGen *g, AstNode *source_node, TypeTableEnt add_node_error(g, source_node, buf_sprintf("variable of type '%s' not allowed", buf_ptr(&type_entry->name))); return g->builtin_types.entry_invalid; + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdNamespace: case TypeTableEntryIdMetaType: case TypeTableEntryIdVoid: @@ -3480,8 +3480,8 @@ static void resolve_decl_var(CodeGen *g, TldVar *tld_var) { add_node_error(g, source_node, buf_sprintf("variable initialization is unreachable")); implicit_type = g->builtin_types.entry_invalid; } else if ((!is_const || linkage == VarLinkageExternal) && - (implicit_type->id == TypeTableEntryIdNumLitFloat || - implicit_type->id == TypeTableEntryIdNumLitInt)) + (implicit_type->id == TypeTableEntryIdComptimeFloat || + implicit_type->id == TypeTableEntryIdComptimeInt)) { add_node_error(g, source_node, buf_sprintf("unable to infer variable type")); implicit_type = g->builtin_types.entry_invalid; @@ -3730,8 +3730,8 @@ static bool is_container(TypeTableEntry *type_entry) { case TypeTableEntryIdInt: case TypeTableEntryIdFloat: case TypeTableEntryIdArray: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -3779,8 +3779,8 @@ void resolve_container_type(CodeGen *g, TypeTableEntry *type_entry) { case TypeTableEntryIdInt: case TypeTableEntryIdFloat: case TypeTableEntryIdArray: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -4283,8 +4283,8 @@ bool handle_is_ptr(TypeTableEntry *type_entry) { switch (type_entry->id) { case TypeTableEntryIdInvalid: case TypeTableEntryIdMetaType: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdNamespace: @@ -4568,7 +4568,7 @@ static uint32_t hash_const_val(ConstExprValue *const_val) { case TypeTableEntryIdVoid: return (uint32_t)4149439618; case TypeTableEntryIdInt: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeInt: { uint32_t result = 1331471175; for (size_t i = 0; i < const_val->data.x_bigint.digit_count; i += 1) { @@ -4609,7 +4609,7 @@ static uint32_t hash_const_val(ConstExprValue *const_val) { default: zig_unreachable(); } - case TypeTableEntryIdNumLitFloat: + case TypeTableEntryIdComptimeFloat: { float128_t f128 = bigfloat_to_f128(&const_val->data.x_bigfloat); uint32_t ints[4]; @@ -4754,8 +4754,8 @@ static bool can_mutate_comptime_var_state(ConstExprValue *value) { case TypeTableEntryIdUnreachable: case TypeTableEntryIdInt: case TypeTableEntryIdFloat: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdNamespace: @@ -4819,8 +4819,8 @@ static bool return_type_is_cacheable(TypeTableEntry *return_type) { case TypeTableEntryIdUnreachable: case TypeTableEntryIdInt: case TypeTableEntryIdFloat: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdNamespace: @@ -4930,8 +4930,8 @@ bool type_requires_comptime(TypeTableEntry *type_entry) { case TypeTableEntryIdInvalid: case TypeTableEntryIdOpaque: zig_unreachable(); - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMetaType: @@ -5070,7 +5070,7 @@ ConstExprValue *create_const_signed(TypeTableEntry *type, int64_t x) { void init_const_float(ConstExprValue *const_val, TypeTableEntry *type, double value) { const_val->special = ConstValSpecialStatic; const_val->type = type; - if (type->id == TypeTableEntryIdNumLitFloat) { + if (type->id == TypeTableEntryIdComptimeFloat) { bigfloat_init_64(&const_val->data.x_bigfloat, value); } else if (type->id == TypeTableEntryIdFloat) { switch (type->data.floating.bit_count) { @@ -5350,10 +5350,10 @@ bool const_values_equal(ConstExprValue *a, ConstExprValue *b) { default: zig_unreachable(); } - case TypeTableEntryIdNumLitFloat: + case TypeTableEntryIdComptimeFloat: return bigfloat_cmp(&a->data.x_bigfloat, &b->data.x_bigfloat) == CmpEQ; case TypeTableEntryIdInt: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeInt: return bigint_cmp(&a->data.x_bigint, &b->data.x_bigint) == CmpEQ; case TypeTableEntryIdPointer: case TypeTableEntryIdFn: @@ -5514,7 +5514,7 @@ void render_const_value(CodeGen *g, Buf *buf, ConstExprValue *const_val) { case TypeTableEntryIdVoid: buf_appendf(buf, "{}"); return; - case TypeTableEntryIdNumLitFloat: + case TypeTableEntryIdComptimeFloat: bigfloat_append_buf(buf, &const_val->data.x_bigfloat); return; case TypeTableEntryIdFloat: @@ -5542,7 +5542,7 @@ void render_const_value(CodeGen *g, Buf *buf, ConstExprValue *const_val) { default: zig_unreachable(); } - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdInt: bigint_append_buf(buf, &const_val->data.x_bigint, 10); return; @@ -5761,8 +5761,8 @@ uint32_t type_id_hash(TypeId x) { case TypeTableEntryIdUnreachable: case TypeTableEntryIdFloat: case TypeTableEntryIdStruct: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -5807,8 +5807,8 @@ bool type_id_eql(TypeId a, TypeId b) { case TypeTableEntryIdUnreachable: case TypeTableEntryIdFloat: case TypeTableEntryIdStruct: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -5929,8 +5929,8 @@ static const TypeTableEntryId all_type_ids[] = { TypeTableEntryIdPointer, TypeTableEntryIdArray, TypeTableEntryIdStruct, - TypeTableEntryIdNumLitFloat, - TypeTableEntryIdNumLitInt, + TypeTableEntryIdComptimeFloat, + TypeTableEntryIdComptimeInt, TypeTableEntryIdUndefLit, TypeTableEntryIdNullLit, TypeTableEntryIdMaybe, @@ -5980,9 +5980,9 @@ size_t type_id_index(TypeTableEntry *entry) { if (entry->data.structure.is_slice) return 25; return 8; - case TypeTableEntryIdNumLitFloat: + case TypeTableEntryIdComptimeFloat: return 9; - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeInt: return 10; case TypeTableEntryIdUndefLit: return 11; @@ -6038,10 +6038,10 @@ const char *type_id_name(TypeTableEntryId id) { return "Array"; case TypeTableEntryIdStruct: return "Struct"; - case TypeTableEntryIdNumLitFloat: - return "FloatLiteral"; - case TypeTableEntryIdNumLitInt: - return "IntLiteral"; + case TypeTableEntryIdComptimeFloat: + return "ComptimeFloat"; + case TypeTableEntryIdComptimeInt: + return "ComptimeInt"; case TypeTableEntryIdUndefLit: return "UndefinedLiteral"; case TypeTableEntryIdNullLit: diff --git a/src/codegen.cpp b/src/codegen.cpp index 49c93feaa5..dc915e766d 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -4916,8 +4916,8 @@ static LLVMValueRef pack_const_int(CodeGen *g, LLVMTypeRef big_int_type_ref, Con case TypeTableEntryIdInvalid: case TypeTableEntryIdMetaType: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdErrorUnion: @@ -5362,8 +5362,8 @@ static LLVMValueRef gen_const_val(CodeGen *g, ConstExprValue *const_val, const c case TypeTableEntryIdInvalid: case TypeTableEntryIdMetaType: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdNamespace: @@ -5604,7 +5604,7 @@ static void do_code_gen(CodeGen *g) { TldVar *tld_var = g->global_vars.at(i); VariableTableEntry *var = tld_var->var; - if (var->value->type->id == TypeTableEntryIdNumLitFloat) { + if (var->value->type->id == TypeTableEntryIdComptimeFloat) { // Generate debug info for it but that's it. ConstExprValue *const_val = var->value; assert(const_val->special != ConstValSpecialRuntime); @@ -5618,7 +5618,7 @@ static void do_code_gen(CodeGen *g) { continue; } - if (var->value->type->id == TypeTableEntryIdNumLitInt) { + if (var->value->type->id == TypeTableEntryIdComptimeInt) { // Generate debug info for it but that's it. ConstExprValue *const_val = var->value; assert(const_val->special != ConstValSpecialRuntime); @@ -6012,16 +6012,18 @@ static void define_builtin_types(CodeGen *g) { g->builtin_types.entry_block = entry; } { - TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdNumLitFloat); - buf_init_from_str(&entry->name, "(float literal)"); + TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdComptimeFloat); + buf_init_from_str(&entry->name, "comptime_float"); entry->zero_bits = true; g->builtin_types.entry_num_lit_float = entry; + g->primitive_type_table.put(&entry->name, entry); } { - TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdNumLitInt); - buf_init_from_str(&entry->name, "(integer literal)"); + TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdComptimeInt); + buf_init_from_str(&entry->name, "comptime_int"); entry->zero_bits = true; g->builtin_types.entry_num_lit_int = entry; + g->primitive_type_table.put(&entry->name, entry); } { TypeTableEntry *entry = new_type_table_entry(TypeTableEntryIdUndefLit); @@ -6495,8 +6497,8 @@ static void define_builtin_compile_vars(CodeGen *g) { " Slice: Slice,\n" " Array: Array,\n" " Struct: Struct,\n" - " FloatLiteral: void,\n" - " IntLiteral: void,\n" + " ComptimeFloat: void,\n" + " ComptimeInt: void,\n" " UndefinedLiteral: void,\n" " NullLiteral: void,\n" " Nullable: Nullable,\n" @@ -7070,8 +7072,8 @@ static void prepend_c_type_to_decl_list(CodeGen *g, GenH *gen_h, TypeTableEntry switch (type_entry->id) { case TypeTableEntryIdInvalid: case TypeTableEntryIdMetaType: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdNamespace: @@ -7255,8 +7257,8 @@ static void get_c_type(CodeGen *g, GenH *gen_h, TypeTableEntry *type_entry, Buf case TypeTableEntryIdBoundFn: case TypeTableEntryIdNamespace: case TypeTableEntryIdBlock: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdArgTuple: @@ -7407,8 +7409,8 @@ static void gen_h_file(CodeGen *g) { case TypeTableEntryIdInt: case TypeTableEntryIdFloat: case TypeTableEntryIdPointer: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdArray: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: diff --git a/src/ir.cpp b/src/ir.cpp index 5cea04ea55..2819ef5b0e 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -6945,14 +6945,14 @@ static bool ir_emit_global_runtime_side_effect(IrAnalyze *ira, IrInstruction *so } static bool const_val_fits_in_num_lit(ConstExprValue *const_val, TypeTableEntry *num_lit_type) { - return ((num_lit_type->id == TypeTableEntryIdNumLitFloat && - (const_val->type->id == TypeTableEntryIdFloat || const_val->type->id == TypeTableEntryIdNumLitFloat)) || - (num_lit_type->id == TypeTableEntryIdNumLitInt && - (const_val->type->id == TypeTableEntryIdInt || const_val->type->id == TypeTableEntryIdNumLitInt))); + return ((num_lit_type->id == TypeTableEntryIdComptimeFloat && + (const_val->type->id == TypeTableEntryIdFloat || const_val->type->id == TypeTableEntryIdComptimeFloat)) || + (num_lit_type->id == TypeTableEntryIdComptimeInt && + (const_val->type->id == TypeTableEntryIdInt || const_val->type->id == TypeTableEntryIdComptimeInt))); } static bool float_has_fraction(ConstExprValue *const_val) { - if (const_val->type->id == TypeTableEntryIdNumLitFloat) { + if (const_val->type->id == TypeTableEntryIdComptimeFloat) { return bigfloat_has_fraction(&const_val->data.x_bigfloat); } else if (const_val->type->id == TypeTableEntryIdFloat) { switch (const_val->type->data.floating.bit_count) { @@ -6975,7 +6975,7 @@ static bool float_has_fraction(ConstExprValue *const_val) { } static void float_append_buf(Buf *buf, ConstExprValue *const_val) { - if (const_val->type->id == TypeTableEntryIdNumLitFloat) { + if (const_val->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_append_buf(buf, &const_val->data.x_bigfloat); } else if (const_val->type->id == TypeTableEntryIdFloat) { switch (const_val->type->data.floating.bit_count) { @@ -7010,7 +7010,7 @@ static void float_append_buf(Buf *buf, ConstExprValue *const_val) { } static void float_init_bigint(BigInt *bigint, ConstExprValue *const_val) { - if (const_val->type->id == TypeTableEntryIdNumLitFloat) { + if (const_val->type->id == TypeTableEntryIdComptimeFloat) { bigint_init_bigfloat(bigint, &const_val->data.x_bigfloat); } else if (const_val->type->id == TypeTableEntryIdFloat) { switch (const_val->type->data.floating.bit_count) { @@ -7046,7 +7046,7 @@ static void float_init_bigint(BigInt *bigint, ConstExprValue *const_val) { } static void float_init_bigfloat(ConstExprValue *dest_val, BigFloat *bigfloat) { - if (dest_val->type->id == TypeTableEntryIdNumLitFloat) { + if (dest_val->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_init_bigfloat(&dest_val->data.x_bigfloat, bigfloat); } else if (dest_val->type->id == TypeTableEntryIdFloat) { switch (dest_val->type->data.floating.bit_count) { @@ -7068,7 +7068,7 @@ static void float_init_bigfloat(ConstExprValue *dest_val, BigFloat *bigfloat) { } static void float_init_f32(ConstExprValue *dest_val, float x) { - if (dest_val->type->id == TypeTableEntryIdNumLitFloat) { + if (dest_val->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_init_32(&dest_val->data.x_bigfloat, x); } else if (dest_val->type->id == TypeTableEntryIdFloat) { switch (dest_val->type->data.floating.bit_count) { @@ -7094,7 +7094,7 @@ static void float_init_f32(ConstExprValue *dest_val, float x) { } static void float_init_f64(ConstExprValue *dest_val, double x) { - if (dest_val->type->id == TypeTableEntryIdNumLitFloat) { + if (dest_val->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_init_64(&dest_val->data.x_bigfloat, x); } else if (dest_val->type->id == TypeTableEntryIdFloat) { switch (dest_val->type->data.floating.bit_count) { @@ -7120,7 +7120,7 @@ static void float_init_f64(ConstExprValue *dest_val, double x) { } static void float_init_f128(ConstExprValue *dest_val, float128_t x) { - if (dest_val->type->id == TypeTableEntryIdNumLitFloat) { + if (dest_val->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_init_128(&dest_val->data.x_bigfloat, x); } else if (dest_val->type->id == TypeTableEntryIdFloat) { switch (dest_val->type->data.floating.bit_count) { @@ -7150,7 +7150,7 @@ static void float_init_f128(ConstExprValue *dest_val, float128_t x) { } static void float_init_float(ConstExprValue *dest_val, ConstExprValue *src_val) { - if (src_val->type->id == TypeTableEntryIdNumLitFloat) { + if (src_val->type->id == TypeTableEntryIdComptimeFloat) { float_init_bigfloat(dest_val, &src_val->data.x_bigfloat); } else if (src_val->type->id == TypeTableEntryIdFloat) { switch (src_val->type->data.floating.bit_count) { @@ -7173,7 +7173,7 @@ static void float_init_float(ConstExprValue *dest_val, ConstExprValue *src_val) static Cmp float_cmp(ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { return bigfloat_cmp(&op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7210,7 +7210,7 @@ static Cmp float_cmp(ConstExprValue *op1, ConstExprValue *op2) { } static Cmp float_cmp_zero(ConstExprValue *op) { - if (op->type->id == TypeTableEntryIdNumLitFloat) { + if (op->type->id == TypeTableEntryIdComptimeFloat) { return bigfloat_cmp_zero(&op->data.x_bigfloat); } else if (op->type->id == TypeTableEntryIdFloat) { switch (op->type->data.floating.bit_count) { @@ -7251,7 +7251,7 @@ static Cmp float_cmp_zero(ConstExprValue *op) { static void float_add(ConstExprValue *out_val, ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); out_val->type = op1->type; - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_add(&out_val->data.x_bigfloat, &op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7275,7 +7275,7 @@ static void float_add(ConstExprValue *out_val, ConstExprValue *op1, ConstExprVal static void float_sub(ConstExprValue *out_val, ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); out_val->type = op1->type; - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_sub(&out_val->data.x_bigfloat, &op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7299,7 +7299,7 @@ static void float_sub(ConstExprValue *out_val, ConstExprValue *op1, ConstExprVal static void float_mul(ConstExprValue *out_val, ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); out_val->type = op1->type; - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_mul(&out_val->data.x_bigfloat, &op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7323,7 +7323,7 @@ static void float_mul(ConstExprValue *out_val, ConstExprValue *op1, ConstExprVal static void float_div(ConstExprValue *out_val, ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); out_val->type = op1->type; - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_div(&out_val->data.x_bigfloat, &op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7347,7 +7347,7 @@ static void float_div(ConstExprValue *out_val, ConstExprValue *op1, ConstExprVal static void float_div_trunc(ConstExprValue *out_val, ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); out_val->type = op1->type; - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_div_trunc(&out_val->data.x_bigfloat, &op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7382,7 +7382,7 @@ static void float_div_trunc(ConstExprValue *out_val, ConstExprValue *op1, ConstE static void float_div_floor(ConstExprValue *out_val, ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); out_val->type = op1->type; - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_div_floor(&out_val->data.x_bigfloat, &op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7407,7 +7407,7 @@ static void float_div_floor(ConstExprValue *out_val, ConstExprValue *op1, ConstE static void float_rem(ConstExprValue *out_val, ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); out_val->type = op1->type; - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_rem(&out_val->data.x_bigfloat, &op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7431,7 +7431,7 @@ static void float_rem(ConstExprValue *out_val, ConstExprValue *op1, ConstExprVal static void float_mod(ConstExprValue *out_val, ConstExprValue *op1, ConstExprValue *op2) { assert(op1->type == op2->type); out_val->type = op1->type; - if (op1->type->id == TypeTableEntryIdNumLitFloat) { + if (op1->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_mod(&out_val->data.x_bigfloat, &op1->data.x_bigfloat, &op2->data.x_bigfloat); } else if (op1->type->id == TypeTableEntryIdFloat) { switch (op1->type->data.floating.bit_count) { @@ -7456,7 +7456,7 @@ static void float_mod(ConstExprValue *out_val, ConstExprValue *op1, ConstExprVal static void float_negate(ConstExprValue *out_val, ConstExprValue *op) { out_val->type = op->type; - if (op->type->id == TypeTableEntryIdNumLitFloat) { + if (op->type->id == TypeTableEntryIdComptimeFloat) { bigfloat_negate(&out_val->data.x_bigfloat, &op->data.x_bigfloat); } else if (op->type->id == TypeTableEntryIdFloat) { switch (op->type->data.floating.bit_count) { @@ -7530,9 +7530,9 @@ static bool ir_num_lit_fits_in_other_type(IrAnalyze *ira, IrInstruction *instruc assert(const_val->special != ConstValSpecialRuntime); bool const_val_is_int = (const_val->type->id == TypeTableEntryIdInt || - const_val->type->id == TypeTableEntryIdNumLitInt); + const_val->type->id == TypeTableEntryIdComptimeInt); bool const_val_is_float = (const_val->type->id == TypeTableEntryIdFloat || - const_val->type->id == TypeTableEntryIdNumLitFloat); + const_val->type->id == TypeTableEntryIdComptimeFloat); if (other_type->id == TypeTableEntryIdFloat) { return true; } else if (other_type->id == TypeTableEntryIdInt && const_val_is_int) { @@ -7576,7 +7576,7 @@ static bool ir_num_lit_fits_in_other_type(IrAnalyze *ira, IrInstruction *instruc return true; } } - if (explicit_cast && (other_type->id == TypeTableEntryIdInt || other_type->id == TypeTableEntryIdNumLitInt) && + if (explicit_cast && (other_type->id == TypeTableEntryIdInt || other_type->id == TypeTableEntryIdComptimeInt) && const_val_is_float) { if (float_has_fraction(const_val)) { @@ -7589,7 +7589,7 @@ static bool ir_num_lit_fits_in_other_type(IrAnalyze *ira, IrInstruction *instruc buf_ptr(&other_type->name))); return false; } else { - if (other_type->id == TypeTableEntryIdNumLitInt) { + if (other_type->id == TypeTableEntryIdComptimeInt) { return true; } else { BigInt bigint; @@ -8078,8 +8078,8 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira, // implicit number literal to typed number // implicit number literal to &const integer - if (actual_type->id == TypeTableEntryIdNumLitFloat || - actual_type->id == TypeTableEntryIdNumLitInt) + if (actual_type->id == TypeTableEntryIdComptimeFloat || + actual_type->id == TypeTableEntryIdComptimeInt) { if (expected_type->id == TypeTableEntryIdPointer && expected_type->data.pointer.is_const) @@ -8099,9 +8099,9 @@ static ImplicitCastMatchResult ir_types_match_with_implicit_cast(IrAnalyze *ira, // implicit typed number to integer or float literal. // works when the number is known if (value->value.special == ConstValSpecialStatic) { - if (actual_type->id == TypeTableEntryIdInt && expected_type->id == TypeTableEntryIdNumLitInt) { + if (actual_type->id == TypeTableEntryIdInt && expected_type->id == TypeTableEntryIdComptimeInt) { return ImplicitCastMatchResultYes; - } else if (actual_type->id == TypeTableEntryIdFloat && expected_type->id == TypeTableEntryIdNumLitFloat) { + } else if (actual_type->id == TypeTableEntryIdFloat && expected_type->id == TypeTableEntryIdComptimeFloat) { return ImplicitCastMatchResultYes; } } @@ -8555,8 +8555,8 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod continue; } - if (prev_type->id == TypeTableEntryIdNumLitInt || - prev_type->id == TypeTableEntryIdNumLitFloat) + if (prev_type->id == TypeTableEntryIdComptimeInt || + prev_type->id == TypeTableEntryIdComptimeFloat) { if (ir_num_lit_fits_in_other_type(ira, prev_inst, cur_type, false)) { prev_inst = cur_inst; @@ -8566,8 +8566,8 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod } } - if (cur_type->id == TypeTableEntryIdNumLitInt || - cur_type->id == TypeTableEntryIdNumLitFloat) + if (cur_type->id == TypeTableEntryIdComptimeInt || + cur_type->id == TypeTableEntryIdComptimeFloat) { if (ir_num_lit_fits_in_other_type(ira, cur_inst, prev_type, false)) { continue; @@ -8671,8 +8671,8 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod } else if (expected_type != nullptr && expected_type->id == TypeTableEntryIdErrorUnion) { return get_error_union_type(ira->codegen, err_set_type, expected_type->data.error_union.payload_type); } else { - if (prev_inst->value.type->id == TypeTableEntryIdNumLitInt || - prev_inst->value.type->id == TypeTableEntryIdNumLitFloat) + if (prev_inst->value.type->id == TypeTableEntryIdComptimeInt || + prev_inst->value.type->id == TypeTableEntryIdComptimeFloat) { ir_add_error_node(ira, source_node, buf_sprintf("unable to make error union out of number literal")); @@ -8686,8 +8686,8 @@ static TypeTableEntry *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_nod } } } else if (any_are_null && prev_inst->value.type->id != TypeTableEntryIdNullLit) { - if (prev_inst->value.type->id == TypeTableEntryIdNumLitInt || - prev_inst->value.type->id == TypeTableEntryIdNumLitFloat) + if (prev_inst->value.type->id == TypeTableEntryIdComptimeInt || + prev_inst->value.type->id == TypeTableEntryIdComptimeFloat) { ir_add_error_node(ira, source_node, buf_sprintf("unable to make maybe out of number literal")); @@ -8743,7 +8743,7 @@ static void eval_const_expr_implicit_cast(CastOp cast_op, break; } case CastOpNumLitToConcrete: - if (other_val->type->id == TypeTableEntryIdNumLitFloat) { + if (other_val->type->id == TypeTableEntryIdComptimeFloat) { assert(new_type->id == TypeTableEntryIdFloat); switch (new_type->data.floating.bit_count) { case 32: @@ -8758,7 +8758,7 @@ static void eval_const_expr_implicit_cast(CastOp cast_op, default: zig_unreachable(); } - } else if (other_val->type->id == TypeTableEntryIdNumLitInt) { + } else if (other_val->type->id == TypeTableEntryIdComptimeInt) { bigint_init_bigint(&const_val->data.x_bigint, &other_val->data.x_bigint); } else { zig_unreachable(); @@ -9601,9 +9601,9 @@ static IrInstruction *ir_analyze_number_to_literal(IrAnalyze *ira, IrInstruction IrInstruction *result = ir_create_const(&ira->new_irb, source_instr->scope, source_instr->source_node, wanted_type); - if (wanted_type->id == TypeTableEntryIdNumLitFloat) { + if (wanted_type->id == TypeTableEntryIdComptimeFloat) { float_init_float(&result->value, val); - } else if (wanted_type->id == TypeTableEntryIdNumLitInt) { + } else if (wanted_type->id == TypeTableEntryIdComptimeInt) { bigint_init_bigint(&result->value.data.x_bigint, &val->data.x_bigint); } else { zig_unreachable(); @@ -9978,8 +9978,8 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst TypeTableEntry *wanted_child_type = wanted_type->data.maybe.child_type; if (types_match_const_cast_only(ira, wanted_child_type, actual_type, source_node).id == ConstCastResultIdOk) { return ir_analyze_maybe_wrap(ira, source_instr, value, wanted_type); - } else if (actual_type->id == TypeTableEntryIdNumLitInt || - actual_type->id == TypeTableEntryIdNumLitFloat) + } else if (actual_type->id == TypeTableEntryIdComptimeInt || + actual_type->id == TypeTableEntryIdComptimeFloat) { if (ir_num_lit_fits_in_other_type(ira, value, wanted_child_type, true)) { return ir_analyze_maybe_wrap(ira, source_instr, value, wanted_type); @@ -10013,8 +10013,8 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst if (wanted_type->id == TypeTableEntryIdErrorUnion) { if (types_match_const_cast_only(ira, wanted_type->data.error_union.payload_type, actual_type, source_node).id == ConstCastResultIdOk) { return ir_analyze_err_wrap_payload(ira, source_instr, value, wanted_type); - } else if (actual_type->id == TypeTableEntryIdNumLitInt || - actual_type->id == TypeTableEntryIdNumLitFloat) + } else if (actual_type->id == TypeTableEntryIdComptimeInt || + actual_type->id == TypeTableEntryIdComptimeFloat) { if (ir_num_lit_fits_in_other_type(ira, value, wanted_type->data.error_union.payload_type, true)) { return ir_analyze_err_wrap_payload(ira, source_instr, value, wanted_type); @@ -10062,8 +10062,8 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst TypeTableEntry *wanted_child_type = wanted_type->data.error_union.payload_type->data.maybe.child_type; if (types_match_const_cast_only(ira, wanted_child_type, actual_type, source_node).id == ConstCastResultIdOk || actual_type->id == TypeTableEntryIdNullLit || - actual_type->id == TypeTableEntryIdNumLitInt || - actual_type->id == TypeTableEntryIdNumLitFloat) + actual_type->id == TypeTableEntryIdComptimeInt || + actual_type->id == TypeTableEntryIdComptimeFloat) { IrInstruction *cast1 = ir_analyze_cast(ira, source_instr, wanted_type->data.error_union.payload_type, value); if (type_is_invalid(cast1->value.type)) @@ -10079,8 +10079,8 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst // explicit cast from number literal to another type // explicit cast from number literal to &const integer - if (actual_type->id == TypeTableEntryIdNumLitFloat || - actual_type->id == TypeTableEntryIdNumLitInt) + if (actual_type->id == TypeTableEntryIdComptimeFloat || + actual_type->id == TypeTableEntryIdComptimeInt) { ensure_complete_type(ira->codegen, wanted_type); if (type_is_invalid(wanted_type)) @@ -10109,9 +10109,9 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst return cast2; } else if (ir_num_lit_fits_in_other_type(ira, value, wanted_type, true)) { CastOp op; - if ((actual_type->id == TypeTableEntryIdNumLitFloat && + if ((actual_type->id == TypeTableEntryIdComptimeFloat && wanted_type->id == TypeTableEntryIdFloat) || - (actual_type->id == TypeTableEntryIdNumLitInt && + (actual_type->id == TypeTableEntryIdComptimeInt && wanted_type->id == TypeTableEntryIdInt)) { op = CastOpNumLitToConcrete; @@ -10131,8 +10131,8 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst // explicit cast from typed number to integer or float literal. // works when the number is known at compile time if (instr_is_comptime(value) && - ((actual_type->id == TypeTableEntryIdInt && wanted_type->id == TypeTableEntryIdNumLitInt) || - (actual_type->id == TypeTableEntryIdFloat && wanted_type->id == TypeTableEntryIdNumLitFloat))) + ((actual_type->id == TypeTableEntryIdInt && wanted_type->id == TypeTableEntryIdComptimeInt) || + (actual_type->id == TypeTableEntryIdFloat && wanted_type->id == TypeTableEntryIdComptimeFloat))) { return ir_analyze_number_to_literal(ira, source_instr, value, wanted_type); } @@ -10759,8 +10759,8 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp case TypeTableEntryIdInvalid: zig_unreachable(); // handled above - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdInt: case TypeTableEntryIdFloat: break; @@ -10818,10 +10818,10 @@ static TypeTableEntry *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp bool one_possible_value = !type_requires_comptime(resolved_type) && !type_has_bits(resolved_type); if (one_possible_value || (value_is_comptime(op1_val) && value_is_comptime(op2_val))) { bool answer; - if (resolved_type->id == TypeTableEntryIdNumLitFloat || resolved_type->id == TypeTableEntryIdFloat) { + if (resolved_type->id == TypeTableEntryIdComptimeFloat || resolved_type->id == TypeTableEntryIdFloat) { Cmp cmp_result = float_cmp(op1_val, op2_val); answer = resolve_cmp_op_id(op_id, cmp_result); - } else if (resolved_type->id == TypeTableEntryIdNumLitInt || resolved_type->id == TypeTableEntryIdInt) { + } else if (resolved_type->id == TypeTableEntryIdComptimeInt || resolved_type->id == TypeTableEntryIdInt) { Cmp cmp_result = bigint_cmp(&op1_val->data.x_bigint, &op2_val->data.x_bigint); answer = resolve_cmp_op_id(op_id, cmp_result); } else { @@ -10885,12 +10885,12 @@ static int ir_eval_math_op(TypeTableEntry *type_entry, ConstExprValue *op1_val, bool is_int; bool is_float; Cmp op2_zcmp; - if (type_entry->id == TypeTableEntryIdInt || type_entry->id == TypeTableEntryIdNumLitInt) { + if (type_entry->id == TypeTableEntryIdInt || type_entry->id == TypeTableEntryIdComptimeInt) { is_int = true; is_float = false; op2_zcmp = bigint_cmp_zero(&op2_val->data.x_bigint); } else if (type_entry->id == TypeTableEntryIdFloat || - type_entry->id == TypeTableEntryIdNumLitFloat) + type_entry->id == TypeTableEntryIdComptimeFloat) { is_int = false; is_float = true; @@ -11064,7 +11064,7 @@ static TypeTableEntry *ir_analyze_bit_shift(IrAnalyze *ira, IrInstructionBinOp * if (type_is_invalid(op1->value.type)) return ira->codegen->builtin_types.entry_invalid; - if (op1->value.type->id != TypeTableEntryIdInt && op1->value.type->id != TypeTableEntryIdNumLitInt) { + if (op1->value.type->id != TypeTableEntryIdInt && op1->value.type->id != TypeTableEntryIdComptimeInt) { ir_add_error(ira, &bin_op_instruction->base, buf_sprintf("bit shifting operation expected integer type, found '%s'", buf_ptr(&op1->value.type->name))); @@ -11077,7 +11077,7 @@ static TypeTableEntry *ir_analyze_bit_shift(IrAnalyze *ira, IrInstructionBinOp * IrInstruction *casted_op2; IrBinOp op_id = bin_op_instruction->op_id; - if (op1->value.type->id == TypeTableEntryIdNumLitInt) { + if (op1->value.type->id == TypeTableEntryIdComptimeInt) { casted_op2 = op2; if (op_id == IrBinOpBitShiftLeftLossy) { @@ -11122,7 +11122,7 @@ static TypeTableEntry *ir_analyze_bit_shift(IrAnalyze *ira, IrInstructionBinOp * ir_num_lit_fits_in_other_type(ira, result_instruction, op1->value.type, false); return op1->value.type; - } else if (op1->value.type->id == TypeTableEntryIdNumLitInt) { + } else if (op1->value.type->id == TypeTableEntryIdComptimeInt) { ir_add_error(ira, &bin_op_instruction->base, buf_sprintf("LHS of shift must be an integer type, or RHS must be compile-time known")); return ira->codegen->builtin_types.entry_invalid; @@ -11158,15 +11158,15 @@ static TypeTableEntry *ir_analyze_bin_op_math(IrAnalyze *ira, IrInstructionBinOp if (type_is_invalid(resolved_type)) return resolved_type; - bool is_int = resolved_type->id == TypeTableEntryIdInt || resolved_type->id == TypeTableEntryIdNumLitInt; - bool is_float = resolved_type->id == TypeTableEntryIdFloat || resolved_type->id == TypeTableEntryIdNumLitFloat; + bool is_int = resolved_type->id == TypeTableEntryIdInt || resolved_type->id == TypeTableEntryIdComptimeInt; + bool is_float = resolved_type->id == TypeTableEntryIdFloat || resolved_type->id == TypeTableEntryIdComptimeFloat; bool is_signed_div = ( (resolved_type->id == TypeTableEntryIdInt && resolved_type->data.integral.is_signed) || resolved_type->id == TypeTableEntryIdFloat || - (resolved_type->id == TypeTableEntryIdNumLitFloat && + (resolved_type->id == TypeTableEntryIdComptimeFloat && ((bigfloat_cmp_zero(&op1->value.data.x_bigfloat) != CmpGT) != (bigfloat_cmp_zero(&op2->value.data.x_bigfloat) != CmpGT))) || - (resolved_type->id == TypeTableEntryIdNumLitInt && + (resolved_type->id == TypeTableEntryIdComptimeInt && ((bigint_cmp_zero(&op1->value.data.x_bigint) != CmpGT) != (bigint_cmp_zero(&op2->value.data.x_bigint) != CmpGT))) ); @@ -11267,7 +11267,7 @@ static TypeTableEntry *ir_analyze_bin_op_math(IrAnalyze *ira, IrInstructionBinOp return ira->codegen->builtin_types.entry_invalid; } - if (resolved_type->id == TypeTableEntryIdNumLitInt) { + if (resolved_type->id == TypeTableEntryIdComptimeInt) { if (op_id == IrBinOpAddWrap) { op_id = IrBinOpAdd; } else if (op_id == IrBinOpSubWrap) { @@ -11641,8 +11641,8 @@ static VarClassRequired get_var_class_required(TypeTableEntry *type_entry) { case TypeTableEntryIdFn: case TypeTableEntryIdPromise: return VarClassRequiredAny; - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdBlock: case TypeTableEntryIdNullLit: @@ -11910,8 +11910,8 @@ static TypeTableEntry *ir_analyze_instruction_export(IrAnalyze *ira, IrInstructi case TypeTableEntryIdMetaType: case TypeTableEntryIdVoid: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -11934,8 +11934,8 @@ static TypeTableEntry *ir_analyze_instruction_export(IrAnalyze *ira, IrInstructi case TypeTableEntryIdFloat: case TypeTableEntryIdPointer: case TypeTableEntryIdArray: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -12149,7 +12149,7 @@ static bool ir_analyze_fn_call_generic_arg(IrAnalyze *ira, AstNode *fn_proto_nod } bool comptime_arg = param_decl_node->data.param_decl.is_inline || - casted_arg->value.type->id == TypeTableEntryIdNumLitInt || casted_arg->value.type->id == TypeTableEntryIdNumLitFloat; + casted_arg->value.type->id == TypeTableEntryIdComptimeInt || casted_arg->value.type->id == TypeTableEntryIdComptimeFloat; ConstExprValue *arg_val; @@ -12174,8 +12174,8 @@ static bool ir_analyze_fn_call_generic_arg(IrAnalyze *ira, AstNode *fn_proto_nod var->shadowable = !comptime_arg; *next_proto_i += 1; - } else if (casted_arg->value.type->id == TypeTableEntryIdNumLitInt || - casted_arg->value.type->id == TypeTableEntryIdNumLitFloat) + } else if (casted_arg->value.type->id == TypeTableEntryIdComptimeInt || + casted_arg->value.type->id == TypeTableEntryIdComptimeFloat) { ir_add_error(ira, casted_arg, buf_sprintf("compiler bug: integer and float literals in var args function must be casted. https://github.com/ziglang/zig/issues/557")); @@ -12898,8 +12898,8 @@ static TypeTableEntry *ir_analyze_maybe(IrAnalyze *ira, IrInstructionUnOp *un_op case TypeTableEntryIdPointer: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -12935,10 +12935,10 @@ static TypeTableEntry *ir_analyze_negation(IrAnalyze *ira, IrInstructionUnOp *un bool is_wrap_op = (un_op_instruction->op_id == IrUnOpNegationWrap); - bool is_float = (expr_type->id == TypeTableEntryIdFloat || expr_type->id == TypeTableEntryIdNumLitFloat); + bool is_float = (expr_type->id == TypeTableEntryIdFloat || expr_type->id == TypeTableEntryIdComptimeFloat); if ((expr_type->id == TypeTableEntryIdInt && expr_type->data.integral.is_signed) || - expr_type->id == TypeTableEntryIdNumLitInt || (is_float && !is_wrap_op)) + expr_type->id == TypeTableEntryIdComptimeInt || (is_float && !is_wrap_op)) { if (instr_is_comptime(value)) { ConstExprValue *target_const_val = ir_resolve_const(ira, value, UndefBad); @@ -12954,7 +12954,7 @@ static TypeTableEntry *ir_analyze_negation(IrAnalyze *ira, IrInstructionUnOp *un } else { bigint_negate(&out_val->data.x_bigint, &target_const_val->data.x_bigint); } - if (is_wrap_op || is_float || expr_type->id == TypeTableEntryIdNumLitInt) { + if (is_wrap_op || is_float || expr_type->id == TypeTableEntryIdComptimeInt) { return expr_type; } @@ -13150,8 +13150,8 @@ static TypeTableEntry *ir_analyze_instruction_phi(IrAnalyze *ira, IrInstructionP if (type_is_invalid(resolved_type)) return resolved_type; - if (resolved_type->id == TypeTableEntryIdNumLitFloat || - resolved_type->id == TypeTableEntryIdNumLitInt || + if (resolved_type->id == TypeTableEntryIdComptimeFloat || + resolved_type->id == TypeTableEntryIdComptimeInt || resolved_type->id == TypeTableEntryIdNullLit || resolved_type->id == TypeTableEntryIdUndefLit) { @@ -14213,8 +14213,8 @@ static TypeTableEntry *ir_analyze_instruction_typeof(IrAnalyze *ira, IrInstructi switch (type_entry->id) { case TypeTableEntryIdInvalid: zig_unreachable(); // handled above - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdNamespace: @@ -14495,8 +14495,8 @@ static TypeTableEntry *ir_analyze_instruction_slice_type(IrAnalyze *ira, case TypeTableEntryIdPointer: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdMaybe: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: @@ -14603,8 +14603,8 @@ static TypeTableEntry *ir_analyze_instruction_array_type(IrAnalyze *ira, case TypeTableEntryIdPointer: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdMaybe: case TypeTableEntryIdErrorUnion: case TypeTableEntryIdErrorSet: @@ -14659,8 +14659,8 @@ static TypeTableEntry *ir_analyze_instruction_size_of(IrAnalyze *ira, case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdBlock: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdBoundFn: case TypeTableEntryIdMetaType: case TypeTableEntryIdNamespace: @@ -15020,8 +15020,8 @@ static TypeTableEntry *ir_analyze_instruction_switch_target(IrAnalyze *ira, case TypeTableEntryIdBool: case TypeTableEntryIdInt: case TypeTableEntryIdFloat: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdPointer: case TypeTableEntryIdPromise: case TypeTableEntryIdFn: @@ -15618,8 +15618,8 @@ static TypeTableEntry *ir_analyze_min_max(IrAnalyze *ira, IrInstruction *source_ case TypeTableEntryIdPromise: case TypeTableEntryIdArray: case TypeTableEntryIdStruct: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdMaybe: @@ -16280,8 +16280,8 @@ static ConstExprValue *ir_make_type_info_value(IrAnalyze *ira, TypeTableEntry *t case TypeTableEntryIdVoid: case TypeTableEntryIdBool: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdNamespace: @@ -17143,7 +17143,7 @@ static TypeTableEntry *ir_analyze_instruction_truncate(IrAnalyze *ira, IrInstruc return ira->codegen->builtin_types.entry_invalid; if (dest_type->id != TypeTableEntryIdInt && - dest_type->id != TypeTableEntryIdNumLitInt) + dest_type->id != TypeTableEntryIdComptimeInt) { ir_add_error(ira, dest_type_value, buf_sprintf("expected integer type, found '%s'", buf_ptr(&dest_type->name))); return ira->codegen->builtin_types.entry_invalid; @@ -17155,7 +17155,7 @@ static TypeTableEntry *ir_analyze_instruction_truncate(IrAnalyze *ira, IrInstruc return ira->codegen->builtin_types.entry_invalid; if (src_type->id != TypeTableEntryIdInt && - src_type->id != TypeTableEntryIdNumLitInt) + src_type->id != TypeTableEntryIdComptimeInt) { ir_add_error(ira, target, buf_sprintf("expected integer type, found '%s'", buf_ptr(&src_type->name))); return ira->codegen->builtin_types.entry_invalid; @@ -17876,8 +17876,8 @@ static TypeTableEntry *ir_analyze_instruction_align_of(IrAnalyze *ira, IrInstruc zig_unreachable(); case TypeTableEntryIdMetaType: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdNamespace: @@ -18377,8 +18377,8 @@ static TypeTableEntry *ir_analyze_instruction_check_switch_prongs(IrAnalyze *ira if (!end_val) return ira->codegen->builtin_types.entry_invalid; - assert(start_val->type->id == TypeTableEntryIdInt || start_val->type->id == TypeTableEntryIdNumLitInt); - assert(end_val->type->id == TypeTableEntryIdInt || end_val->type->id == TypeTableEntryIdNumLitInt); + assert(start_val->type->id == TypeTableEntryIdInt || start_val->type->id == TypeTableEntryIdComptimeInt); + assert(end_val->type->id == TypeTableEntryIdInt || end_val->type->id == TypeTableEntryIdComptimeInt); AstNode *prev_node = rangeset_add_range(&rs, &start_val->data.x_bigint, &end_val->data.x_bigint, start_value->source_node); if (prev_node != nullptr) { @@ -18610,8 +18610,8 @@ static void buf_write_value_bytes(CodeGen *codegen, uint8_t *buf, ConstExprValue case TypeTableEntryIdNamespace: case TypeTableEntryIdBlock: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdPromise: @@ -18677,8 +18677,8 @@ static void buf_read_value_bytes(CodeGen *codegen, uint8_t *buf, ConstExprValue case TypeTableEntryIdNamespace: case TypeTableEntryIdBlock: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: case TypeTableEntryIdPromise: @@ -18758,8 +18758,8 @@ static TypeTableEntry *ir_analyze_instruction_bit_cast(IrAnalyze *ira, IrInstruc case TypeTableEntryIdNamespace: case TypeTableEntryIdBlock: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: ir_add_error(ira, dest_type_value, @@ -18784,8 +18784,8 @@ static TypeTableEntry *ir_analyze_instruction_bit_cast(IrAnalyze *ira, IrInstruc case TypeTableEntryIdNamespace: case TypeTableEntryIdBlock: case TypeTableEntryIdUnreachable: - case TypeTableEntryIdNumLitFloat: - case TypeTableEntryIdNumLitInt: + case TypeTableEntryIdComptimeFloat: + case TypeTableEntryIdComptimeInt: case TypeTableEntryIdUndefLit: case TypeTableEntryIdNullLit: ir_add_error(ira, dest_type_value, @@ -19560,7 +19560,7 @@ static TypeTableEntry *ir_analyze_instruction_sqrt(IrAnalyze *ira, IrInstruction if (type_is_invalid(op->value.type)) return ira->codegen->builtin_types.entry_invalid; - bool ok_type = float_type->id == TypeTableEntryIdNumLitFloat || float_type->id == TypeTableEntryIdFloat; + bool ok_type = float_type->id == TypeTableEntryIdComptimeFloat || float_type->id == TypeTableEntryIdFloat; if (!ok_type) { ir_add_error(ira, instruction->type, buf_sprintf("@sqrt does not support type '%s'", buf_ptr(&float_type->name))); return ira->codegen->builtin_types.entry_invalid; @@ -19577,7 +19577,7 @@ static TypeTableEntry *ir_analyze_instruction_sqrt(IrAnalyze *ira, IrInstruction ConstExprValue *out_val = ir_build_const_from(ira, &instruction->base); - if (float_type->id == TypeTableEntryIdNumLitFloat) { + if (float_type->id == TypeTableEntryIdComptimeFloat) { bigfloat_sqrt(&out_val->data.x_bigfloat, &val->data.x_bigfloat); } else if (float_type->id == TypeTableEntryIdFloat) { switch (float_type->data.floating.bit_count) { diff --git a/std/math/ln.zig b/std/math/ln.zig index 263e5955cb..3fd75977b9 100644 --- a/std/math/ln.zig +++ b/std/math/ln.zig @@ -14,7 +14,7 @@ const TypeId = builtin.TypeId; pub fn ln(x: var) @typeOf(x) { const T = @typeOf(x); switch (@typeId(T)) { - TypeId.FloatLiteral => { + TypeId.ComptimeFloat => { return @typeOf(1.0)(ln_64(x)); }, TypeId.Float => { @@ -24,7 +24,7 @@ pub fn ln(x: var) @typeOf(x) { else => @compileError("ln not implemented for " ++ @typeName(T)), }; }, - TypeId.IntLiteral => { + TypeId.ComptimeInt => { return @typeOf(1)(math.floor(ln_64(f64(x)))); }, TypeId.Int => { diff --git a/std/math/log.zig b/std/math/log.zig index 1cba1138db..2c876081d8 100644 --- a/std/math/log.zig +++ b/std/math/log.zig @@ -9,15 +9,15 @@ pub fn log(comptime T: type, base: T, x: T) T { return math.log2(x); } else if (base == 10) { return math.log10(x); - } else if ((@typeId(T) == TypeId.Float or @typeId(T) == TypeId.FloatLiteral) and base == math.e) { + } else if ((@typeId(T) == TypeId.Float or @typeId(T) == TypeId.ComptimeFloat) and base == math.e) { return math.ln(x); } switch (@typeId(T)) { - TypeId.FloatLiteral => { + TypeId.ComptimeFloat => { return @typeOf(1.0)(math.ln(f64(x)) / math.ln(f64(base))); }, - TypeId.IntLiteral => { + TypeId.ComptimeInt => { return @typeOf(1)(math.floor(math.ln(f64(x)) / math.ln(f64(base)))); }, builtin.TypeId.Int => { diff --git a/std/math/log10.zig b/std/math/log10.zig index d9fa1dcb02..c444add9ac 100644 --- a/std/math/log10.zig +++ b/std/math/log10.zig @@ -14,7 +14,7 @@ const TypeId = builtin.TypeId; pub fn log10(x: var) @typeOf(x) { const T = @typeOf(x); switch (@typeId(T)) { - TypeId.FloatLiteral => { + TypeId.ComptimeFloat => { return @typeOf(1.0)(log10_64(x)); }, TypeId.Float => { @@ -24,7 +24,7 @@ pub fn log10(x: var) @typeOf(x) { else => @compileError("log10 not implemented for " ++ @typeName(T)), }; }, - TypeId.IntLiteral => { + TypeId.ComptimeInt => { return @typeOf(1)(math.floor(log10_64(f64(x)))); }, TypeId.Int => { diff --git a/std/math/log2.zig b/std/math/log2.zig index 22cc8082b3..2530519941 100644 --- a/std/math/log2.zig +++ b/std/math/log2.zig @@ -14,7 +14,7 @@ const TypeId = builtin.TypeId; pub fn log2(x: var) @typeOf(x) { const T = @typeOf(x); switch (@typeId(T)) { - TypeId.FloatLiteral => { + TypeId.ComptimeFloat => { return @typeOf(1.0)(log2_64(x)); }, TypeId.Float => { @@ -24,7 +24,7 @@ pub fn log2(x: var) @typeOf(x) { else => @compileError("log2 not implemented for " ++ @typeName(T)), }; }, - TypeId.IntLiteral => comptime { + TypeId.ComptimeInt => comptime { var result = 0; var x_shifted = x; while (b: { diff --git a/std/math/sqrt.zig b/std/math/sqrt.zig index 982bd28b72..7a3ddb3b96 100644 --- a/std/math/sqrt.zig +++ b/std/math/sqrt.zig @@ -14,9 +14,9 @@ const TypeId = builtin.TypeId; pub fn sqrt(x: var) (if (@typeId(@typeOf(x)) == TypeId.Int) @IntType(false, @typeOf(x).bit_count / 2) else @typeOf(x)) { const T = @typeOf(x); switch (@typeId(T)) { - TypeId.FloatLiteral => return T(@sqrt(f64, x)), // TODO upgrade to f128 + TypeId.ComptimeFloat => return T(@sqrt(f64, x)), // TODO upgrade to f128 TypeId.Float => return @sqrt(T, x), - TypeId.IntLiteral => comptime { + TypeId.ComptimeInt => comptime { if (x > @maxValue(u128)) { @compileError("sqrt not implemented for comptime_int greater than 128 bits"); } diff --git a/test/cases/math.zig b/test/cases/math.zig index 0c18293dd5..0bf99cff0e 100644 --- a/test/cases/math.zig +++ b/test/cases/math.zig @@ -329,14 +329,14 @@ fn testShrExact(x: u8) void { assert(shifted == 0b00101101); } -test "big number addition" { +test "comptime_int addition" { comptime { assert(35361831660712422535336160538497375248 + 101752735581729509668353361206450473702 == 137114567242441932203689521744947848950); assert(594491908217841670578297176641415611445982232488944558774612 + 390603545391089362063884922208143568023166603618446395589768 == 985095453608931032642182098849559179469148836107390954364380); } } -test "big number multiplication" { +test "comptime_int multiplication" { comptime { assert( 45960427431263824329884196484953148229 * 128339149605334697009938835852565949723 == 5898522172026096622534201617172456926982464453350084962781392314016180490567, @@ -347,13 +347,13 @@ test "big number multiplication" { } } -test "big number shifting" { +test "comptime_int shifting" { comptime { assert((u128(1) << 127) == 0x80000000000000000000000000000000); } } -test "big number multi-limb shift and mask" { +test "comptime_int multi-limb shift and mask" { comptime { var a = 0xefffffffa0000001eeeeeeefaaaaaaab; @@ -370,7 +370,7 @@ test "big number multi-limb shift and mask" { } } -test "big number multi-limb partial shift right" { +test "comptime_int multi-limb partial shift right" { comptime { var a = 0x1ffffffffeeeeeeee; a >>= 16; @@ -391,7 +391,7 @@ fn test_xor() void { assert(0xFF ^ 0xFF == 0x00); } -test "big number xor" { +test "comptime_int xor" { comptime { assert(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ^ 0x00000000000000000000000000000000 == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); assert(0xFFFFFFFFFFFFFFFF0000000000000000 ^ 0x0000000000000000FFFFFFFFFFFFFFFF == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); @@ -449,3 +449,15 @@ test "@sqrt" { fn testSqrt(comptime T: type, x: T) void { assert(@sqrt(T, x * x) == x); } + +test "comptime_int param and return" { + const a = comptimeAdd(35361831660712422535336160538497375248, 101752735581729509668353361206450473702); + assert(a == 137114567242441932203689521744947848950); + + const b = comptimeAdd(594491908217841670578297176641415611445982232488944558774612, 390603545391089362063884922208143568023166603618446395589768); + assert(b == 985095453608931032642182098849559179469148836107390954364380); +} + +fn comptimeAdd(comptime a: comptime_int, comptime b: comptime_int) comptime_int { + return a + b; +} diff --git a/test/cases/misc.zig b/test/cases/misc.zig index e007ec4c46..1821e29a20 100644 --- a/test/cases/misc.zig +++ b/test/cases/misc.zig @@ -501,8 +501,8 @@ test "@typeId" { assert(@typeId(*f32) == Tid.Pointer); assert(@typeId([2]u8) == Tid.Array); assert(@typeId(AStruct) == Tid.Struct); - assert(@typeId(@typeOf(1)) == Tid.IntLiteral); - assert(@typeId(@typeOf(1.0)) == Tid.FloatLiteral); + assert(@typeId(@typeOf(1)) == Tid.ComptimeInt); + assert(@typeId(@typeOf(1.0)) == Tid.ComptimeFloat); assert(@typeId(@typeOf(undefined)) == Tid.UndefinedLiteral); assert(@typeId(@typeOf(null)) == Tid.NullLiteral); assert(@typeId(?i32) == Tid.Nullable); diff --git a/test/compile_errors.zig b/test/compile_errors.zig index 17136e150f..e264d57b5e 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1539,7 +1539,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\fn foo() *const i32 { return y; } \\export fn entry() usize { return @sizeOf(@typeOf(foo)); } , - ".tmp_source.zig:3:30: error: expected type '*const i32', found '*const (integer literal)'", + ".tmp_source.zig:3:30: error: expected type '*const i32', found '*const comptime_int'", ); cases.add( @@ -1555,7 +1555,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\const x = 2 == 2.0; \\export fn entry() usize { return @sizeOf(@typeOf(x)); } , - ".tmp_source.zig:1:11: error: integer value 2 cannot be implicitly casted to type '(float literal)'", + ".tmp_source.zig:1:11: error: integer value 2 cannot be implicitly casted to type 'comptime_float'", ); cases.add( @@ -2189,7 +2189,7 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\ \\export fn entry() usize { return @sizeOf(@typeOf(block_aligned_stuff)); } , - ".tmp_source.zig:3:60: error: unable to perform binary not operation on type '(integer literal)'", + ".tmp_source.zig:3:60: error: unable to perform binary not operation on type 'comptime_int'", ); cases.addCase(x: { @@ -3269,10 +3269,10 @@ pub fn addCases(cases: *tests.CompileErrorContext) void { \\ fn bar(self: *const Foo) void {} \\}; , - ".tmp_source.zig:4:4: error: variable of type '*(integer literal)' must be const or comptime", + ".tmp_source.zig:4:4: error: variable of type '*comptime_int' must be const or comptime", ".tmp_source.zig:7:4: error: variable of type '(undefined)' must be const or comptime", - ".tmp_source.zig:8:4: error: variable of type '(integer literal)' must be const or comptime", - ".tmp_source.zig:9:4: error: variable of type '(float literal)' must be const or comptime", + ".tmp_source.zig:8:4: error: variable of type 'comptime_int' must be const or comptime", + ".tmp_source.zig:9:4: error: variable of type 'comptime_float' must be const or comptime", ".tmp_source.zig:10:4: error: variable of type '(block)' must be const or comptime", ".tmp_source.zig:11:4: error: variable of type '(null)' must be const or comptime", ".tmp_source.zig:12:4: error: variable of type 'Opaque' must be const or comptime", -- cgit v1.2.3 From 79120612267f55901029dd57290ee90c0a3ec987 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sun, 17 Jun 2018 02:57:07 -0400 Subject: remove integer and float casting syntax * add `@intCast` * add `@floatCast` * add `@floatToInt` * add `@intToFloat` See #1061 --- doc/langref.html.in | 12 +- src/all_types.hpp | 36 +++++ src/codegen.cpp | 8 + src/ir.cpp | 290 +++++++++++++++++++++++++++++++++--- src/ir_print.cpp | 44 ++++++ src/main.cpp | 2 +- std/array_list.zig | 8 +- std/base64.zig | 4 +- std/crypto/blake2.zig | 10 +- std/crypto/md5.zig | 6 +- std/crypto/sha1.zig | 6 +- std/crypto/sha2.zig | 12 +- std/debug/index.zig | 8 +- std/fmt/errol/index.zig | 78 +++++----- std/fmt/index.zig | 19 +-- std/hash/crc.zig | 4 +- std/hash/siphash.zig | 6 +- std/heap.zig | 2 +- std/json.zig | 2 +- std/math/acos.zig | 4 +- std/math/asin.zig | 4 +- std/math/atan.zig | 4 +- std/math/atan2.zig | 8 +- std/math/atanh.zig | 2 +- std/math/big/int.zig | 22 +-- std/math/cbrt.zig | 6 +- std/math/ceil.zig | 4 +- std/math/complex/atan.zig | 10 +- std/math/complex/cosh.zig | 4 +- std/math/complex/exp.zig | 6 +- std/math/complex/ldexp.zig | 13 +- std/math/complex/sinh.zig | 10 +- std/math/complex/sqrt.zig | 10 +- std/math/complex/tanh.zig | 10 +- std/math/cos.zig | 4 +- std/math/cosh.zig | 2 +- std/math/exp.zig | 12 +- std/math/exp2.zig | 14 +- std/math/expm1.zig | 20 +-- std/math/floor.zig | 4 +- std/math/fma.zig | 6 +- std/math/frexp.zig | 4 +- std/math/hypot.zig | 2 +- std/math/ilogb.zig | 4 +- std/math/index.zig | 25 +++- std/math/ln.zig | 12 +- std/math/log.zig | 11 +- std/math/log10.zig | 14 +- std/math/log1p.zig | 12 +- std/math/log2.zig | 12 +- std/math/modf.zig | 8 +- std/math/pow.zig | 4 +- std/math/scalbn.zig | 4 +- std/math/sin.zig | 4 +- std/math/sinh.zig | 2 +- std/math/sqrt.zig | 2 +- std/math/tan.zig | 4 +- std/math/tanh.zig | 4 +- std/math/trunc.zig | 8 +- std/mem.zig | 2 +- std/os/child_process.zig | 2 +- std/os/darwin.zig | 11 +- std/os/file.zig | 6 +- std/os/index.zig | 16 +- std/os/linux/index.zig | 80 +++++----- std/os/linux/test.zig | 6 +- std/os/linux/vdso.zig | 4 +- std/os/time.zig | 24 +-- std/os/windows/util.zig | 9 +- std/rand/index.zig | 16 +- std/segmented_list.zig | 12 +- std/special/bootstrap.zig | 2 +- std/special/builtin.zig | 30 ++-- std/special/compiler_rt/divti3.zig | 2 +- std/special/compiler_rt/fixuint.zig | 8 +- std/special/compiler_rt/index.zig | 12 +- std/special/compiler_rt/udivmod.zig | 34 ++--- std/unicode.zig | 20 +-- std/zig/tokenizer.zig | 2 +- test/cases/cast.zig | 18 ++- test/cases/enum.zig | 2 +- test/cases/eval.zig | 8 +- test/cases/fn.zig | 2 +- test/cases/for.zig | 4 +- test/cases/struct.zig | 8 +- 85 files changed, 799 insertions(+), 413 deletions(-) (limited to 'std/math/log2.zig') diff --git a/doc/langref.html.in b/doc/langref.html.in index 651629d8fb..35ca9a13b4 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -1355,7 +1355,7 @@ var some_integers: [100]i32 = undefined; test "modify an array" { for (some_integers) |*item, i| { - item.* = i32(i); + item.* = @intCast(i32, i); } assert(some_integers[10] == 10); assert(some_integers[99] == 99); @@ -1397,8 +1397,8 @@ var fancy_array = init: { var initial_value: [10]Point = undefined; for (initial_value) |*pt, i| { pt.* = Point{ - .x = i32(i), - .y = i32(i) * 2, + .x = @intCast(i32, i), + .y = @intCast(i32, i) * 2, }; } break :init initial_value; @@ -2410,7 +2410,7 @@ test "for basics" { var sum2: i32 = 0; for (items) |value, i| { assert(@typeOf(i) == usize); - sum2 += i32(i); + sum2 += @intCast(i32, i); } assert(sum2 == 10); } @@ -5730,7 +5730,7 @@ comptime { {#code_begin|test_err|attempt to cast negative value to unsigned integer#} comptime { const value: i32 = -1; - const unsigned = u32(value); + const unsigned = @intCast(u32, value); } {#code_end#}

At runtime crashes with the message attempt to cast negative value to unsigned integer and a stack trace.

@@ -5744,7 +5744,7 @@ comptime { {#code_begin|test_err|cast from 'u16' to 'u8' truncates bits#} comptime { const spartan_count: u16 = 300; - const byte = u8(spartan_count); + const byte = @intCast(u8, spartan_count); } {#code_end#}

At runtime crashes with the message integer cast truncated bits and a stack trace.

diff --git a/src/all_types.hpp b/src/all_types.hpp index 0d364915f9..bc2fe07c18 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -1357,6 +1357,10 @@ enum BuiltinFnId { BuiltinFnIdMod, BuiltinFnIdSqrt, BuiltinFnIdTruncate, + BuiltinFnIdIntCast, + BuiltinFnIdFloatCast, + BuiltinFnIdIntToFloat, + BuiltinFnIdFloatToInt, BuiltinFnIdIntType, BuiltinFnIdSetCold, BuiltinFnIdSetRuntimeSafety, @@ -2040,6 +2044,10 @@ enum IrInstructionId { IrInstructionIdCmpxchg, IrInstructionIdFence, IrInstructionIdTruncate, + IrInstructionIdIntCast, + IrInstructionIdFloatCast, + IrInstructionIdIntToFloat, + IrInstructionIdFloatToInt, IrInstructionIdIntType, IrInstructionIdBoolNot, IrInstructionIdMemset, @@ -2632,6 +2640,34 @@ struct IrInstructionTruncate { IrInstruction *target; }; +struct IrInstructionIntCast { + IrInstruction base; + + IrInstruction *dest_type; + IrInstruction *target; +}; + +struct IrInstructionFloatCast { + IrInstruction base; + + IrInstruction *dest_type; + IrInstruction *target; +}; + +struct IrInstructionIntToFloat { + IrInstruction base; + + IrInstruction *dest_type; + IrInstruction *target; +}; + +struct IrInstructionFloatToInt { + IrInstruction base; + + IrInstruction *dest_type; + IrInstruction *target; +}; + struct IrInstructionIntType { IrInstruction base; diff --git a/src/codegen.cpp b/src/codegen.cpp index 425cdac024..4108cbbd68 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -4722,6 +4722,10 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, case IrInstructionIdPromiseResultType: case IrInstructionIdAwaitBookkeeping: case IrInstructionIdAddImplicitReturnType: + case IrInstructionIdIntCast: + case IrInstructionIdFloatCast: + case IrInstructionIdIntToFloat: + case IrInstructionIdFloatToInt: zig_unreachable(); case IrInstructionIdReturn: @@ -6310,6 +6314,10 @@ static void define_builtin_fns(CodeGen *g) { create_builtin_fn(g, BuiltinFnIdCmpxchgStrong, "cmpxchgStrong", 6); create_builtin_fn(g, BuiltinFnIdFence, "fence", 1); create_builtin_fn(g, BuiltinFnIdTruncate, "truncate", 2); + create_builtin_fn(g, BuiltinFnIdIntCast, "intCast", 2); + create_builtin_fn(g, BuiltinFnIdFloatCast, "floatCast", 2); + create_builtin_fn(g, BuiltinFnIdIntToFloat, "intToFloat", 2); + create_builtin_fn(g, BuiltinFnIdFloatToInt, "floatToInt", 2); create_builtin_fn(g, BuiltinFnIdCompileErr, "compileError", 1); create_builtin_fn(g, BuiltinFnIdCompileLog, "compileLog", SIZE_MAX); create_builtin_fn(g, BuiltinFnIdIntType, "IntType", 2); // TODO rename to Int diff --git a/src/ir.cpp b/src/ir.cpp index d008ead113..0b847fc4e4 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -460,6 +460,22 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionTruncate *) { return IrInstructionIdTruncate; } +static constexpr IrInstructionId ir_instruction_id(IrInstructionIntCast *) { + return IrInstructionIdIntCast; +} + +static constexpr IrInstructionId ir_instruction_id(IrInstructionFloatCast *) { + return IrInstructionIdFloatCast; +} + +static constexpr IrInstructionId ir_instruction_id(IrInstructionIntToFloat *) { + return IrInstructionIdIntToFloat; +} + +static constexpr IrInstructionId ir_instruction_id(IrInstructionFloatToInt *) { + return IrInstructionIdFloatToInt; +} + static constexpr IrInstructionId ir_instruction_id(IrInstructionIntType *) { return IrInstructionIdIntType; } @@ -1899,10 +1915,48 @@ static IrInstruction *ir_build_truncate(IrBuilder *irb, Scope *scope, AstNode *s return &instruction->base; } -static IrInstruction *ir_build_truncate_from(IrBuilder *irb, IrInstruction *old_instruction, IrInstruction *dest_type, IrInstruction *target) { - IrInstruction *new_instruction = ir_build_truncate(irb, old_instruction->scope, old_instruction->source_node, dest_type, target); - ir_link_new_instruction(new_instruction, old_instruction); - return new_instruction; +static IrInstruction *ir_build_int_cast(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *dest_type, IrInstruction *target) { + IrInstructionIntCast *instruction = ir_build_instruction(irb, scope, source_node); + instruction->dest_type = dest_type; + instruction->target = target; + + ir_ref_instruction(dest_type, irb->current_basic_block); + ir_ref_instruction(target, irb->current_basic_block); + + return &instruction->base; +} + +static IrInstruction *ir_build_float_cast(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *dest_type, IrInstruction *target) { + IrInstructionFloatCast *instruction = ir_build_instruction(irb, scope, source_node); + instruction->dest_type = dest_type; + instruction->target = target; + + ir_ref_instruction(dest_type, irb->current_basic_block); + ir_ref_instruction(target, irb->current_basic_block); + + return &instruction->base; +} + +static IrInstruction *ir_build_int_to_float(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *dest_type, IrInstruction *target) { + IrInstructionIntToFloat *instruction = ir_build_instruction(irb, scope, source_node); + instruction->dest_type = dest_type; + instruction->target = target; + + ir_ref_instruction(dest_type, irb->current_basic_block); + ir_ref_instruction(target, irb->current_basic_block); + + return &instruction->base; +} + +static IrInstruction *ir_build_float_to_int(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *dest_type, IrInstruction *target) { + IrInstructionFloatToInt *instruction = ir_build_instruction(irb, scope, source_node); + instruction->dest_type = dest_type; + instruction->target = target; + + ir_ref_instruction(dest_type, irb->current_basic_block); + ir_ref_instruction(target, irb->current_basic_block); + + return &instruction->base; } static IrInstruction *ir_build_int_type(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *is_signed, IrInstruction *bit_count) { @@ -3957,6 +4011,66 @@ static IrInstruction *ir_gen_builtin_fn_call(IrBuilder *irb, Scope *scope, AstNo IrInstruction *truncate = ir_build_truncate(irb, scope, node, arg0_value, arg1_value); return ir_lval_wrap(irb, scope, truncate, lval); } + case BuiltinFnIdIntCast: + { + AstNode *arg0_node = node->data.fn_call_expr.params.at(0); + IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope); + if (arg0_value == irb->codegen->invalid_instruction) + return arg0_value; + + AstNode *arg1_node = node->data.fn_call_expr.params.at(1); + IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope); + if (arg1_value == irb->codegen->invalid_instruction) + return arg1_value; + + IrInstruction *result = ir_build_int_cast(irb, scope, node, arg0_value, arg1_value); + return ir_lval_wrap(irb, scope, result, lval); + } + case BuiltinFnIdFloatCast: + { + AstNode *arg0_node = node->data.fn_call_expr.params.at(0); + IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope); + if (arg0_value == irb->codegen->invalid_instruction) + return arg0_value; + + AstNode *arg1_node = node->data.fn_call_expr.params.at(1); + IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope); + if (arg1_value == irb->codegen->invalid_instruction) + return arg1_value; + + IrInstruction *result = ir_build_float_cast(irb, scope, node, arg0_value, arg1_value); + return ir_lval_wrap(irb, scope, result, lval); + } + case BuiltinFnIdIntToFloat: + { + AstNode *arg0_node = node->data.fn_call_expr.params.at(0); + IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope); + if (arg0_value == irb->codegen->invalid_instruction) + return arg0_value; + + AstNode *arg1_node = node->data.fn_call_expr.params.at(1); + IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope); + if (arg1_value == irb->codegen->invalid_instruction) + return arg1_value; + + IrInstruction *result = ir_build_int_to_float(irb, scope, node, arg0_value, arg1_value); + return ir_lval_wrap(irb, scope, result, lval); + } + case BuiltinFnIdFloatToInt: + { + AstNode *arg0_node = node->data.fn_call_expr.params.at(0); + IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope); + if (arg0_value == irb->codegen->invalid_instruction) + return arg0_value; + + AstNode *arg1_node = node->data.fn_call_expr.params.at(1); + IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope); + if (arg1_value == irb->codegen->invalid_instruction) + return arg1_value; + + IrInstruction *result = ir_build_float_to_int(irb, scope, node, arg0_value, arg1_value); + return ir_lval_wrap(irb, scope, result, lval); + } case BuiltinFnIdIntType: { AstNode *arg0_node = node->data.fn_call_expr.params.at(0); @@ -9948,34 +10062,37 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst return ir_resolve_cast(ira, source_instr, value, wanted_type, CastOpBoolToInt, false); } - // explicit widening or shortening cast - if ((wanted_type->id == TypeTableEntryIdInt && - actual_type->id == TypeTableEntryIdInt) || - (wanted_type->id == TypeTableEntryIdFloat && - actual_type->id == TypeTableEntryIdFloat)) + // explicit widening conversion + if (wanted_type->id == TypeTableEntryIdInt && + actual_type->id == TypeTableEntryIdInt && + wanted_type->data.integral.is_signed == actual_type->data.integral.is_signed && + wanted_type->data.integral.bit_count >= actual_type->data.integral.bit_count) { return ir_analyze_widen_or_shorten(ira, source_instr, value, wanted_type); } - // explicit error set cast - if (wanted_type->id == TypeTableEntryIdErrorSet && - actual_type->id == TypeTableEntryIdErrorSet) + // small enough unsigned ints can get casted to large enough signed ints + if (wanted_type->id == TypeTableEntryIdInt && wanted_type->data.integral.is_signed && + actual_type->id == TypeTableEntryIdInt && !actual_type->data.integral.is_signed && + wanted_type->data.integral.bit_count > actual_type->data.integral.bit_count) { - return ir_analyze_err_set_cast(ira, source_instr, value, wanted_type); + return ir_analyze_widen_or_shorten(ira, source_instr, value, wanted_type); } - // explicit cast from int to float + // explicit float widening conversion if (wanted_type->id == TypeTableEntryIdFloat && - actual_type->id == TypeTableEntryIdInt) + actual_type->id == TypeTableEntryIdFloat && + wanted_type->data.floating.bit_count >= actual_type->data.floating.bit_count) { - return ir_resolve_cast(ira, source_instr, value, wanted_type, CastOpIntToFloat, false); + return ir_analyze_widen_or_shorten(ira, source_instr, value, wanted_type); } - // explicit cast from float to int - if (wanted_type->id == TypeTableEntryIdInt && - actual_type->id == TypeTableEntryIdFloat) + + // explicit error set cast + if (wanted_type->id == TypeTableEntryIdErrorSet && + actual_type->id == TypeTableEntryIdErrorSet) { - return ir_resolve_cast(ira, source_instr, value, wanted_type, CastOpFloatToInt, false); + return ir_analyze_err_set_cast(ira, source_instr, value, wanted_type); } // explicit cast from [N]T to []const T @@ -17365,7 +17482,126 @@ static TypeTableEntry *ir_analyze_instruction_truncate(IrAnalyze *ira, IrInstruc return dest_type; } - ir_build_truncate_from(&ira->new_irb, &instruction->base, dest_type_value, target); + IrInstruction *new_instruction = ir_build_truncate(&ira->new_irb, instruction->base.scope, + instruction->base.source_node, dest_type_value, target); + ir_link_new_instruction(new_instruction, &instruction->base); + return dest_type; +} + +static TypeTableEntry *ir_analyze_instruction_int_cast(IrAnalyze *ira, IrInstructionIntCast *instruction) { + TypeTableEntry *dest_type = ir_resolve_type(ira, instruction->dest_type->other); + if (type_is_invalid(dest_type)) + return ira->codegen->builtin_types.entry_invalid; + + if (dest_type->id != TypeTableEntryIdInt) { + ir_add_error(ira, instruction->dest_type, buf_sprintf("expected integer type, found '%s'", buf_ptr(&dest_type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + + IrInstruction *target = instruction->target->other; + if (type_is_invalid(target->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + if (target->value.type->id == TypeTableEntryIdComptimeInt) { + if (ir_num_lit_fits_in_other_type(ira, target, dest_type, true)) { + IrInstruction *result = ir_resolve_cast(ira, &instruction->base, target, dest_type, + CastOpNumLitToConcrete, false); + if (type_is_invalid(result->value.type)) + return ira->codegen->builtin_types.entry_invalid; + ir_link_new_instruction(result, &instruction->base); + return dest_type; + } else { + return ira->codegen->builtin_types.entry_invalid; + } + } + + if (target->value.type->id != TypeTableEntryIdInt) { + ir_add_error(ira, instruction->target, buf_sprintf("expected integer type, found '%s'", + buf_ptr(&target->value.type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + + IrInstruction *result = ir_analyze_widen_or_shorten(ira, &instruction->base, target, dest_type); + if (type_is_invalid(result->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + ir_link_new_instruction(result, &instruction->base); + return dest_type; +} + +static TypeTableEntry *ir_analyze_instruction_float_cast(IrAnalyze *ira, IrInstructionFloatCast *instruction) { + TypeTableEntry *dest_type = ir_resolve_type(ira, instruction->dest_type->other); + if (type_is_invalid(dest_type)) + return ira->codegen->builtin_types.entry_invalid; + + if (dest_type->id != TypeTableEntryIdFloat) { + ir_add_error(ira, instruction->dest_type, + buf_sprintf("expected float type, found '%s'", buf_ptr(&dest_type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + + IrInstruction *target = instruction->target->other; + if (type_is_invalid(target->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + if (target->value.type->id == TypeTableEntryIdComptimeInt || + target->value.type->id == TypeTableEntryIdComptimeFloat) + { + if (ir_num_lit_fits_in_other_type(ira, target, dest_type, true)) { + CastOp op; + if (target->value.type->id == TypeTableEntryIdComptimeInt) { + op = CastOpIntToFloat; + } else { + op = CastOpNumLitToConcrete; + } + IrInstruction *result = ir_resolve_cast(ira, &instruction->base, target, dest_type, op, false); + if (type_is_invalid(result->value.type)) + return ira->codegen->builtin_types.entry_invalid; + ir_link_new_instruction(result, &instruction->base); + return dest_type; + } else { + return ira->codegen->builtin_types.entry_invalid; + } + } + + if (target->value.type->id != TypeTableEntryIdFloat) { + ir_add_error(ira, instruction->target, buf_sprintf("expected float type, found '%s'", + buf_ptr(&target->value.type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + + IrInstruction *result = ir_analyze_widen_or_shorten(ira, &instruction->base, target, dest_type); + if (type_is_invalid(result->value.type)) + return ira->codegen->builtin_types.entry_invalid; + ir_link_new_instruction(result, &instruction->base); + return dest_type; +} + +static TypeTableEntry *ir_analyze_instruction_int_to_float(IrAnalyze *ira, IrInstructionIntToFloat *instruction) { + TypeTableEntry *dest_type = ir_resolve_type(ira, instruction->dest_type->other); + if (type_is_invalid(dest_type)) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *target = instruction->target->other; + if (type_is_invalid(target->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *result = ir_resolve_cast(ira, &instruction->base, target, dest_type, CastOpIntToFloat, false); + ir_link_new_instruction(result, &instruction->base); + return dest_type; +} + +static TypeTableEntry *ir_analyze_instruction_float_to_int(IrAnalyze *ira, IrInstructionFloatToInt *instruction) { + TypeTableEntry *dest_type = ir_resolve_type(ira, instruction->dest_type->other); + if (type_is_invalid(dest_type)) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *target = instruction->target->other; + if (type_is_invalid(target->value.type)) + return ira->codegen->builtin_types.entry_invalid; + + IrInstruction *result = ir_resolve_cast(ira, &instruction->base, target, dest_type, CastOpFloatToInt, false); + ir_link_new_instruction(result, &instruction->base); return dest_type; } @@ -19899,6 +20135,14 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi return ir_analyze_instruction_fence(ira, (IrInstructionFence *)instruction); case IrInstructionIdTruncate: return ir_analyze_instruction_truncate(ira, (IrInstructionTruncate *)instruction); + case IrInstructionIdIntCast: + return ir_analyze_instruction_int_cast(ira, (IrInstructionIntCast *)instruction); + case IrInstructionIdFloatCast: + return ir_analyze_instruction_float_cast(ira, (IrInstructionFloatCast *)instruction); + case IrInstructionIdIntToFloat: + return ir_analyze_instruction_int_to_float(ira, (IrInstructionIntToFloat *)instruction); + case IrInstructionIdFloatToInt: + return ir_analyze_instruction_float_to_int(ira, (IrInstructionFloatToInt *)instruction); case IrInstructionIdIntType: return ir_analyze_instruction_int_type(ira, (IrInstructionIntType *)instruction); case IrInstructionIdBoolNot: @@ -20242,6 +20486,10 @@ bool ir_has_side_effects(IrInstruction *instruction) { case IrInstructionIdPromiseResultType: case IrInstructionIdSqrt: case IrInstructionIdAtomicLoad: + case IrInstructionIdIntCast: + case IrInstructionIdFloatCast: + case IrInstructionIdIntToFloat: + case IrInstructionIdFloatToInt: return false; case IrInstructionIdAsm: diff --git a/src/ir_print.cpp b/src/ir_print.cpp index 43907fa9d4..b5722c52fa 100644 --- a/src/ir_print.cpp +++ b/src/ir_print.cpp @@ -648,6 +648,38 @@ static void ir_print_truncate(IrPrint *irp, IrInstructionTruncate *instruction) fprintf(irp->f, ")"); } +static void ir_print_int_cast(IrPrint *irp, IrInstructionIntCast *instruction) { + fprintf(irp->f, "@intCast("); + ir_print_other_instruction(irp, instruction->dest_type); + fprintf(irp->f, ", "); + ir_print_other_instruction(irp, instruction->target); + fprintf(irp->f, ")"); +} + +static void ir_print_float_cast(IrPrint *irp, IrInstructionFloatCast *instruction) { + fprintf(irp->f, "@floatCast("); + ir_print_other_instruction(irp, instruction->dest_type); + fprintf(irp->f, ", "); + ir_print_other_instruction(irp, instruction->target); + fprintf(irp->f, ")"); +} + +static void ir_print_int_to_float(IrPrint *irp, IrInstructionIntToFloat *instruction) { + fprintf(irp->f, "@intToFloat("); + ir_print_other_instruction(irp, instruction->dest_type); + fprintf(irp->f, ", "); + ir_print_other_instruction(irp, instruction->target); + fprintf(irp->f, ")"); +} + +static void ir_print_float_to_int(IrPrint *irp, IrInstructionFloatToInt *instruction) { + fprintf(irp->f, "@floatToInt("); + ir_print_other_instruction(irp, instruction->dest_type); + fprintf(irp->f, ", "); + ir_print_other_instruction(irp, instruction->target); + fprintf(irp->f, ")"); +} + static void ir_print_int_type(IrPrint *irp, IrInstructionIntType *instruction) { fprintf(irp->f, "@IntType("); ir_print_other_instruction(irp, instruction->is_signed); @@ -1417,6 +1449,18 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) { case IrInstructionIdTruncate: ir_print_truncate(irp, (IrInstructionTruncate *)instruction); break; + case IrInstructionIdIntCast: + ir_print_int_cast(irp, (IrInstructionIntCast *)instruction); + break; + case IrInstructionIdFloatCast: + ir_print_float_cast(irp, (IrInstructionFloatCast *)instruction); + break; + case IrInstructionIdIntToFloat: + ir_print_int_to_float(irp, (IrInstructionIntToFloat *)instruction); + break; + case IrInstructionIdFloatToInt: + ir_print_float_to_int(irp, (IrInstructionFloatToInt *)instruction); + break; case IrInstructionIdIntType: ir_print_int_type(irp, (IrInstructionIntType *)instruction); break; diff --git a/src/main.cpp b/src/main.cpp index c63a143bff..0fe12bb0cb 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -34,7 +34,7 @@ static int usage(const char *arg0) { " --assembly [source] add assembly file to build\n" " --cache-dir [path] override the cache directory\n" " --color [auto|off|on] enable or disable colored error messages\n" - " --emit [filetype] emit a specific file format as compilation output\n" + " --emit [asm|bin|llvm-ir] emit a specific file format as compilation output\n" " --enable-timing-info print timing diagnostics\n" " --libc-include-dir [path] directory where libc stdlib.h resides\n" " --name [name] override output name\n" diff --git a/std/array_list.zig b/std/array_list.zig index fd1d5cbe26..b71f5be6ab 100644 --- a/std/array_list.zig +++ b/std/array_list.zig @@ -185,23 +185,23 @@ test "basic ArrayList test" { { var i: usize = 0; while (i < 10) : (i += 1) { - list.append(i32(i + 1)) catch unreachable; + list.append(@intCast(i32, i + 1)) catch unreachable; } } { var i: usize = 0; while (i < 10) : (i += 1) { - assert(list.items[i] == i32(i + 1)); + assert(list.items[i] == @intCast(i32, i + 1)); } } for (list.toSlice()) |v, i| { - assert(v == i32(i + 1)); + assert(v == @intCast(i32, i + 1)); } for (list.toSliceConst()) |v, i| { - assert(v == i32(i + 1)); + assert(v == @intCast(i32, i + 1)); } assert(list.pop() == 10); diff --git a/std/base64.zig b/std/base64.zig index d27bcbd201..45c8e22c7e 100644 --- a/std/base64.zig +++ b/std/base64.zig @@ -99,7 +99,7 @@ pub const Base64Decoder = struct { assert(!result.char_in_alphabet[c]); assert(c != pad_char); - result.char_to_index[c] = u8(i); + result.char_to_index[c] = @intCast(u8, i); result.char_in_alphabet[c] = true; } @@ -284,7 +284,7 @@ pub const Base64DecoderUnsafe = struct { }; for (alphabet_chars) |c, i| { assert(c != pad_char); - result.char_to_index[c] = u8(i); + result.char_to_index[c] = @intCast(u8, i); } return result; } diff --git a/std/crypto/blake2.zig b/std/crypto/blake2.zig index f0a9766c00..947133e4cf 100644 --- a/std/crypto/blake2.zig +++ b/std/crypto/blake2.zig @@ -79,7 +79,7 @@ fn Blake2s(comptime out_len: usize) type { mem.copy(u32, d.h[0..], iv[0..]); // No key plus default parameters - d.h[0] ^= 0x01010000 ^ u32(out_len >> 3); + d.h[0] ^= 0x01010000 ^ @intCast(u32, out_len >> 3); d.t = 0; d.buf_len = 0; } @@ -110,7 +110,7 @@ fn Blake2s(comptime out_len: usize) type { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); } pub fn final(d: *Self, out: []u8) void { @@ -144,7 +144,7 @@ fn Blake2s(comptime out_len: usize) type { } v[12] ^= @truncate(u32, d.t); - v[13] ^= u32(d.t >> 32); + v[13] ^= @intCast(u32, d.t >> 32); if (last) v[14] = ~v[14]; const rounds = comptime []RoundParam{ @@ -345,7 +345,7 @@ fn Blake2b(comptime out_len: usize) type { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); } pub fn final(d: *Self, out: []u8) void { @@ -377,7 +377,7 @@ fn Blake2b(comptime out_len: usize) type { } v[12] ^= @truncate(u64, d.t); - v[13] ^= u64(d.t >> 64); + v[13] ^= @intCast(u64, d.t >> 64); if (last) v[14] = ~v[14]; const rounds = comptime []RoundParam{ diff --git a/std/crypto/md5.zig b/std/crypto/md5.zig index c0d1732d37..23fe2313a0 100644 --- a/std/crypto/md5.zig +++ b/std/crypto/md5.zig @@ -78,7 +78,7 @@ pub const Md5 = struct { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); // Md5 uses the bottom 64-bits for length padding d.total_len +%= b.len; @@ -103,9 +103,9 @@ pub const Md5 = struct { // Append message length. var i: usize = 1; var len = d.total_len >> 5; - d.buf[56] = u8(d.total_len & 0x1f) << 3; + d.buf[56] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 8) : (i += 1) { - d.buf[56 + i] = u8(len & 0xff); + d.buf[56 + i] = @intCast(u8, len & 0xff); len >>= 8; } diff --git a/std/crypto/sha1.zig b/std/crypto/sha1.zig index 9e46fc9239..5c91590c88 100644 --- a/std/crypto/sha1.zig +++ b/std/crypto/sha1.zig @@ -78,7 +78,7 @@ pub const Sha1 = struct { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); d.total_len += b.len; } @@ -102,9 +102,9 @@ pub const Sha1 = struct { // Append message length. var i: usize = 1; var len = d.total_len >> 5; - d.buf[63] = u8(d.total_len & 0x1f) << 3; + d.buf[63] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 8) : (i += 1) { - d.buf[63 - i] = u8(len & 0xff); + d.buf[63 - i] = @intCast(u8, len & 0xff); len >>= 8; } diff --git a/std/crypto/sha2.zig b/std/crypto/sha2.zig index d1375d73e8..d1b915835c 100644 --- a/std/crypto/sha2.zig +++ b/std/crypto/sha2.zig @@ -131,7 +131,7 @@ fn Sha2_32(comptime params: Sha2Params32) type { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); d.total_len += b.len; } @@ -155,9 +155,9 @@ fn Sha2_32(comptime params: Sha2Params32) type { // Append message length. var i: usize = 1; var len = d.total_len >> 5; - d.buf[63] = u8(d.total_len & 0x1f) << 3; + d.buf[63] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 8) : (i += 1) { - d.buf[63 - i] = u8(len & 0xff); + d.buf[63 - i] = @intCast(u8, len & 0xff); len >>= 8; } @@ -472,7 +472,7 @@ fn Sha2_64(comptime params: Sha2Params64) type { // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); d.total_len += b.len; } @@ -496,9 +496,9 @@ fn Sha2_64(comptime params: Sha2Params64) type { // Append message length. var i: usize = 1; var len = d.total_len >> 5; - d.buf[127] = u8(d.total_len & 0x1f) << 3; + d.buf[127] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 16) : (i += 1) { - d.buf[127 - i] = u8(len & 0xff); + d.buf[127 - i] = @intCast(u8, len & 0xff); len >>= 8; } diff --git a/std/debug/index.zig b/std/debug/index.zig index fb1dac537c..198e0f90f6 100644 --- a/std/debug/index.zig +++ b/std/debug/index.zig @@ -554,7 +554,7 @@ const LineNumberProgram = struct { const file_name = try os.path.join(self.file_entries.allocator, dir_name, file_entry.file_name); errdefer self.file_entries.allocator.free(file_name); return LineInfo{ - .line = if (self.prev_line >= 0) usize(self.prev_line) else 0, + .line = if (self.prev_line >= 0) @intCast(usize, self.prev_line) else 0, .column = self.prev_column, .file_name = file_name, .allocator = self.file_entries.allocator, @@ -1070,7 +1070,7 @@ fn readULeb128(in_stream: var) !u64 { var operand: u64 = undefined; - if (@shlWithOverflow(u64, byte & 0b01111111, u6(shift), &operand)) return error.InvalidDebugInfo; + if (@shlWithOverflow(u64, byte & 0b01111111, @intCast(u6, shift), &operand)) return error.InvalidDebugInfo; result |= operand; @@ -1089,13 +1089,13 @@ fn readILeb128(in_stream: var) !i64 { var operand: i64 = undefined; - if (@shlWithOverflow(i64, byte & 0b01111111, u6(shift), &operand)) return error.InvalidDebugInfo; + if (@shlWithOverflow(i64, byte & 0b01111111, @intCast(u6, shift), &operand)) return error.InvalidDebugInfo; result |= operand; shift += 7; if ((byte & 0b10000000) == 0) { - if (shift < @sizeOf(i64) * 8 and (byte & 0b01000000) != 0) result |= -(i64(1) << u6(shift)); + if (shift < @sizeOf(i64) * 8 and (byte & 0b01000000) != 0) result |= -(i64(1) << @intCast(u6, shift)); return result; } } diff --git a/std/fmt/errol/index.zig b/std/fmt/errol/index.zig index a906b714ab..a5fb692857 100644 --- a/std/fmt/errol/index.zig +++ b/std/fmt/errol/index.zig @@ -29,11 +29,11 @@ pub fn roundToPrecision(float_decimal: *FloatDecimal, precision: usize, mode: Ro switch (mode) { RoundMode.Decimal => { if (float_decimal.exp >= 0) { - round_digit = precision + usize(float_decimal.exp); + round_digit = precision + @intCast(usize, float_decimal.exp); } else { // if a small negative exp, then adjust we need to offset by the number // of leading zeros that will occur. - const min_exp_required = usize(-float_decimal.exp); + const min_exp_required = @intCast(usize, -float_decimal.exp); if (precision > min_exp_required) { round_digit = precision - min_exp_required; } @@ -107,16 +107,16 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal { // normalize the midpoint const e = math.frexp(val).exponent; - var exp = i16(math.floor(307 + f64(e) * 0.30103)); + var exp = @floatToInt(i16, math.floor(307 + @intToFloat(f64, e) * 0.30103)); if (exp < 20) { exp = 20; - } else if (usize(exp) >= lookup_table.len) { - exp = i16(lookup_table.len - 1); + } else if (@intCast(usize, exp) >= lookup_table.len) { + exp = @intCast(i16, lookup_table.len - 1); } - var mid = lookup_table[usize(exp)]; + var mid = lookup_table[@intCast(usize, exp)]; mid = hpProd(mid, val); - const lten = lookup_table[usize(exp)].val; + const lten = lookup_table[@intCast(usize, exp)].val; exp -= 307; @@ -168,25 +168,25 @@ fn errol3u(val: f64, buffer: []u8) FloatDecimal { // the 0-index for this extra digit. var buf_index: usize = 1; while (true) { - var hdig = u8(math.floor(high.val)); - if ((high.val == f64(hdig)) and (high.off < 0)) hdig -= 1; + var hdig = @floatToInt(u8, math.floor(high.val)); + if ((high.val == @intToFloat(f64, hdig)) and (high.off < 0)) hdig -= 1; - var ldig = u8(math.floor(low.val)); - if ((low.val == f64(ldig)) and (low.off < 0)) ldig -= 1; + var ldig = @floatToInt(u8, math.floor(low.val)); + if ((low.val == @intToFloat(f64, ldig)) and (low.off < 0)) ldig -= 1; if (ldig != hdig) break; buffer[buf_index] = hdig + '0'; buf_index += 1; - high.val -= f64(hdig); - low.val -= f64(ldig); + high.val -= @intToFloat(f64, hdig); + low.val -= @intToFloat(f64, ldig); hpMul10(&high); hpMul10(&low); } const tmp = (high.val + low.val) / 2.0; - var mdig = u8(math.floor(tmp + 0.5)); - if ((f64(mdig) - tmp) == 0.5 and (mdig & 0x1) != 0) mdig -= 1; + var mdig = @floatToInt(u8, math.floor(tmp + 0.5)); + if ((@intToFloat(f64, mdig) - tmp) == 0.5 and (mdig & 0x1) != 0) mdig -= 1; buffer[buf_index] = mdig + '0'; buf_index += 1; @@ -304,7 +304,7 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { assert((val > 9.007199254740992e15) and val < (3.40282366920938e38)); - var mid = u128(val); + var mid = @floatToInt(u128, val); var low: u128 = mid - fpeint((fpnext(val) - val) / 2.0); var high: u128 = mid + fpeint((val - fpprev(val)) / 2.0); @@ -314,11 +314,11 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { low -= 1; } - var l64 = u64(low % pow19); - const lf = u64((low / pow19) % pow19); + var l64 = @intCast(u64, low % pow19); + const lf = @intCast(u64, (low / pow19) % pow19); - var h64 = u64(high % pow19); - const hf = u64((high / pow19) % pow19); + var h64 = @intCast(u64, high % pow19); + const hf = @intCast(u64, (high / pow19) % pow19); if (lf != hf) { l64 = lf; @@ -348,7 +348,7 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { return FloatDecimal{ .digits = buffer[0..buf_index], - .exp = i32(buf_index) + mi, + .exp = @intCast(i32, buf_index) + mi, }; } @@ -359,33 +359,33 @@ fn errolInt(val: f64, buffer: []u8) FloatDecimal { fn errolFixed(val: f64, buffer: []u8) FloatDecimal { assert((val >= 16.0) and (val < 9.007199254740992e15)); - const u = u64(val); - const n = f64(u); + const u = @floatToInt(u64, val); + const n = @intToFloat(f64, u); var mid = val - n; var lo = ((fpprev(val) - n) + mid) / 2.0; var hi = ((fpnext(val) - n) + mid) / 2.0; var buf_index = u64toa(u, buffer); - var exp = i32(buf_index); + var exp = @intCast(i32, buf_index); var j = buf_index; buffer[j] = 0; if (mid != 0.0) { while (mid != 0.0) { lo *= 10.0; - const ldig = i32(lo); - lo -= f64(ldig); + const ldig = @floatToInt(i32, lo); + lo -= @intToFloat(f64, ldig); mid *= 10.0; - const mdig = i32(mid); - mid -= f64(mdig); + const mdig = @floatToInt(i32, mid); + mid -= @intToFloat(f64, mdig); hi *= 10.0; - const hdig = i32(hi); - hi -= f64(hdig); + const hdig = @floatToInt(i32, hi); + hi -= @intToFloat(f64, hdig); - buffer[j] = u8(mdig + '0'); + buffer[j] = @intCast(u8, mdig + '0'); j += 1; if (hdig != ldig or j > 50) break; @@ -452,7 +452,7 @@ fn u64toa(value_param: u64, buffer: []u8) usize { var buf_index: usize = 0; if (value < kTen8) { - const v = u32(value); + const v = @intCast(u32, value); if (v < 10000) { const d1: u32 = (v / 100) << 1; const d2: u32 = (v % 100) << 1; @@ -507,8 +507,8 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buf_index += 1; } } else if (value < kTen16) { - const v0: u32 = u32(value / kTen8); - const v1: u32 = u32(value % kTen8); + const v0: u32 = @intCast(u32, value / kTen8); + const v1: u32 = @intCast(u32, value % kTen8); const b0: u32 = v0 / 10000; const c0: u32 = v0 % 10000; @@ -578,11 +578,11 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buffer[buf_index] = c_digits_lut[d8 + 1]; buf_index += 1; } else { - const a = u32(value / kTen16); // 1 to 1844 + const a = @intCast(u32, value / kTen16); // 1 to 1844 value %= kTen16; if (a < 10) { - buffer[buf_index] = '0' + u8(a); + buffer[buf_index] = '0' + @intCast(u8, a); buf_index += 1; } else if (a < 100) { const i: u32 = a << 1; @@ -591,7 +591,7 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buffer[buf_index] = c_digits_lut[i + 1]; buf_index += 1; } else if (a < 1000) { - buffer[buf_index] = '0' + u8(a / 100); + buffer[buf_index] = '0' + @intCast(u8, a / 100); buf_index += 1; const i: u32 = (a % 100) << 1; @@ -612,8 +612,8 @@ fn u64toa(value_param: u64, buffer: []u8) usize { buf_index += 1; } - const v0 = u32(value / kTen8); - const v1 = u32(value % kTen8); + const v0 = @intCast(u32, value / kTen8); + const v1 = @intCast(u32, value % kTen8); const b0: u32 = v0 / 10000; const c0: u32 = v0 % 10000; diff --git a/std/fmt/index.zig b/std/fmt/index.zig index 90d3a559c4..f4dfa0e324 100644 --- a/std/fmt/index.zig +++ b/std/fmt/index.zig @@ -5,6 +5,7 @@ const assert = debug.assert; const mem = std.mem; const builtin = @import("builtin"); const errol = @import("errol/index.zig"); +const lossyCast = std.math.lossyCast; const max_int_digits = 65; @@ -463,7 +464,7 @@ pub fn formatFloatDecimal( errol.roundToPrecision(&float_decimal, precision, errol.RoundMode.Decimal); // exp < 0 means the leading is always 0 as errol result is normalized. - var num_digits_whole = if (float_decimal.exp > 0) usize(float_decimal.exp) else 0; + var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0; // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this. var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len); @@ -492,7 +493,7 @@ pub fn formatFloatDecimal( // Zero-fill until we reach significant digits or run out of precision. if (float_decimal.exp <= 0) { - const zero_digit_count = usize(-float_decimal.exp); + const zero_digit_count = @intCast(usize, -float_decimal.exp); const zeros_to_print = math.min(zero_digit_count, precision); var i: usize = 0; @@ -521,7 +522,7 @@ pub fn formatFloatDecimal( } } else { // exp < 0 means the leading is always 0 as errol result is normalized. - var num_digits_whole = if (float_decimal.exp > 0) usize(float_decimal.exp) else 0; + var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0; // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this. var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len); @@ -547,7 +548,7 @@ pub fn formatFloatDecimal( // Zero-fill until we reach significant digits or run out of precision. if (float_decimal.exp < 0) { - const zero_digit_count = usize(-float_decimal.exp); + const zero_digit_count = @intCast(usize, -float_decimal.exp); var i: usize = 0; while (i < zero_digit_count) : (i += 1) { @@ -578,7 +579,7 @@ pub fn formatBytes( 1024 => math.min(math.log2(value) / 10, mags_iec.len - 1), else => unreachable, }; - const new_value = f64(value) / math.pow(f64, f64(radix), f64(magnitude)); + const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, radix), lossyCast(f64, magnitude)); const suffix = switch (radix) { 1000 => mags_si[magnitude], 1024 => mags_iec[magnitude], @@ -628,15 +629,15 @@ fn formatIntSigned( if (value < 0) { const minus_sign: u8 = '-'; try output(context, (*[1]u8)(&minus_sign)[0..]); - const new_value = uint(-(value + 1)) + 1; + const new_value = @intCast(uint, -(value + 1)) + 1; const new_width = if (width == 0) 0 else (width - 1); return formatIntUnsigned(new_value, base, uppercase, new_width, context, Errors, output); } else if (width == 0) { - return formatIntUnsigned(uint(value), base, uppercase, width, context, Errors, output); + return formatIntUnsigned(@intCast(uint, value), base, uppercase, width, context, Errors, output); } else { const plus_sign: u8 = '+'; try output(context, (*[1]u8)(&plus_sign)[0..]); - const new_value = uint(value); + const new_value = @intCast(uint, value); const new_width = if (width == 0) 0 else (width - 1); return formatIntUnsigned(new_value, base, uppercase, new_width, context, Errors, output); } @@ -660,7 +661,7 @@ fn formatIntUnsigned( while (true) { const digit = a % base; index -= 1; - buf[index] = digitToChar(u8(digit), uppercase); + buf[index] = digitToChar(@intCast(u8, digit), uppercase); a /= base; if (a == 0) break; } diff --git a/std/hash/crc.zig b/std/hash/crc.zig index ec831cdc2e..c455140785 100644 --- a/std/hash/crc.zig +++ b/std/hash/crc.zig @@ -26,7 +26,7 @@ pub fn Crc32WithPoly(comptime poly: u32) type { var tables: [8][256]u32 = undefined; for (tables[0]) |*e, i| { - var crc = u32(i); + var crc = @intCast(u32, i); var j: usize = 0; while (j < 8) : (j += 1) { if (crc & 1 == 1) { @@ -122,7 +122,7 @@ pub fn Crc32SmallWithPoly(comptime poly: u32) type { var table: [16]u32 = undefined; for (table) |*e, i| { - var crc = u32(i * 16); + var crc = @intCast(u32, i * 16); var j: usize = 0; while (j < 8) : (j += 1) { if (crc & 1 == 1) { diff --git a/std/hash/siphash.zig b/std/hash/siphash.zig index 8a90308a46..cdad77e59e 100644 --- a/std/hash/siphash.zig +++ b/std/hash/siphash.zig @@ -81,7 +81,7 @@ fn SipHash(comptime T: type, comptime c_rounds: usize, comptime d_rounds: usize) // Remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); - d.buf_len += u8(b[off..].len); + d.buf_len += @intCast(u8, b[off..].len); d.msg_len +%= @truncate(u8, b.len); } @@ -233,7 +233,7 @@ test "siphash64-2-4 sanity" { var buffer: [64]u8 = undefined; for (vectors) |vector, i| { - buffer[i] = u8(i); + buffer[i] = @intCast(u8, i); const expected = mem.readInt(vector, u64, Endian.Little); debug.assert(siphash.hash(test_key, buffer[0..i]) == expected); @@ -312,7 +312,7 @@ test "siphash128-2-4 sanity" { var buffer: [64]u8 = undefined; for (vectors) |vector, i| { - buffer[i] = u8(i); + buffer[i] = @intCast(u8, i); const expected = mem.readInt(vector, u128, Endian.Little); debug.assert(siphash.hash(test_key, buffer[0..i]) == expected); diff --git a/std/heap.zig b/std/heap.zig index 172bc24118..2a2c8c0b59 100644 --- a/std/heap.zig +++ b/std/heap.zig @@ -408,7 +408,7 @@ fn testAllocator(allocator: *mem.Allocator) !void { for (slice) |*item, i| { item.* = try allocator.create(i32); - item.*.* = i32(i); + item.*.* = @intCast(i32, i); } for (slice) |item, i| { diff --git a/std/json.zig b/std/json.zig index 8bbee981e3..2930cd21bb 100644 --- a/std/json.zig +++ b/std/json.zig @@ -180,7 +180,7 @@ pub const StreamingParser = struct { pub fn fromInt(x: var) State { debug.assert(x == 0 or x == 1); const T = @TagType(State); - return State(T(x)); + return State(@intCast(T, x)); } }; diff --git a/std/math/acos.zig b/std/math/acos.zig index 284f73fc91..54844e8f6e 100644 --- a/std/math/acos.zig +++ b/std/math/acos.zig @@ -95,12 +95,12 @@ fn acos64(x: f64) f64 { const pio2_lo: f64 = 6.12323399573676603587e-17; const ux = @bitCast(u64, x); - const hx = u32(ux >> 32); + const hx = @intCast(u32, ux >> 32); const ix = hx & 0x7FFFFFFF; // |x| >= 1 or nan if (ix >= 0x3FF00000) { - const lx = u32(ux & 0xFFFFFFFF); + const lx = @intCast(u32, ux & 0xFFFFFFFF); // acos(1) = 0, acos(-1) = pi if ((ix - 0x3FF00000) | lx == 0) { diff --git a/std/math/asin.zig b/std/math/asin.zig index 2ee3aa6048..30b3a57e32 100644 --- a/std/math/asin.zig +++ b/std/math/asin.zig @@ -87,12 +87,12 @@ fn asin64(x: f64) f64 { const pio2_lo: f64 = 6.12323399573676603587e-17; const ux = @bitCast(u64, x); - const hx = u32(ux >> 32); + const hx = @intCast(u32, ux >> 32); const ix = hx & 0x7FFFFFFF; // |x| >= 1 or nan if (ix >= 0x3FF00000) { - const lx = u32(ux & 0xFFFFFFFF); + const lx = @intCast(u32, ux & 0xFFFFFFFF); // asin(1) = +-pi/2 with inexact if ((ix - 0x3FF00000) | lx == 0) { diff --git a/std/math/atan.zig b/std/math/atan.zig index 7eceef98e3..6ca94dd84a 100644 --- a/std/math/atan.zig +++ b/std/math/atan.zig @@ -138,7 +138,7 @@ fn atan64(x_: f64) f64 { var x = x_; var ux = @bitCast(u64, x); - var ix = u32(ux >> 32); + var ix = @intCast(u32, ux >> 32); const sign = ix >> 31; ix &= 0x7FFFFFFF; @@ -159,7 +159,7 @@ fn atan64(x_: f64) f64 { // |x| < 2^(-27) if (ix < 0x3E400000) { if (ix < 0x00100000) { - math.forceEval(f32(x)); + math.forceEval(@floatCast(f32, x)); } return x; } diff --git a/std/math/atan2.zig b/std/math/atan2.zig index f0a8e67c46..b3e45ba045 100644 --- a/std/math/atan2.zig +++ b/std/math/atan2.zig @@ -124,12 +124,12 @@ fn atan2_64(y: f64, x: f64) f64 { } var ux = @bitCast(u64, x); - var ix = u32(ux >> 32); - var lx = u32(ux & 0xFFFFFFFF); + var ix = @intCast(u32, ux >> 32); + var lx = @intCast(u32, ux & 0xFFFFFFFF); var uy = @bitCast(u64, y); - var iy = u32(uy >> 32); - var ly = u32(uy & 0xFFFFFFFF); + var iy = @intCast(u32, uy >> 32); + var ly = @intCast(u32, uy & 0xFFFFFFFF); // x = 1.0 if ((ix -% 0x3FF00000) | lx == 0) { diff --git a/std/math/atanh.zig b/std/math/atanh.zig index 8ca0cc85bc..4ae8a66bc0 100644 --- a/std/math/atanh.zig +++ b/std/math/atanh.zig @@ -62,7 +62,7 @@ fn atanh_64(x: f64) f64 { if (e < 0x3FF - 32) { // underflow if (e == 0) { - math.forceEval(f32(y)); + math.forceEval(@floatCast(f32, y)); } } // |x| < 0.5 diff --git a/std/math/big/int.zig b/std/math/big/int.zig index 5e15cfb895..21d9347c01 100644 --- a/std/math/big/int.zig +++ b/std/math/big/int.zig @@ -135,7 +135,7 @@ pub const Int = struct { self.positive = value >= 0; self.len = 0; - var w_value: UT = if (value < 0) UT(-value) else UT(value); + var w_value: UT = if (value < 0) @intCast(UT, -value) else @intCast(UT, value); if (info.bits <= Limb.bit_count) { self.limbs[0] = Limb(w_value); @@ -198,7 +198,7 @@ pub const Int = struct { var r: UT = 0; if (@sizeOf(UT) <= @sizeOf(Limb)) { - r = UT(self.limbs[0]); + r = @intCast(UT, self.limbs[0]); } else { for (self.limbs[0..self.len]) |_, ri| { const limb = self.limbs[self.len - ri - 1]; @@ -210,7 +210,7 @@ pub const Int = struct { if (!T.is_signed) { return if (self.positive) r else error.NegativeIntoUnsigned; } else { - return if (self.positive) T(r) else -T(r); + return if (self.positive) @intCast(T, r) else -@intCast(T, r); } }, else => { @@ -295,7 +295,7 @@ pub const Int = struct { for (self.limbs[0..self.len]) |limb| { var shift: usize = 0; while (shift < Limb.bit_count) : (shift += base_shift) { - const r = u8((limb >> Log2Limb(shift)) & Limb(base - 1)); + const r = @intCast(u8, (limb >> @intCast(Log2Limb, shift)) & Limb(base - 1)); const ch = try digitToChar(r, base); try digits.append(ch); } @@ -329,7 +329,7 @@ pub const Int = struct { var r_word = r.limbs[0]; var i: usize = 0; while (i < digits_per_limb) : (i += 1) { - const ch = try digitToChar(u8(r_word % base), base); + const ch = try digitToChar(@intCast(u8, r_word % base), base); r_word /= base; try digits.append(ch); } @@ -340,7 +340,7 @@ pub const Int = struct { var r_word = q.limbs[0]; while (r_word != 0) { - const ch = try digitToChar(u8(r_word % base), base); + const ch = try digitToChar(@intCast(u8, r_word % base), base); r_word /= base; try digits.append(ch); } @@ -801,7 +801,7 @@ pub const Int = struct { q.limbs[i - t - 1] = @maxValue(Limb); } else { const num = (DoubleLimb(x.limbs[i]) << Limb.bit_count) | DoubleLimb(x.limbs[i - 1]); - const z = Limb(num / DoubleLimb(y.limbs[t])); + const z = @intCast(Limb, num / DoubleLimb(y.limbs[t])); q.limbs[i - t - 1] = if (z > @maxValue(Limb)) @maxValue(Limb) else Limb(z); } @@ -860,7 +860,7 @@ pub const Int = struct { debug.assert(r.len >= a.len + (shift / Limb.bit_count) + 1); const limb_shift = shift / Limb.bit_count + 1; - const interior_limb_shift = Log2Limb(shift % Limb.bit_count); + const interior_limb_shift = @intCast(Log2Limb, shift % Limb.bit_count); var carry: Limb = 0; var i: usize = 0; @@ -869,7 +869,7 @@ pub const Int = struct { const dst_i = src_i + limb_shift; const src_digit = a[src_i]; - r[dst_i] = carry | @inlineCall(math.shr, Limb, src_digit, Limb.bit_count - Limb(interior_limb_shift)); + r[dst_i] = carry | @inlineCall(math.shr, Limb, src_digit, Limb.bit_count - @intCast(Limb, interior_limb_shift)); carry = (src_digit << interior_limb_shift); } @@ -898,7 +898,7 @@ pub const Int = struct { debug.assert(r.len >= a.len - (shift / Limb.bit_count)); const limb_shift = shift / Limb.bit_count; - const interior_limb_shift = Log2Limb(shift % Limb.bit_count); + const interior_limb_shift = @intCast(Log2Limb, shift % Limb.bit_count); var carry: Limb = 0; var i: usize = 0; @@ -908,7 +908,7 @@ pub const Int = struct { const src_digit = a[src_i]; r[dst_i] = carry | (src_digit >> interior_limb_shift); - carry = @inlineCall(math.shl, Limb, src_digit, Limb.bit_count - Limb(interior_limb_shift)); + carry = @inlineCall(math.shl, Limb, src_digit, Limb.bit_count - @intCast(Limb, interior_limb_shift)); } } diff --git a/std/math/cbrt.zig b/std/math/cbrt.zig index cd3b71ca8a..c067c5155a 100644 --- a/std/math/cbrt.zig +++ b/std/math/cbrt.zig @@ -54,7 +54,7 @@ fn cbrt32(x: f32) f32 { r = t * t * t; t = t * (f64(x) + x + r) / (x + r + r); - return f32(t); + return @floatCast(f32, t); } fn cbrt64(x: f64) f64 { @@ -69,7 +69,7 @@ fn cbrt64(x: f64) f64 { const P4: f64 = 0.145996192886612446982; var u = @bitCast(u64, x); - var hx = u32(u >> 32) & 0x7FFFFFFF; + var hx = @intCast(u32, u >> 32) & 0x7FFFFFFF; // cbrt(nan, inf) = itself if (hx >= 0x7FF00000) { @@ -79,7 +79,7 @@ fn cbrt64(x: f64) f64 { // cbrt to ~5bits if (hx < 0x00100000) { u = @bitCast(u64, x * 0x1.0p54); - hx = u32(u >> 32) & 0x7FFFFFFF; + hx = @intCast(u32, u >> 32) & 0x7FFFFFFF; // cbrt(0) is itself if (hx == 0) { diff --git a/std/math/ceil.zig b/std/math/ceil.zig index a189bb66d2..1c429504e8 100644 --- a/std/math/ceil.zig +++ b/std/math/ceil.zig @@ -20,7 +20,7 @@ pub fn ceil(x: var) @typeOf(x) { fn ceil32(x: f32) f32 { var u = @bitCast(u32, x); - var e = i32((u >> 23) & 0xFF) - 0x7F; + var e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. @@ -31,7 +31,7 @@ fn ceil32(x: f32) f32 { if (e >= 23) { return x; } else if (e >= 0) { - m = u32(0x007FFFFF) >> u5(e); + m = u32(0x007FFFFF) >> @intCast(u5, e); if (u & m == 0) { return x; } diff --git a/std/math/complex/atan.zig b/std/math/complex/atan.zig index 9bfe5fe724..de60f2546d 100644 --- a/std/math/complex/atan.zig +++ b/std/math/complex/atan.zig @@ -4,7 +4,7 @@ const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; -pub fn atan(z: var) Complex(@typeOf(z.re)) { +pub fn atan(z: var) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { f32 => atan32(z), @@ -25,11 +25,11 @@ fn redupif32(x: f32) f32 { t -= 0.5; } - const u = f32(i32(t)); + const u = @intToFloat(f32, @floatToInt(i32, t)); return ((x - u * DP1) - u * DP2) - t * DP3; } -fn atan32(z: *const Complex(f32)) Complex(f32) { +fn atan32(z: Complex(f32)) Complex(f32) { const maxnum = 1.0e38; const x = z.re; @@ -74,11 +74,11 @@ fn redupif64(x: f64) f64 { t -= 0.5; } - const u = f64(i64(t)); + const u = @intToFloat(f64, @floatToInt(i64, t)); return ((x - u * DP1) - u * DP2) - t * DP3; } -fn atan64(z: *const Complex(f64)) Complex(f64) { +fn atan64(z: Complex(f64)) Complex(f64) { const maxnum = 1.0e308; const x = z.re; diff --git a/std/math/complex/cosh.zig b/std/math/complex/cosh.zig index c2f9a47b8d..a2e31631ea 100644 --- a/std/math/complex/cosh.zig +++ b/std/math/complex/cosh.zig @@ -83,12 +83,12 @@ fn cosh64(z: *const Complex(f64)) Complex(f64) { const y = z.im; const fx = @bitCast(u64, x); - const hx = u32(fx >> 32); + const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); const ix = hx & 0x7fffffff; const fy = @bitCast(u64, y); - const hy = u32(fy >> 32); + const hy = @intCast(u32, fy >> 32); const ly = @truncate(u32, fy); const iy = hy & 0x7fffffff; diff --git a/std/math/complex/exp.zig b/std/math/complex/exp.zig index 44c354f246..48fb132d97 100644 --- a/std/math/complex/exp.zig +++ b/std/math/complex/exp.zig @@ -6,7 +6,7 @@ const Complex = cmath.Complex; const ldexp_cexp = @import("ldexp.zig").ldexp_cexp; -pub fn exp(z: var) Complex(@typeOf(z.re)) { +pub fn exp(z: var) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { @@ -16,7 +16,7 @@ pub fn exp(z: var) Complex(@typeOf(z.re)) { }; } -fn exp32(z: *const Complex(f32)) Complex(f32) { +fn exp32(z: Complex(f32)) Complex(f32) { @setFloatMode(this, @import("builtin").FloatMode.Strict); const exp_overflow = 0x42b17218; // max_exp * ln2 ~= 88.72283955 @@ -63,7 +63,7 @@ fn exp32(z: *const Complex(f32)) Complex(f32) { } } -fn exp64(z: *const Complex(f64)) Complex(f64) { +fn exp64(z: Complex(f64)) Complex(f64) { const exp_overflow = 0x40862e42; // high bits of max_exp * ln2 ~= 710 const cexp_overflow = 0x4096b8e4; // (max_exp - min_denorm_exp) * ln2 diff --git a/std/math/complex/ldexp.zig b/std/math/complex/ldexp.zig index a56c2ef2eb..e919ef6bec 100644 --- a/std/math/complex/ldexp.zig +++ b/std/math/complex/ldexp.zig @@ -4,7 +4,7 @@ const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; -pub fn ldexp_cexp(z: var, expt: i32) Complex(@typeOf(z.re)) { +pub fn ldexp_cexp(z: var, expt: i32) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { @@ -20,11 +20,12 @@ fn frexp_exp32(x: f32, expt: *i32) f32 { const exp_x = math.exp(x - kln2); const hx = @bitCast(u32, exp_x); - expt.* = i32(hx >> 23) - (0x7f + 127) + k; + // TODO zig should allow this cast implicitly because it should know the value is in range + expt.* = @intCast(i32, hx >> 23) - (0x7f + 127) + k; return @bitCast(f32, (hx & 0x7fffff) | ((0x7f + 127) << 23)); } -fn ldexp_cexp32(z: *const Complex(f32), expt: i32) Complex(f32) { +fn ldexp_cexp32(z: Complex(f32), expt: i32) Complex(f32) { var ex_expt: i32 = undefined; const exp_x = frexp_exp32(z.re, &ex_expt); const exptf = expt + ex_expt; @@ -45,16 +46,16 @@ fn frexp_exp64(x: f64, expt: *i32) f64 { const exp_x = math.exp(x - kln2); const fx = @bitCast(u64, x); - const hx = u32(fx >> 32); + const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); - expt.* = i32(hx >> 20) - (0x3ff + 1023) + k; + expt.* = @intCast(i32, hx >> 20) - (0x3ff + 1023) + k; const high_word = (hx & 0xfffff) | ((0x3ff + 1023) << 20); return @bitCast(f64, (u64(high_word) << 32) | lx); } -fn ldexp_cexp64(z: *const Complex(f64), expt: i32) Complex(f64) { +fn ldexp_cexp64(z: Complex(f64), expt: i32) Complex(f64) { var ex_expt: i32 = undefined; const exp_x = frexp_exp64(z.re, &ex_expt); const exptf = i64(expt + ex_expt); diff --git a/std/math/complex/sinh.zig b/std/math/complex/sinh.zig index 3d196bfd50..ab23c5c74d 100644 --- a/std/math/complex/sinh.zig +++ b/std/math/complex/sinh.zig @@ -6,7 +6,7 @@ const Complex = cmath.Complex; const ldexp_cexp = @import("ldexp.zig").ldexp_cexp; -pub fn sinh(z: var) Complex(@typeOf(z.re)) { +pub fn sinh(z: var) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { f32 => sinh32(z), @@ -15,7 +15,7 @@ pub fn sinh(z: var) Complex(@typeOf(z.re)) { }; } -fn sinh32(z: *const Complex(f32)) Complex(f32) { +fn sinh32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; @@ -78,17 +78,17 @@ fn sinh32(z: *const Complex(f32)) Complex(f32) { return Complex(f32).new((x * x) * (y - y), (x + x) * (y - y)); } -fn sinh64(z: *const Complex(f64)) Complex(f64) { +fn sinh64(z: Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; const fx = @bitCast(u64, x); - const hx = u32(fx >> 32); + const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); const ix = hx & 0x7fffffff; const fy = @bitCast(u64, y); - const hy = u32(fy >> 32); + const hy = @intCast(u32, fy >> 32); const ly = @truncate(u32, fy); const iy = hy & 0x7fffffff; diff --git a/std/math/complex/sqrt.zig b/std/math/complex/sqrt.zig index caa3bd2868..47367816f7 100644 --- a/std/math/complex/sqrt.zig +++ b/std/math/complex/sqrt.zig @@ -49,10 +49,16 @@ fn sqrt32(z: Complex(f32)) Complex(f32) { if (dx >= 0) { const t = math.sqrt((dx + math.hypot(f64, dx, dy)) * 0.5); - return Complex(f32).new(f32(t), f32(dy / (2.0 * t))); + return Complex(f32).new( + @floatCast(f32, t), + @floatCast(f32, dy / (2.0 * t)), + ); } else { const t = math.sqrt((-dx + math.hypot(f64, dx, dy)) * 0.5); - return Complex(f32).new(f32(math.fabs(y) / (2.0 * t)), f32(math.copysign(f64, t, y))); + return Complex(f32).new( + @floatCast(f32, math.fabs(y) / (2.0 * t)), + @floatCast(f32, math.copysign(f64, t, y)), + ); } } diff --git a/std/math/complex/tanh.zig b/std/math/complex/tanh.zig index 1d754838a3..e48d438783 100644 --- a/std/math/complex/tanh.zig +++ b/std/math/complex/tanh.zig @@ -4,7 +4,7 @@ const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; -pub fn tanh(z: var) Complex(@typeOf(z.re)) { +pub fn tanh(z: var) @typeOf(z) { const T = @typeOf(z.re); return switch (T) { f32 => tanh32(z), @@ -13,7 +13,7 @@ pub fn tanh(z: var) Complex(@typeOf(z.re)) { }; } -fn tanh32(z: *const Complex(f32)) Complex(f32) { +fn tanh32(z: Complex(f32)) Complex(f32) { const x = z.re; const y = z.im; @@ -51,12 +51,14 @@ fn tanh32(z: *const Complex(f32)) Complex(f32) { return Complex(f32).new((beta * rho * s) / den, t / den); } -fn tanh64(z: *const Complex(f64)) Complex(f64) { +fn tanh64(z: Complex(f64)) Complex(f64) { const x = z.re; const y = z.im; const fx = @bitCast(u64, x); - const hx = u32(fx >> 32); + // TODO: zig should allow this conversion implicitly because it can notice that the value necessarily + // fits in range. + const hx = @intCast(u32, fx >> 32); const lx = @truncate(u32, fx); const ix = hx & 0x7fffffff; diff --git a/std/math/cos.zig b/std/math/cos.zig index 5e5ec4f1cb..71d5e4a8f6 100644 --- a/std/math/cos.zig +++ b/std/math/cos.zig @@ -55,7 +55,7 @@ fn cos32(x_: f32) f32 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; @@ -106,7 +106,7 @@ fn cos64(x_: f64) f64 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; diff --git a/std/math/cosh.zig b/std/math/cosh.zig index fa46219986..52beafb642 100644 --- a/std/math/cosh.zig +++ b/std/math/cosh.zig @@ -49,7 +49,7 @@ fn cosh32(x: f32) f32 { fn cosh64(x: f64) f64 { const u = @bitCast(u64, x); - const w = u32(u >> 32); + const w = @intCast(u32, u >> 32); const ax = @bitCast(f64, u & (@maxValue(u64) >> 1)); // TODO: Shouldn't need this explicit check. diff --git a/std/math/exp.zig b/std/math/exp.zig index 76dc47d04b..d6185d4f0b 100644 --- a/std/math/exp.zig +++ b/std/math/exp.zig @@ -29,7 +29,7 @@ fn exp32(x_: f32) f32 { var x = x_; var hx = @bitCast(u32, x); - const sign = i32(hx >> 31); + const sign = @intCast(i32, hx >> 31); hx &= 0x7FFFFFFF; if (math.isNan(x)) { @@ -63,12 +63,12 @@ fn exp32(x_: f32) f32 { if (hx > 0x3EB17218) { // |x| > 1.5 * ln2 if (hx > 0x3F851592) { - k = i32(invln2 * x + half[usize(sign)]); + k = @floatToInt(i32, invln2 * x + half[@intCast(usize, sign)]); } else { k = 1 - sign - sign; } - const fk = f32(k); + const fk = @intToFloat(f32, k); hi = x - fk * ln2hi; lo = fk * ln2lo; x = hi - lo; @@ -110,7 +110,7 @@ fn exp64(x_: f64) f64 { var x = x_; var ux = @bitCast(u64, x); var hx = ux >> 32; - const sign = i32(hx >> 31); + const sign = @intCast(i32, hx >> 31); hx &= 0x7FFFFFFF; if (math.isNan(x)) { @@ -148,12 +148,12 @@ fn exp64(x_: f64) f64 { if (hx > 0x3EB17218) { // |x| >= 1.5 * ln2 if (hx > 0x3FF0A2B2) { - k = i32(invln2 * x + half[usize(sign)]); + k = @floatToInt(i32, invln2 * x + half[@intCast(usize, sign)]); } else { k = 1 - sign - sign; } - const dk = f64(k); + const dk = @intToFloat(f64, k); hi = x - dk * ln2hi; lo = dk * ln2lo; x = hi - lo; diff --git a/std/math/exp2.zig b/std/math/exp2.zig index 62a3eb85b6..90ea088181 100644 --- a/std/math/exp2.zig +++ b/std/math/exp2.zig @@ -38,8 +38,8 @@ const exp2ft = []const f64{ fn exp2_32(x: f32) f32 { @setFloatMode(this, @import("builtin").FloatMode.Strict); - const tblsiz = u32(exp2ft.len); - const redux: f32 = 0x1.8p23 / f32(tblsiz); + const tblsiz = @intCast(u32, exp2ft.len); + const redux: f32 = 0x1.8p23 / @intToFloat(f32, tblsiz); const P1: f32 = 0x1.62e430p-1; const P2: f32 = 0x1.ebfbe0p-3; const P3: f32 = 0x1.c6b348p-5; @@ -89,7 +89,7 @@ fn exp2_32(x: f32) f32 { var r: f64 = exp2ft[i0]; const t: f64 = r * z; r = r + t * (P1 + z * P2) + t * (z * z) * (P3 + z * P4); - return f32(r * uk); + return @floatCast(f32, r * uk); } const exp2dt = []f64{ @@ -355,8 +355,8 @@ const exp2dt = []f64{ fn exp2_64(x: f64) f64 { @setFloatMode(this, @import("builtin").FloatMode.Strict); - const tblsiz = u32(exp2dt.len / 2); - const redux: f64 = 0x1.8p52 / f64(tblsiz); + const tblsiz = @intCast(u32, exp2dt.len / 2); + const redux: f64 = 0x1.8p52 / @intToFloat(f64, tblsiz); const P1: f64 = 0x1.62e42fefa39efp-1; const P2: f64 = 0x1.ebfbdff82c575p-3; const P3: f64 = 0x1.c6b08d704a0a6p-5; @@ -364,7 +364,7 @@ fn exp2_64(x: f64) f64 { const P5: f64 = 0x1.5d88003875c74p-10; const ux = @bitCast(u64, x); - const ix = u32(ux >> 32) & 0x7FFFFFFF; + const ix = @intCast(u32, ux >> 32) & 0x7FFFFFFF; // TODO: This should be handled beneath. if (math.isNan(x)) { @@ -386,7 +386,7 @@ fn exp2_64(x: f64) f64 { if (ux >> 63 != 0) { // underflow if (x <= -1075 or x - 0x1.0p52 + 0x1.0p52 != x) { - math.forceEval(f32(-0x1.0p-149 / x)); + math.forceEval(@floatCast(f32, -0x1.0p-149 / x)); } if (x <= -1075) { return 0; diff --git a/std/math/expm1.zig b/std/math/expm1.zig index 11af1b215f..438e44ccce 100644 --- a/std/math/expm1.zig +++ b/std/math/expm1.zig @@ -78,8 +78,8 @@ fn expm1_32(x_: f32) f32 { kf += 0.5; } - k = i32(kf); - const t = f32(k); + k = @floatToInt(i32, kf); + const t = @intToFloat(f32, k); hi = x - t * ln2_hi; lo = t * ln2_lo; } @@ -123,7 +123,7 @@ fn expm1_32(x_: f32) f32 { } } - const twopk = @bitCast(f32, u32((0x7F +% k) << 23)); + const twopk = @bitCast(f32, @intCast(u32, (0x7F +% k) << 23)); if (k < 0 or k > 56) { var y = x - e + 1.0; @@ -136,7 +136,7 @@ fn expm1_32(x_: f32) f32 { return y - 1.0; } - const uf = @bitCast(f32, u32(0x7F -% k) << 23); + const uf = @bitCast(f32, @intCast(u32, 0x7F -% k) << 23); if (k < 23) { return (x - e + (1 - uf)) * twopk; } else { @@ -158,7 +158,7 @@ fn expm1_64(x_: f64) f64 { var x = x_; const ux = @bitCast(u64, x); - const hx = u32(ux >> 32) & 0x7FFFFFFF; + const hx = @intCast(u32, ux >> 32) & 0x7FFFFFFF; const sign = ux >> 63; if (math.isNegativeInf(x)) { @@ -207,8 +207,8 @@ fn expm1_64(x_: f64) f64 { kf += 0.5; } - k = i32(kf); - const t = f64(k); + k = @floatToInt(i32, kf); + const t = @intToFloat(f64, k); hi = x - t * ln2_hi; lo = t * ln2_lo; } @@ -219,7 +219,7 @@ fn expm1_64(x_: f64) f64 { // |x| < 2^(-54) else if (hx < 0x3C900000) { if (hx < 0x00100000) { - math.forceEval(f32(x)); + math.forceEval(@floatCast(f32, x)); } return x; } else { @@ -252,7 +252,7 @@ fn expm1_64(x_: f64) f64 { } } - const twopk = @bitCast(f64, u64(0x3FF +% k) << 52); + const twopk = @bitCast(f64, @intCast(u64, 0x3FF +% k) << 52); if (k < 0 or k > 56) { var y = x - e + 1.0; @@ -265,7 +265,7 @@ fn expm1_64(x_: f64) f64 { return y - 1.0; } - const uf = @bitCast(f64, u64(0x3FF -% k) << 52); + const uf = @bitCast(f64, @intCast(u64, 0x3FF -% k) << 52); if (k < 20) { return (x - e + (1 - uf)) * twopk; } else { diff --git a/std/math/floor.zig b/std/math/floor.zig index 7d5364787f..79d1097d08 100644 --- a/std/math/floor.zig +++ b/std/math/floor.zig @@ -20,7 +20,7 @@ pub fn floor(x: var) @typeOf(x) { fn floor32(x: f32) f32 { var u = @bitCast(u32, x); - const e = i32((u >> 23) & 0xFF) - 0x7F; + const e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. @@ -33,7 +33,7 @@ fn floor32(x: f32) f32 { } if (e >= 0) { - m = u32(0x007FFFFF) >> u5(e); + m = u32(0x007FFFFF) >> @intCast(u5, e); if (u & m == 0) { return x; } diff --git a/std/math/fma.zig b/std/math/fma.zig index 3e9214f35b..21faf4118d 100644 --- a/std/math/fma.zig +++ b/std/math/fma.zig @@ -17,10 +17,10 @@ fn fma32(x: f32, y: f32, z: f32) f32 { const e = (u >> 52) & 0x7FF; if ((u & 0x1FFFFFFF) != 0x10000000 or e == 0x7FF or xy_z - xy == z) { - return f32(xy_z); + return @floatCast(f32, xy_z); } else { // TODO: Handle inexact case with double-rounding - return f32(xy_z); + return @floatCast(f32, xy_z); } } @@ -124,7 +124,7 @@ fn add_and_denorm(a: f64, b: f64, scale: i32) f64 { var sum = dd_add(a, b); if (sum.lo != 0) { var uhii = @bitCast(u64, sum.hi); - const bits_lost = -i32((uhii >> 52) & 0x7FF) - scale + 1; + const bits_lost = -@intCast(i32, (uhii >> 52) & 0x7FF) - scale + 1; if ((bits_lost != 1) == (uhii & 1 != 0)) { const uloi = @bitCast(u64, sum.lo); uhii += 1 - (((uhii ^ uloi) >> 62) & 2); diff --git a/std/math/frexp.zig b/std/math/frexp.zig index b58af0a9bc..dfc790fdd9 100644 --- a/std/math/frexp.zig +++ b/std/math/frexp.zig @@ -30,7 +30,7 @@ fn frexp32(x: f32) frexp32_result { var result: frexp32_result = undefined; var y = @bitCast(u32, x); - const e = i32(y >> 23) & 0xFF; + const e = @intCast(i32, y >> 23) & 0xFF; if (e == 0) { if (x != 0) { @@ -67,7 +67,7 @@ fn frexp64(x: f64) frexp64_result { var result: frexp64_result = undefined; var y = @bitCast(u64, x); - const e = i32(y >> 52) & 0x7FF; + const e = @intCast(i32, y >> 52) & 0x7FF; if (e == 0) { if (x != 0) { diff --git a/std/math/hypot.zig b/std/math/hypot.zig index 494df22ba6..f834f422e6 100644 --- a/std/math/hypot.zig +++ b/std/math/hypot.zig @@ -49,7 +49,7 @@ fn hypot32(x: f32, y: f32) f32 { yy *= 0x1.0p-90; } - return z * math.sqrt(f32(f64(x) * x + f64(y) * y)); + return z * math.sqrt(@floatCast(f32, f64(x) * x + f64(y) * y)); } fn sq(hi: *f64, lo: *f64, x: f64) void { diff --git a/std/math/ilogb.zig b/std/math/ilogb.zig index f1f33aff55..a24f580a32 100644 --- a/std/math/ilogb.zig +++ b/std/math/ilogb.zig @@ -23,7 +23,7 @@ const fp_ilogb0 = fp_ilogbnan; fn ilogb32(x: f32) i32 { var u = @bitCast(u32, x); - var e = i32((u >> 23) & 0xFF); + var e = @intCast(i32, (u >> 23) & 0xFF); // TODO: We should be able to merge this with the lower check. if (math.isNan(x)) { @@ -59,7 +59,7 @@ fn ilogb32(x: f32) i32 { fn ilogb64(x: f64) i32 { var u = @bitCast(u64, x); - var e = i32((u >> 52) & 0x7FF); + var e = @intCast(i32, (u >> 52) & 0x7FF); if (math.isNan(x)) { return @maxValue(i32); diff --git a/std/math/index.zig b/std/math/index.zig index 99e5b4ecf1..176293be74 100644 --- a/std/math/index.zig +++ b/std/math/index.zig @@ -227,7 +227,7 @@ pub fn shlExact(comptime T: type, a: T, shift_amt: Log2Int(T)) !T { /// A negative shift amount results in a right shift. pub fn shl(comptime T: type, a: T, shift_amt: var) T { const abs_shift_amt = absCast(shift_amt); - const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else Log2Int(T)(abs_shift_amt); + const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else @intCast(Log2Int(T), abs_shift_amt); if (@typeOf(shift_amt).is_signed) { if (shift_amt >= 0) { @@ -251,7 +251,7 @@ test "math.shl" { /// A negative shift amount results in a lefft shift. pub fn shr(comptime T: type, a: T, shift_amt: var) T { const abs_shift_amt = absCast(shift_amt); - const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else Log2Int(T)(abs_shift_amt); + const casted_shift_amt = if (abs_shift_amt >= T.bit_count) return 0 else @intCast(Log2Int(T), abs_shift_amt); if (@typeOf(shift_amt).is_signed) { if (shift_amt >= 0) { @@ -473,9 +473,9 @@ fn testRem() void { /// Result is an unsigned integer. pub fn absCast(x: var) @IntType(false, @typeOf(x).bit_count) { const uint = @IntType(false, @typeOf(x).bit_count); - if (x >= 0) return uint(x); + if (x >= 0) return @intCast(uint, x); - return uint(-(x + 1)) + 1; + return @intCast(uint, -(x + 1)) + 1; } test "math.absCast" { @@ -499,7 +499,7 @@ pub fn negateCast(x: var) !@IntType(true, @typeOf(x).bit_count) { if (x == -@minValue(int)) return @minValue(int); - return -int(x); + return -@intCast(int, x); } test "math.negateCast" { @@ -522,7 +522,7 @@ pub fn cast(comptime T: type, x: var) (error{Overflow}!T) { } else if (@minValue(@typeOf(x)) < @minValue(T) and x < @minValue(T)) { return error.Overflow; } else { - return T(x); + return @intCast(T, x); } } @@ -565,7 +565,7 @@ test "math.floorPowerOfTwo" { pub fn log2_int(comptime T: type, x: T) Log2Int(T) { assert(x != 0); - return Log2Int(T)(T.bit_count - 1 - @clz(x)); + return @intCast(Log2Int(T), T.bit_count - 1 - @clz(x)); } pub fn log2_int_ceil(comptime T: type, x: T) Log2Int(T) { @@ -597,3 +597,14 @@ fn testFloorPowerOfTwo() void { assert(floorPowerOfTwo(u4, 8) == 8); assert(floorPowerOfTwo(u4, 9) == 8); } + +pub fn lossyCast(comptime T: type, value: var) T { + switch (@typeInfo(@typeOf(value))) { + builtin.TypeId.Int => return @intToFloat(T, value), + builtin.TypeId.Float => return @floatCast(T, value), + builtin.TypeId.ComptimeInt => return T(value), + builtin.TypeId.ComptimeFloat => return T(value), + else => @compileError("bad type"), + } +} + diff --git a/std/math/ln.zig b/std/math/ln.zig index 3fd75977b9..e78cc379e0 100644 --- a/std/math/ln.zig +++ b/std/math/ln.zig @@ -71,7 +71,7 @@ pub fn ln_32(x_: f32) f32 { // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; - k += i32(ix >> 23) - 0x7F; + k += @intCast(i32, ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); @@ -83,7 +83,7 @@ pub fn ln_32(x_: f32) f32 { const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; - const dk = f32(k); + const dk = @intToFloat(f32, k); return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi; } @@ -103,7 +103,7 @@ pub fn ln_64(x_: f64) f64 { var x = x_; var ix = @bitCast(u64, x); - var hx = u32(ix >> 32); + var hx = @intCast(u32, ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { @@ -119,7 +119,7 @@ pub fn ln_64(x_: f64) f64 { // subnormal, scale x k -= 54; x *= 0x1.0p54; - hx = u32(@bitCast(u64, ix) >> 32); + hx = @intCast(u32, @bitCast(u64, ix) >> 32); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { @@ -128,7 +128,7 @@ pub fn ln_64(x_: f64) f64 { // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; - k += i32(hx >> 20) - 0x3FF; + k += @intCast(i32, hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); @@ -141,7 +141,7 @@ pub fn ln_64(x_: f64) f64 { const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; - const dk = f64(k); + const dk = @intToFloat(f64, k); return s * (hfsq + R) + dk * ln2_lo - hfsq + f + dk * ln2_hi; } diff --git a/std/math/log.zig b/std/math/log.zig index 2c876081d8..20b6d055e8 100644 --- a/std/math/log.zig +++ b/std/math/log.zig @@ -13,22 +13,23 @@ pub fn log(comptime T: type, base: T, x: T) T { return math.ln(x); } + const float_base = math.lossyCast(f64, base); switch (@typeId(T)) { TypeId.ComptimeFloat => { - return @typeOf(1.0)(math.ln(f64(x)) / math.ln(f64(base))); + return @typeOf(1.0)(math.ln(f64(x)) / math.ln(float_base)); }, TypeId.ComptimeInt => { - return @typeOf(1)(math.floor(math.ln(f64(x)) / math.ln(f64(base)))); + return @typeOf(1)(math.floor(math.ln(f64(x)) / math.ln(float_base))); }, builtin.TypeId.Int => { // TODO implement integer log without using float math - return T(math.floor(math.ln(f64(x)) / math.ln(f64(base)))); + return @floatToInt(T, math.floor(math.ln(@intToFloat(f64, x)) / math.ln(float_base))); }, builtin.TypeId.Float => { switch (T) { - f32 => return f32(math.ln(f64(x)) / math.ln(f64(base))), - f64 => return math.ln(x) / math.ln(f64(base)), + f32 => return @floatCast(f32, math.ln(f64(x)) / math.ln(float_base)), + f64 => return math.ln(x) / math.ln(float_base), else => @compileError("log not implemented for " ++ @typeName(T)), } }, diff --git a/std/math/log10.zig b/std/math/log10.zig index c444add9ac..a93ce48fb7 100644 --- a/std/math/log10.zig +++ b/std/math/log10.zig @@ -28,7 +28,7 @@ pub fn log10(x: var) @typeOf(x) { return @typeOf(1)(math.floor(log10_64(f64(x)))); }, TypeId.Int => { - return T(math.floor(log10_64(f64(x)))); + return @floatToInt(T, math.floor(log10_64(@intToFloat(f64, x)))); }, else => @compileError("log10 not implemented for " ++ @typeName(T)), } @@ -71,7 +71,7 @@ pub fn log10_32(x_: f32) f32 { // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; - k += i32(ix >> 23) - 0x7F; + k += @intCast(i32, ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); @@ -89,7 +89,7 @@ pub fn log10_32(x_: f32) f32 { u &= 0xFFFFF000; hi = @bitCast(f32, u); const lo = f - hi - hfsq + s * (hfsq + R); - const dk = f32(k); + const dk = @intToFloat(f32, k); return dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi + hi * ivln10hi + dk * log10_2hi; } @@ -109,7 +109,7 @@ pub fn log10_64(x_: f64) f64 { var x = x_; var ix = @bitCast(u64, x); - var hx = u32(ix >> 32); + var hx = @intCast(u32, ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { @@ -125,7 +125,7 @@ pub fn log10_64(x_: f64) f64 { // subnormal, scale x k -= 54; x *= 0x1.0p54; - hx = u32(@bitCast(u64, x) >> 32); + hx = @intCast(u32, @bitCast(u64, x) >> 32); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { @@ -134,7 +134,7 @@ pub fn log10_64(x_: f64) f64 { // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; - k += i32(hx >> 20) - 0x3FF; + k += @intCast(i32, hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); @@ -157,7 +157,7 @@ pub fn log10_64(x_: f64) f64 { // val_hi + val_lo ~ log10(1 + f) + k * log10(2) var val_hi = hi * ivln10hi; - const dk = f64(k); + const dk = @intToFloat(f64, k); const y = dk * log10_2hi; var val_lo = dk * log10_2lo + (lo + hi) * ivln10lo + lo * ivln10hi; diff --git a/std/math/log1p.zig b/std/math/log1p.zig index 57efdaf51c..7d3be6bb49 100644 --- a/std/math/log1p.zig +++ b/std/math/log1p.zig @@ -68,7 +68,7 @@ fn log1p_32(x: f32) f32 { const uf = 1 + x; var iu = @bitCast(u32, uf); iu += 0x3F800000 - 0x3F3504F3; - k = i32(iu >> 23) - 0x7F; + k = @intCast(i32, iu >> 23) - 0x7F; // correction to avoid underflow in c / u if (k < 25) { @@ -90,7 +90,7 @@ fn log1p_32(x: f32) f32 { const t2 = z * (Lg1 + w * Lg3); const R = t2 + t1; const hfsq = 0.5 * f * f; - const dk = f32(k); + const dk = @intToFloat(f32, k); return s * (hfsq + R) + (dk * ln2_lo + c) - hfsq + f + dk * ln2_hi; } @@ -107,7 +107,7 @@ fn log1p_64(x: f64) f64 { const Lg7: f64 = 1.479819860511658591e-01; var ix = @bitCast(u64, x); - var hx = u32(ix >> 32); + var hx = @intCast(u32, ix >> 32); var k: i32 = 1; var c: f64 = undefined; var f: f64 = undefined; @@ -145,9 +145,9 @@ fn log1p_64(x: f64) f64 { if (k != 0) { const uf = 1 + x; const hu = @bitCast(u64, uf); - var iu = u32(hu >> 32); + var iu = @intCast(u32, hu >> 32); iu += 0x3FF00000 - 0x3FE6A09E; - k = i32(iu >> 20) - 0x3FF; + k = @intCast(i32, iu >> 20) - 0x3FF; // correction to avoid underflow in c / u if (k < 54) { @@ -170,7 +170,7 @@ fn log1p_64(x: f64) f64 { const t1 = w * (Lg2 + w * (Lg4 + w * Lg6)); const t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7))); const R = t2 + t1; - const dk = f64(k); + const dk = @intToFloat(f64, k); return s * (hfsq + R) + (dk * ln2_lo + c) - hfsq + f + dk * ln2_hi; } diff --git a/std/math/log2.zig b/std/math/log2.zig index 2530519941..858f6ffa02 100644 --- a/std/math/log2.zig +++ b/std/math/log2.zig @@ -75,7 +75,7 @@ pub fn log2_32(x_: f32) f32 { // x into [sqrt(2) / 2, sqrt(2)] ix += 0x3F800000 - 0x3F3504F3; - k += i32(ix >> 23) - 0x7F; + k += @intCast(i32, ix >> 23) - 0x7F; ix = (ix & 0x007FFFFF) + 0x3F3504F3; x = @bitCast(f32, ix); @@ -93,7 +93,7 @@ pub fn log2_32(x_: f32) f32 { u &= 0xFFFFF000; hi = @bitCast(f32, u); const lo = f - hi - hfsq + s * (hfsq + R); - return (lo + hi) * ivln2lo + lo * ivln2hi + hi * ivln2hi + f32(k); + return (lo + hi) * ivln2lo + lo * ivln2hi + hi * ivln2hi + @intToFloat(f32, k); } pub fn log2_64(x_: f64) f64 { @@ -109,7 +109,7 @@ pub fn log2_64(x_: f64) f64 { var x = x_; var ix = @bitCast(u64, x); - var hx = u32(ix >> 32); + var hx = @intCast(u32, ix >> 32); var k: i32 = 0; if (hx < 0x00100000 or hx >> 31 != 0) { @@ -125,7 +125,7 @@ pub fn log2_64(x_: f64) f64 { // subnormal, scale x k -= 54; x *= 0x1.0p54; - hx = u32(@bitCast(u64, x) >> 32); + hx = @intCast(u32, @bitCast(u64, x) >> 32); } else if (hx >= 0x7FF00000) { return x; } else if (hx == 0x3FF00000 and ix << 32 == 0) { @@ -134,7 +134,7 @@ pub fn log2_64(x_: f64) f64 { // x into [sqrt(2) / 2, sqrt(2)] hx += 0x3FF00000 - 0x3FE6A09E; - k += i32(hx >> 20) - 0x3FF; + k += @intCast(i32, hx >> 20) - 0x3FF; hx = (hx & 0x000FFFFF) + 0x3FE6A09E; ix = (u64(hx) << 32) | (ix & 0xFFFFFFFF); x = @bitCast(f64, ix); @@ -159,7 +159,7 @@ pub fn log2_64(x_: f64) f64 { var val_lo = (lo + hi) * ivln2lo + lo * ivln2hi; // spadd(val_hi, val_lo, y) - const y = f64(k); + const y = @intToFloat(f64, k); const ww = y + val_hi; val_lo += (y - ww) + val_hi; val_hi = ww; diff --git a/std/math/modf.zig b/std/math/modf.zig index a6606ce34c..b6dd78f022 100644 --- a/std/math/modf.zig +++ b/std/math/modf.zig @@ -29,7 +29,7 @@ fn modf32(x: f32) modf32_result { var result: modf32_result = undefined; const u = @bitCast(u32, x); - const e = i32((u >> 23) & 0xFF) - 0x7F; + const e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; const us = u & 0x80000000; // TODO: Shouldn't need this. @@ -57,7 +57,7 @@ fn modf32(x: f32) modf32_result { return result; } - const mask = u32(0x007FFFFF) >> u5(e); + const mask = u32(0x007FFFFF) >> @intCast(u5, e); if (u & mask == 0) { result.ipart = x; result.fpart = @bitCast(f32, us); @@ -74,7 +74,7 @@ fn modf64(x: f64) modf64_result { var result: modf64_result = undefined; const u = @bitCast(u64, x); - const e = i32((u >> 52) & 0x7FF) - 0x3FF; + const e = @intCast(i32, (u >> 52) & 0x7FF) - 0x3FF; const us = u & (1 << 63); if (math.isInf(x)) { @@ -101,7 +101,7 @@ fn modf64(x: f64) modf64_result { return result; } - const mask = u64(@maxValue(u64) >> 12) >> u6(e); + const mask = u64(@maxValue(u64) >> 12) >> @intCast(u6, e); if (u & mask == 0) { result.ipart = x; result.fpart = @bitCast(f64, us); diff --git a/std/math/pow.zig b/std/math/pow.zig index dfe4fc09d6..7fc334c06b 100644 --- a/std/math/pow.zig +++ b/std/math/pow.zig @@ -146,7 +146,7 @@ pub fn pow(comptime T: type, x: T, y: T) T { var xe = r2.exponent; var x1 = r2.significand; - var i = i32(yi); + var i = @floatToInt(i32, yi); while (i != 0) : (i >>= 1) { if (i & 1 == 1) { a1 *= x1; @@ -171,7 +171,7 @@ pub fn pow(comptime T: type, x: T, y: T) T { fn isOddInteger(x: f64) bool { const r = math.modf(x); - return r.fpart == 0.0 and i64(r.ipart) & 1 == 1; + return r.fpart == 0.0 and @floatToInt(i64, r.ipart) & 1 == 1; } test "math.pow" { diff --git a/std/math/scalbn.zig b/std/math/scalbn.zig index deb5d989d2..f72c7e866f 100644 --- a/std/math/scalbn.zig +++ b/std/math/scalbn.zig @@ -37,7 +37,7 @@ fn scalbn32(x: f32, n_: i32) f32 { } } - const u = u32(n +% 0x7F) << 23; + const u = @intCast(u32, n +% 0x7F) << 23; return y * @bitCast(f32, u); } @@ -67,7 +67,7 @@ fn scalbn64(x: f64, n_: i32) f64 { } } - const u = u64(n +% 0x3FF) << 52; + const u = @intCast(u64, n +% 0x3FF) << 52; return y * @bitCast(f64, u); } diff --git a/std/math/sin.zig b/std/math/sin.zig index 21c324e444..3796d74812 100644 --- a/std/math/sin.zig +++ b/std/math/sin.zig @@ -60,7 +60,7 @@ fn sin32(x_: f32) f32 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; @@ -112,7 +112,7 @@ fn sin64(x_: f64) f64 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; diff --git a/std/math/sinh.zig b/std/math/sinh.zig index 85c9ae979b..bb3af280ab 100644 --- a/std/math/sinh.zig +++ b/std/math/sinh.zig @@ -57,7 +57,7 @@ fn sinh64(x: f64) f64 { @setFloatMode(this, @import("builtin").FloatMode.Strict); const u = @bitCast(u64, x); - const w = u32(u >> 32); + const w = @intCast(u32, u >> 32); const ax = @bitCast(f64, u & (@maxValue(u64) >> 1)); if (x == 0.0 or math.isNan(x)) { diff --git a/std/math/sqrt.zig b/std/math/sqrt.zig index 7a3ddb3b96..599008acff 100644 --- a/std/math/sqrt.zig +++ b/std/math/sqrt.zig @@ -99,7 +99,7 @@ fn sqrt_int(comptime T: type, value: T) @IntType(false, T.bit_count / 2) { } const ResultType = @IntType(false, T.bit_count / 2); - return ResultType(res); + return @intCast(ResultType, res); } test "math.sqrt_int" { diff --git a/std/math/tan.zig b/std/math/tan.zig index f578cf8156..ff3ed06186 100644 --- a/std/math/tan.zig +++ b/std/math/tan.zig @@ -53,7 +53,7 @@ fn tan32(x_: f32) f32 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; @@ -102,7 +102,7 @@ fn tan64(x_: f64) f64 { } var y = math.floor(x * m4pi); - var j = i64(y); + var j = @floatToInt(i64, y); if (j & 1 == 1) { j += 1; diff --git a/std/math/tanh.zig b/std/math/tanh.zig index c1f5a0ca46..6204b2a374 100644 --- a/std/math/tanh.zig +++ b/std/math/tanh.zig @@ -68,7 +68,7 @@ fn tanh32(x: f32) f32 { fn tanh64(x: f64) f64 { const u = @bitCast(u64, x); - const w = u32(u >> 32); + const w = @intCast(u32, u >> 32); const ax = @bitCast(f64, u & (@maxValue(u64) >> 1)); var t: f64 = undefined; @@ -100,7 +100,7 @@ fn tanh64(x: f64) f64 { } // |x| is subnormal else { - math.forceEval(f32(x)); + math.forceEval(@floatCast(f32, x)); t = x; } diff --git a/std/math/trunc.zig b/std/math/trunc.zig index 54aa6943f7..92d5bfebc5 100644 --- a/std/math/trunc.zig +++ b/std/math/trunc.zig @@ -19,7 +19,7 @@ pub fn trunc(x: var) @typeOf(x) { fn trunc32(x: f32) f32 { const u = @bitCast(u32, x); - var e = i32(((u >> 23) & 0xFF)) - 0x7F + 9; + var e = @intCast(i32, ((u >> 23) & 0xFF)) - 0x7F + 9; var m: u32 = undefined; if (e >= 23 + 9) { @@ -29,7 +29,7 @@ fn trunc32(x: f32) f32 { e = 1; } - m = u32(@maxValue(u32)) >> u5(e); + m = u32(@maxValue(u32)) >> @intCast(u5, e); if (u & m == 0) { return x; } else { @@ -40,7 +40,7 @@ fn trunc32(x: f32) f32 { fn trunc64(x: f64) f64 { const u = @bitCast(u64, x); - var e = i32(((u >> 52) & 0x7FF)) - 0x3FF + 12; + var e = @intCast(i32, ((u >> 52) & 0x7FF)) - 0x3FF + 12; var m: u64 = undefined; if (e >= 52 + 12) { @@ -50,7 +50,7 @@ fn trunc64(x: f64) f64 { e = 1; } - m = u64(@maxValue(u64)) >> u6(e); + m = u64(@maxValue(u64)) >> @intCast(u6, e); if (u & m == 0) { return x; } else { diff --git a/std/mem.zig b/std/mem.zig index 10b3eb8fef..b02589b0dd 100644 --- a/std/mem.zig +++ b/std/mem.zig @@ -334,7 +334,7 @@ pub fn readInt(bytes: []const u8, comptime T: type, endian: builtin.Endian) T { builtin.Endian.Little => { const ShiftType = math.Log2Int(T); for (bytes) |b, index| { - result = result | (T(b) << ShiftType(index * 8)); + result = result | (T(b) << @intCast(ShiftType, index * 8)); } }, } diff --git a/std/os/child_process.zig b/std/os/child_process.zig index 1e3a732498..3a0fa7f461 100644 --- a/std/os/child_process.zig +++ b/std/os/child_process.zig @@ -413,7 +413,7 @@ pub const ChildProcess = struct { } // we are the parent - const pid = i32(pid_result); + const pid = @intCast(i32, pid_result); if (self.stdin_behavior == StdIo.Pipe) { self.stdin = os.File.openHandle(stdin_pipe[1]); } else { diff --git a/std/os/darwin.zig b/std/os/darwin.zig index a835959103..15e5608343 100644 --- a/std/os/darwin.zig +++ b/std/os/darwin.zig @@ -290,7 +290,7 @@ pub fn WIFSIGNALED(x: i32) bool { /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { const signed_r = @bitCast(isize, r); - return if (signed_r > -4096 and signed_r < 0) usize(-signed_r) else 0; + return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0; } pub fn close(fd: i32) usize { @@ -339,7 +339,14 @@ pub fn write(fd: i32, buf: [*]const u8, nbyte: usize) usize { } pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { - const ptr_result = c.mmap(@ptrCast(*c_void, address), length, @bitCast(c_int, c_uint(prot)), @bitCast(c_int, c_uint(flags)), fd, offset); + const ptr_result = c.mmap( + @ptrCast(*c_void, address), + length, + @bitCast(c_int, @intCast(c_uint, prot)), + @bitCast(c_int, c_uint(flags)), + fd, + offset, + ); const isize_result = @bitCast(isize, @ptrToInt(ptr_result)); return errnoWrap(isize_result); } diff --git a/std/os/file.zig b/std/os/file.zig index 7e05501831..055f185121 100644 --- a/std/os/file.zig +++ b/std/os/file.zig @@ -266,7 +266,7 @@ pub const File = struct { pub fn getEndPos(self: *File) !usize { if (is_posix) { const stat = try os.posixFStat(self.handle); - return usize(stat.size); + return @intCast(usize, stat.size); } else if (is_windows) { var file_size: windows.LARGE_INTEGER = undefined; if (windows.GetFileSizeEx(self.handle, &file_size) == 0) { @@ -277,7 +277,7 @@ pub const File = struct { } if (file_size < 0) return error.Overflow; - return math.cast(usize, u64(file_size)); + return math.cast(usize, @intCast(u64, file_size)); } else { @compileError("TODO support getEndPos on this OS"); } @@ -343,7 +343,7 @@ pub const File = struct { } else if (is_windows) { var index: usize = 0; while (index < buffer.len) { - const want_read_count = windows.DWORD(math.min(windows.DWORD(@maxValue(windows.DWORD)), buffer.len - index)); + const want_read_count = @intCast(windows.DWORD, math.min(windows.DWORD(@maxValue(windows.DWORD)), buffer.len - index)); var amt_read: windows.DWORD = undefined; if (windows.ReadFile(self.handle, @ptrCast(*c_void, buffer.ptr + index), want_read_count, &amt_read, null) == 0) { const err = windows.GetLastError(); diff --git a/std/os/index.zig b/std/os/index.zig index fb4605fce0..f1c3ab2128 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -126,7 +126,7 @@ pub fn getRandomBytes(buf: []u8) !void { } defer _ = windows.CryptReleaseContext(hCryptProv, 0); - if (windows.CryptGenRandom(hCryptProv, windows.DWORD(buf.len), buf.ptr) == 0) { + if (windows.CryptGenRandom(hCryptProv, @intCast(windows.DWORD, buf.len), buf.ptr) == 0) { const err = windows.GetLastError(); return switch (err) { else => unexpectedErrorWindows(err), @@ -343,7 +343,7 @@ pub fn posixOpenC(file_path: [*]const u8, flags: u32, perm: usize) !i32 { else => return unexpectedErrorPosix(err), } } - return i32(result); + return @intCast(i32, result); } } @@ -586,7 +586,7 @@ pub fn getCwd(allocator: *Allocator) ![]u8 { errdefer allocator.free(buf); while (true) { - const result = windows.GetCurrentDirectoryA(windows.WORD(buf.len), buf.ptr); + const result = windows.GetCurrentDirectoryA(@intCast(windows.WORD, buf.len), buf.ptr); if (result == 0) { const err = windows.GetLastError(); @@ -2019,7 +2019,7 @@ pub fn posixSocket(domain: u32, socket_type: u32, protocol: u32) !i32 { const rc = posix.socket(domain, socket_type, protocol); const err = posix.getErrno(rc); switch (err) { - 0 => return i32(rc), + 0 => return @intCast(i32, rc), posix.EACCES => return PosixSocketError.PermissionDenied, posix.EAFNOSUPPORT => return PosixSocketError.AddressFamilyNotSupported, posix.EINVAL => return PosixSocketError.ProtocolFamilyNotAvailable, @@ -2183,7 +2183,7 @@ pub fn posixAccept(fd: i32, addr: *posix.sockaddr, flags: u32) PosixAcceptError! const rc = posix.accept4(fd, addr, &sockaddr_size, flags); const err = posix.getErrno(rc); switch (err) { - 0 => return i32(rc), + 0 => return @intCast(i32, rc), posix.EINTR => continue, else => return unexpectedErrorPosix(err), @@ -2226,7 +2226,7 @@ pub fn linuxEpollCreate(flags: u32) LinuxEpollCreateError!i32 { const rc = posix.epoll_create1(flags); const err = posix.getErrno(rc); switch (err) { - 0 => return i32(rc), + 0 => return @intCast(i32, rc), else => return unexpectedErrorPosix(err), posix.EINVAL => return LinuxEpollCreateError.InvalidSyscall, @@ -2296,7 +2296,7 @@ pub fn linuxEpollCtl(epfd: i32, op: u32, fd: i32, event: *linux.epoll_event) Lin pub fn linuxEpollWait(epfd: i32, events: []linux.epoll_event, timeout: i32) usize { while (true) { - const rc = posix.epoll_wait(epfd, events.ptr, u32(events.len), timeout); + const rc = posix.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout); const err = posix.getErrno(rc); switch (err) { 0 => return rc, @@ -2661,7 +2661,7 @@ pub fn spawnThread(context: var, comptime startFn: var) SpawnThreadError!*Thread posix.EAGAIN => return SpawnThreadError.SystemResources, posix.EPERM => unreachable, posix.EINVAL => unreachable, - else => return unexpectedErrorPosix(usize(err)), + else => return unexpectedErrorPosix(@intCast(usize, err)), } } else if (builtin.os == builtin.Os.linux) { // use linux API directly. TODO use posix.CLONE_SETTLS and initialize thread local storage correctly diff --git a/std/os/linux/index.zig b/std/os/linux/index.zig index 0e77371ec2..65aa659c82 100644 --- a/std/os/linux/index.zig +++ b/std/os/linux/index.zig @@ -642,7 +642,7 @@ pub fn WIFEXITED(s: i32) bool { return WTERMSIG(s) == 0; } pub fn WIFSTOPPED(s: i32) bool { - return (u16)(((unsigned(s) & 0xffff) *% 0x10001) >> 8) > 0x7f00; + return @intCast(u16, ((unsigned(s) & 0xffff) *% 0x10001) >> 8) > 0x7f00; } pub fn WIFSIGNALED(s: i32) bool { return (unsigned(s) & 0xffff) -% 1 < 0xff; @@ -658,11 +658,11 @@ pub const winsize = extern struct { /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { const signed_r = @bitCast(isize, r); - return if (signed_r > -4096 and signed_r < 0) usize(-signed_r) else 0; + return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0; } pub fn dup2(old: i32, new: i32) usize { - return syscall2(SYS_dup2, usize(old), usize(new)); + return syscall2(SYS_dup2, @intCast(usize, old), @intCast(usize, new)); } // TODO https://github.com/ziglang/zig/issues/265 @@ -693,12 +693,12 @@ pub fn getcwd(buf: [*]u8, size: usize) usize { } pub fn getdents(fd: i32, dirp: [*]u8, count: usize) usize { - return syscall3(SYS_getdents, usize(fd), @ptrToInt(dirp), count); + return syscall3(SYS_getdents, @intCast(usize, fd), @ptrToInt(dirp), count); } pub fn isatty(fd: i32) bool { var wsz: winsize = undefined; - return syscall3(SYS_ioctl, usize(fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0; + return syscall3(SYS_ioctl, @intCast(usize, fd), TIOCGWINSZ, @ptrToInt(&wsz)) == 0; } // TODO https://github.com/ziglang/zig/issues/265 @@ -727,7 +727,7 @@ pub fn umount2(special: [*]const u8, flags: u32) usize { } pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { - return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, usize(fd), @bitCast(usize, offset)); + return syscall6(SYS_mmap, @ptrToInt(address), length, prot, flags, @intCast(usize, fd), @bitCast(usize, offset)); } pub fn munmap(address: usize, length: usize) usize { @@ -735,7 +735,7 @@ pub fn munmap(address: usize, length: usize) usize { } pub fn read(fd: i32, buf: [*]u8, count: usize) usize { - return syscall3(SYS_read, usize(fd), @ptrToInt(buf), count); + return syscall3(SYS_read, @intCast(usize, fd), @ptrToInt(buf), count); } // TODO https://github.com/ziglang/zig/issues/265 @@ -749,7 +749,7 @@ pub fn symlink(existing: [*]const u8, new: [*]const u8) usize { } pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: usize) usize { - return syscall4(SYS_pread, usize(fd), @ptrToInt(buf), count, offset); + return syscall4(SYS_pread, @intCast(usize, fd), @ptrToInt(buf), count, offset); } // TODO https://github.com/ziglang/zig/issues/265 @@ -766,11 +766,11 @@ pub fn pipe2(fd: *[2]i32, flags: usize) usize { } pub fn write(fd: i32, buf: [*]const u8, count: usize) usize { - return syscall3(SYS_write, usize(fd), @ptrToInt(buf), count); + return syscall3(SYS_write, @intCast(usize, fd), @ptrToInt(buf), count); } pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize { - return syscall4(SYS_pwrite, usize(fd), @ptrToInt(buf), count, offset); + return syscall4(SYS_pwrite, @intCast(usize, fd), @ptrToInt(buf), count, offset); } // TODO https://github.com/ziglang/zig/issues/265 @@ -790,7 +790,7 @@ pub fn create(path: [*]const u8, perm: usize) usize { // TODO https://github.com/ziglang/zig/issues/265 pub fn openat(dirfd: i32, path: [*]const u8, flags: usize, mode: usize) usize { - return syscall4(SYS_openat, usize(dirfd), @ptrToInt(path), flags, mode); + return syscall4(SYS_openat, @intCast(usize, dirfd), @ptrToInt(path), flags, mode); } /// See also `clone` (from the arch-specific include) @@ -804,11 +804,11 @@ pub fn clone2(flags: usize, child_stack_ptr: usize) usize { } pub fn close(fd: i32) usize { - return syscall1(SYS_close, usize(fd)); + return syscall1(SYS_close, @intCast(usize, fd)); } pub fn lseek(fd: i32, offset: isize, ref_pos: usize) usize { - return syscall3(SYS_lseek, usize(fd), @bitCast(usize, offset), ref_pos); + return syscall3(SYS_lseek, @intCast(usize, fd), @bitCast(usize, offset), ref_pos); } pub fn exit(status: i32) noreturn { @@ -817,11 +817,11 @@ pub fn exit(status: i32) noreturn { } pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize { - return syscall3(SYS_getrandom, @ptrToInt(buf), count, usize(flags)); + return syscall3(SYS_getrandom, @ptrToInt(buf), count, @intCast(usize, flags)); } pub fn kill(pid: i32, sig: i32) usize { - return syscall2(SYS_kill, @bitCast(usize, isize(pid)), usize(sig)); + return syscall2(SYS_kill, @bitCast(usize, isize(pid)), @intCast(usize, sig)); } // TODO https://github.com/ziglang/zig/issues/265 @@ -999,8 +999,8 @@ pub const empty_sigset = []usize{0} ** sigset_t.len; pub fn raise(sig: i32) usize { var set: sigset_t = undefined; blockAppSignals(&set); - const tid = i32(syscall0(SYS_gettid)); - const ret = syscall2(SYS_tkill, usize(tid), usize(sig)); + const tid = @intCast(i32, syscall0(SYS_gettid)); + const ret = syscall2(SYS_tkill, @intCast(usize, tid), @intCast(usize, sig)); restoreSignals(&set); return ret; } @@ -1019,12 +1019,12 @@ fn restoreSignals(set: *sigset_t) void { pub fn sigaddset(set: *sigset_t, sig: u6) void { const s = sig - 1; - (set.*)[usize(s) / usize.bit_count] |= usize(1) << (s & (usize.bit_count - 1)); + (set.*)[@intCast(usize, s) / usize.bit_count] |= @intCast(usize, 1) << (s & (usize.bit_count - 1)); } pub fn sigismember(set: *const sigset_t, sig: u6) bool { const s = sig - 1; - return ((set.*)[usize(s) / usize.bit_count] & (usize(1) << (s & (usize.bit_count - 1)))) != 0; + return ((set.*)[@intCast(usize, s) / usize.bit_count] & (@intCast(usize, 1) << (s & (usize.bit_count - 1)))) != 0; } pub const in_port_t = u16; @@ -1057,11 +1057,11 @@ pub const iovec = extern struct { }; pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { - return syscall3(SYS_getsockname, usize(fd), @ptrToInt(addr), @ptrToInt(len)); + return syscall3(SYS_getsockname, @intCast(usize, fd), @ptrToInt(addr), @ptrToInt(len)); } pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { - return syscall3(SYS_getpeername, usize(fd), @ptrToInt(addr), @ptrToInt(len)); + return syscall3(SYS_getpeername, @intCast(usize, fd), @ptrToInt(addr), @ptrToInt(len)); } pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { @@ -1069,47 +1069,47 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize { } pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize { - return syscall5(SYS_setsockopt, usize(fd), level, optname, usize(optval), @ptrToInt(optlen)); + return syscall5(SYS_setsockopt, @intCast(usize, fd), level, optname, @intCast(usize, optval), @ptrToInt(optlen)); } pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize { - return syscall5(SYS_getsockopt, usize(fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); + return syscall5(SYS_getsockopt, @intCast(usize, fd), level, optname, @ptrToInt(optval), @ptrToInt(optlen)); } pub fn sendmsg(fd: i32, msg: *const msghdr, flags: u32) usize { - return syscall3(SYS_sendmsg, usize(fd), @ptrToInt(msg), flags); + return syscall3(SYS_sendmsg, @intCast(usize, fd), @ptrToInt(msg), flags); } pub fn connect(fd: i32, addr: *const sockaddr, len: socklen_t) usize { - return syscall3(SYS_connect, usize(fd), @ptrToInt(addr), usize(len)); + return syscall3(SYS_connect, @intCast(usize, fd), @ptrToInt(addr), @intCast(usize, len)); } pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize { - return syscall3(SYS_recvmsg, usize(fd), @ptrToInt(msg), flags); + return syscall3(SYS_recvmsg, @intCast(usize, fd), @ptrToInt(msg), flags); } pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize { - return syscall6(SYS_recvfrom, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); + return syscall6(SYS_recvfrom, @intCast(usize, fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen)); } pub fn shutdown(fd: i32, how: i32) usize { - return syscall2(SYS_shutdown, usize(fd), usize(how)); + return syscall2(SYS_shutdown, @intCast(usize, fd), @intCast(usize, how)); } pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize { - return syscall3(SYS_bind, usize(fd), @ptrToInt(addr), usize(len)); + return syscall3(SYS_bind, @intCast(usize, fd), @ptrToInt(addr), @intCast(usize, len)); } pub fn listen(fd: i32, backlog: u32) usize { - return syscall2(SYS_listen, usize(fd), backlog); + return syscall2(SYS_listen, @intCast(usize, fd), backlog); } pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize { - return syscall6(SYS_sendto, usize(fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), usize(alen)); + return syscall6(SYS_sendto, @intCast(usize, fd), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen)); } pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize { - return syscall4(SYS_socketpair, usize(domain), usize(socket_type), usize(protocol), @ptrToInt(*fd[0])); + return syscall4(SYS_socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(*fd[0])); } pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { @@ -1117,11 +1117,11 @@ pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize { } pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags: u32) usize { - return syscall4(SYS_accept4, usize(fd), @ptrToInt(addr), @ptrToInt(len), flags); + return syscall4(SYS_accept4, @intCast(usize, fd), @ptrToInt(addr), @ptrToInt(len), flags); } pub fn fstat(fd: i32, stat_buf: *Stat) usize { - return syscall2(SYS_fstat, usize(fd), @ptrToInt(stat_buf)); + return syscall2(SYS_fstat, @intCast(usize, fd), @ptrToInt(stat_buf)); } // TODO https://github.com/ziglang/zig/issues/265 @@ -1214,15 +1214,15 @@ pub fn epoll_create1(flags: usize) usize { } pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: *epoll_event) usize { - return syscall4(SYS_epoll_ctl, usize(epoll_fd), usize(op), usize(fd), @ptrToInt(ev)); + return syscall4(SYS_epoll_ctl, @intCast(usize, epoll_fd), @intCast(usize, op), @intCast(usize, fd), @ptrToInt(ev)); } pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize { - return syscall4(SYS_epoll_wait, usize(epoll_fd), @ptrToInt(events), usize(maxevents), usize(timeout)); + return syscall4(SYS_epoll_wait, @intCast(usize, epoll_fd), @ptrToInt(events), @intCast(usize, maxevents), @intCast(usize, timeout)); } pub fn timerfd_create(clockid: i32, flags: u32) usize { - return syscall2(SYS_timerfd_create, usize(clockid), usize(flags)); + return syscall2(SYS_timerfd_create, @intCast(usize, clockid), @intCast(usize, flags)); } pub const itimerspec = extern struct { @@ -1231,11 +1231,11 @@ pub const itimerspec = extern struct { }; pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize { - return syscall2(SYS_timerfd_gettime, usize(fd), @ptrToInt(curr_value)); + return syscall2(SYS_timerfd_gettime, @intCast(usize, fd), @ptrToInt(curr_value)); } pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize { - return syscall4(SYS_timerfd_settime, usize(fd), usize(flags), @ptrToInt(new_value), @ptrToInt(old_value)); + return syscall4(SYS_timerfd_settime, @intCast(usize, fd), @intCast(usize, flags), @ptrToInt(new_value), @ptrToInt(old_value)); } pub const _LINUX_CAPABILITY_VERSION_1 = 0x19980330; @@ -1345,7 +1345,7 @@ pub const cap_user_data_t = extern struct { }; pub fn unshare(flags: usize) usize { - return syscall1(SYS_unshare, usize(flags)); + return syscall1(SYS_unshare, @intCast(usize, flags)); } pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize { diff --git a/std/os/linux/test.zig b/std/os/linux/test.zig index 948a3ac96b..e7dae3a584 100644 --- a/std/os/linux/test.zig +++ b/std/os/linux/test.zig @@ -21,7 +21,7 @@ test "timer" { .it_value = time_interval, }; - err = linux.timerfd_settime(i32(timer_fd), 0, &new_time, null); + err = linux.timerfd_settime(@intCast(i32, timer_fd), 0, &new_time, null); assert(err == 0); var event = linux.epoll_event{ @@ -29,12 +29,12 @@ test "timer" { .data = linux.epoll_data{ .ptr = 0 }, }; - err = linux.epoll_ctl(i32(epoll_fd), linux.EPOLL_CTL_ADD, i32(timer_fd), &event); + err = linux.epoll_ctl(@intCast(i32, epoll_fd), linux.EPOLL_CTL_ADD, @intCast(i32, timer_fd), &event); assert(err == 0); const events_one: linux.epoll_event = undefined; var events = []linux.epoll_event{events_one} ** 8; // TODO implicit cast from *[N]T to [*]T - err = linux.epoll_wait(i32(epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1); + err = linux.epoll_wait(@intCast(i32, epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1); } diff --git a/std/os/linux/vdso.zig b/std/os/linux/vdso.zig index cbd0cd1df5..a78e3370e6 100644 --- a/std/os/linux/vdso.zig +++ b/std/os/linux/vdso.zig @@ -62,8 +62,8 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { var i: usize = 0; while (i < hashtab[1]) : (i += 1) { - if (0 == (u32(1) << u5(syms[i].st_info & 0xf) & OK_TYPES)) continue; - if (0 == (u32(1) << u5(syms[i].st_info >> 4) & OK_BINDS)) continue; + if (0 == (u32(1) << @intCast(u5, syms[i].st_info & 0xf) & OK_TYPES)) continue; + if (0 == (u32(1) << @intCast(u5, syms[i].st_info >> 4) & OK_BINDS)) continue; if (0 == syms[i].st_shndx) continue; if (!mem.eql(u8, name, cstr.toSliceConst(strings + syms[i].st_name))) continue; if (maybe_versym) |versym| { diff --git a/std/os/time.zig b/std/os/time.zig index ffb506cd7d..73ba5bba82 100644 --- a/std/os/time.zig +++ b/std/os/time.zig @@ -14,12 +14,12 @@ pub const epoch = @import("epoch.zig"); pub fn sleep(seconds: usize, nanoseconds: usize) void { switch (builtin.os) { Os.linux, Os.macosx, Os.ios => { - posixSleep(u63(seconds), u63(nanoseconds)); + posixSleep(@intCast(u63, seconds), @intCast(u63, nanoseconds)); }, Os.windows => { const ns_per_ms = ns_per_s / ms_per_s; const milliseconds = seconds * ms_per_s + nanoseconds / ns_per_ms; - windows.Sleep(windows.DWORD(milliseconds)); + windows.Sleep(@intCast(windows.DWORD, milliseconds)); }, else => @compileError("Unsupported OS"), } @@ -83,8 +83,8 @@ fn milliTimestampDarwin() u64 { var tv: darwin.timeval = undefined; var err = darwin.gettimeofday(&tv, null); debug.assert(err == 0); - const sec_ms = u64(tv.tv_sec) * ms_per_s; - const usec_ms = @divFloor(u64(tv.tv_usec), us_per_s / ms_per_s); + const sec_ms = @intCast(u64, tv.tv_sec) * ms_per_s; + const usec_ms = @divFloor(@intCast(u64, tv.tv_usec), us_per_s / ms_per_s); return u64(sec_ms) + u64(usec_ms); } @@ -95,8 +95,8 @@ fn milliTimestampPosix() u64 { var ts: posix.timespec = undefined; const err = posix.clock_gettime(posix.CLOCK_REALTIME, &ts); debug.assert(err == 0); - const sec_ms = u64(ts.tv_sec) * ms_per_s; - const nsec_ms = @divFloor(u64(ts.tv_nsec), ns_per_s / ms_per_s); + const sec_ms = @intCast(u64, ts.tv_sec) * ms_per_s; + const nsec_ms = @divFloor(@intCast(u64, ts.tv_nsec), ns_per_s / ms_per_s); return sec_ms + nsec_ms; } @@ -162,13 +162,13 @@ pub const Timer = struct { var freq: i64 = undefined; var err = windows.QueryPerformanceFrequency(&freq); if (err == windows.FALSE) return error.TimerUnsupported; - self.frequency = u64(freq); + self.frequency = @intCast(u64, freq); self.resolution = @divFloor(ns_per_s, self.frequency); var start_time: i64 = undefined; err = windows.QueryPerformanceCounter(&start_time); debug.assert(err != windows.FALSE); - self.start_time = u64(start_time); + self.start_time = @intCast(u64, start_time); }, Os.linux => { //On Linux, seccomp can do arbitrary things to our ability to call @@ -184,12 +184,12 @@ pub const Timer = struct { posix.EINVAL => return error.TimerUnsupported, else => return std.os.unexpectedErrorPosix(errno), } - self.resolution = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec); + self.resolution = @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec); result = posix.clock_gettime(monotonic_clock_id, &ts); errno = posix.getErrno(result); if (errno != 0) return std.os.unexpectedErrorPosix(errno); - self.start_time = u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec); + self.start_time = @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec); }, Os.macosx, Os.ios => { darwin.mach_timebase_info(&self.frequency); @@ -236,7 +236,7 @@ pub const Timer = struct { var result: i64 = undefined; var err = windows.QueryPerformanceCounter(&result); debug.assert(err != windows.FALSE); - return u64(result); + return @intCast(u64, result); } fn clockDarwin() u64 { @@ -247,7 +247,7 @@ pub const Timer = struct { var ts: posix.timespec = undefined; var result = posix.clock_gettime(monotonic_clock_id, &ts); debug.assert(posix.getErrno(result) == 0); - return u64(ts.tv_sec) * u64(ns_per_s) + u64(ts.tv_nsec); + return @intCast(u64, ts.tv_sec) * u64(ns_per_s) + @intCast(u64, ts.tv_nsec); } }; diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index 88a9e7952e..cb4788ba17 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -42,7 +42,7 @@ pub const WriteError = error{ }; pub fn windowsWrite(handle: windows.HANDLE, bytes: []const u8) WriteError!void { - if (windows.WriteFile(handle, @ptrCast(*const c_void, bytes.ptr), u32(bytes.len), null, null) == 0) { + if (windows.WriteFile(handle, @ptrCast(*const c_void, bytes.ptr), @intCast(u32, bytes.len), null, null) == 0) { const err = windows.GetLastError(); return switch (err) { windows.ERROR.INVALID_USER_BUFFER => WriteError.SystemResources, @@ -68,7 +68,12 @@ pub fn windowsIsCygwinPty(handle: windows.HANDLE) bool { const size = @sizeOf(windows.FILE_NAME_INFO); var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = []u8{0} ** (size + windows.MAX_PATH); - if (windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, @ptrCast(*c_void, &name_info_bytes[0]), u32(name_info_bytes.len)) == 0) { + if (windows.GetFileInformationByHandleEx( + handle, + windows.FileNameInfo, + @ptrCast(*c_void, &name_info_bytes[0]), + @intCast(u32, name_info_bytes.len), + ) == 0) { return true; } diff --git a/std/rand/index.zig b/std/rand/index.zig index 3a1a559cd9..13694f4c09 100644 --- a/std/rand/index.zig +++ b/std/rand/index.zig @@ -55,16 +55,16 @@ pub const Random = struct { if (T.is_signed) { const uint = @IntType(false, T.bit_count); if (start >= 0 and end >= 0) { - return T(r.range(uint, uint(start), uint(end))); + return @intCast(T, r.range(uint, @intCast(uint, start), @intCast(uint, end))); } else if (start < 0 and end < 0) { // Can't overflow because the range is over signed ints return math.negateCast(r.range(uint, math.absCast(end), math.absCast(start)) + 1) catch unreachable; } else if (start < 0 and end >= 0) { - const end_uint = uint(end); + const end_uint = @intCast(uint, end); const total_range = math.absCast(start) + end_uint; const value = r.range(uint, 0, total_range); const result = if (value < end_uint) x: { - break :x T(value); + break :x @intCast(T, value); } else if (value == end_uint) x: { break :x start; } else x: { @@ -213,9 +213,9 @@ pub const Pcg = struct { self.s = l *% default_multiplier +% (self.i | 1); const xor_s = @truncate(u32, ((l >> 18) ^ l) >> 27); - const rot = u32(l >> 59); + const rot = @intCast(u32, l >> 59); - return (xor_s >> u5(rot)) | (xor_s << u5((0 -% rot) & 31)); + return (xor_s >> @intCast(u5, rot)) | (xor_s << @intCast(u5, (0 -% rot) & 31)); } fn seed(self: *Pcg, init_s: u64) void { @@ -322,7 +322,7 @@ pub const Xoroshiro128 = struct { inline for (table) |entry| { var b: usize = 0; while (b < 64) : (b += 1) { - if ((entry & (u64(1) << u6(b))) != 0) { + if ((entry & (u64(1) << @intCast(u6, b))) != 0) { s0 ^= self.s[0]; s1 ^= self.s[1]; } @@ -667,13 +667,13 @@ test "Random range" { } fn testRange(r: *Random, start: i32, end: i32) void { - const count = usize(end - start); + const count = @intCast(usize, end - start); var values_buffer = []bool{false} ** 20; const values = values_buffer[0..count]; var i: usize = 0; while (i < count) { const value = r.range(i32, start, end); - const index = usize(value - start); + const index = @intCast(usize, value - start); if (!values[index]) { i += 1; values[index] = true; diff --git a/std/segmented_list.zig b/std/segmented_list.zig index 9f10f4d44a..6e3f32e9d6 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -104,7 +104,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } pub fn deinit(self: *Self) void { - self.freeShelves(ShelfIndex(self.dynamic_segments.len), 0); + self.freeShelves(@intCast(ShelfIndex, self.dynamic_segments.len), 0); self.allocator.free(self.dynamic_segments); self.* = undefined; } @@ -158,7 +158,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type /// Only grows capacity, or retains current capacity pub fn growCapacity(self: *Self, new_capacity: usize) !void { const new_cap_shelf_count = shelfCount(new_capacity); - const old_shelf_count = ShelfIndex(self.dynamic_segments.len); + const old_shelf_count = @intCast(ShelfIndex, self.dynamic_segments.len); if (new_cap_shelf_count > old_shelf_count) { self.dynamic_segments = try self.allocator.realloc([*]T, self.dynamic_segments, new_cap_shelf_count); var i = old_shelf_count; @@ -175,7 +175,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type /// Only shrinks capacity or retains current capacity pub fn shrinkCapacity(self: *Self, new_capacity: usize) void { if (new_capacity <= prealloc_item_count) { - const len = ShelfIndex(self.dynamic_segments.len); + const len = @intCast(ShelfIndex, self.dynamic_segments.len); self.freeShelves(len, 0); self.allocator.free(self.dynamic_segments); self.dynamic_segments = [][*]T{}; @@ -183,7 +183,7 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type } const new_cap_shelf_count = shelfCount(new_capacity); - const old_shelf_count = ShelfIndex(self.dynamic_segments.len); + const old_shelf_count = @intCast(ShelfIndex, self.dynamic_segments.len); assert(new_cap_shelf_count <= old_shelf_count); if (new_cap_shelf_count == old_shelf_count) { return; @@ -338,7 +338,7 @@ fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void { { var i: usize = 0; while (i < 100) : (i += 1) { - try list.push(i32(i + 1)); + try list.push(@intCast(i32, i + 1)); assert(list.len == i + 1); } } @@ -346,7 +346,7 @@ fn testSegmentedList(comptime prealloc: usize, allocator: *Allocator) !void { { var i: usize = 0; while (i < 100) : (i += 1) { - assert(list.at(i).* == i32(i + 1)); + assert(list.at(i).* == @intCast(i32, i + 1)); } } diff --git a/std/special/bootstrap.zig b/std/special/bootstrap.zig index dd37f1edb6..5c8a330a92 100644 --- a/std/special/bootstrap.zig +++ b/std/special/bootstrap.zig @@ -80,7 +80,7 @@ extern fn main(c_argc: i32, c_argv: [*][*]u8, c_envp: [*]?[*]u8) i32 { var env_count: usize = 0; while (c_envp[env_count] != null) : (env_count += 1) {} const envp = @ptrCast([*][*]u8, c_envp)[0..env_count]; - return callMainWithArgs(usize(c_argc), c_argv, envp); + return callMainWithArgs(@intCast(usize, c_argc), c_argv, envp); } fn callMain() u8 { diff --git a/std/special/builtin.zig b/std/special/builtin.zig index e97b0a89e4..07e735d931 100644 --- a/std/special/builtin.zig +++ b/std/special/builtin.zig @@ -135,9 +135,9 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { const mask = if (T == f32) 0xff else 0x7ff; var ux = @bitCast(uint, x); var uy = @bitCast(uint, y); - var ex = i32((ux >> digits) & mask); - var ey = i32((uy >> digits) & mask); - const sx = if (T == f32) u32(ux & 0x80000000) else i32(ux >> bits_minus_1); + var ex = @intCast(i32, (ux >> digits) & mask); + var ey = @intCast(i32, (uy >> digits) & mask); + const sx = if (T == f32) @intCast(u32, ux & 0x80000000) else @intCast(i32, ux >> bits_minus_1); var i: uint = undefined; if (uy << 1 == 0 or isNan(uint, uy) or ex == mask) @@ -156,7 +156,7 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { ex -= 1; i <<= 1; }) {} - ux <<= log2uint(@bitCast(u32, -ex + 1)); + ux <<= @intCast(log2uint, @bitCast(u32, -ex + 1)); } else { ux &= @maxValue(uint) >> exp_bits; ux |= 1 << digits; @@ -167,7 +167,7 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { ey -= 1; i <<= 1; }) {} - uy <<= log2uint(@bitCast(u32, -ey + 1)); + uy <<= @intCast(log2uint, @bitCast(u32, -ey + 1)); } else { uy &= @maxValue(uint) >> exp_bits; uy |= 1 << digits; @@ -199,12 +199,12 @@ fn generic_fmod(comptime T: type, x: T, y: T) T { ux -%= 1 << digits; ux |= uint(@bitCast(u32, ex)) << digits; } else { - ux >>= log2uint(@bitCast(u32, -ex + 1)); + ux >>= @intCast(log2uint, @bitCast(u32, -ex + 1)); } if (T == f32) { ux |= sx; } else { - ux |= uint(sx) << bits_minus_1; + ux |= @intCast(uint, sx) << bits_minus_1; } return @bitCast(T, ux); } @@ -227,8 +227,8 @@ export fn sqrt(x: f64) f64 { const sign: u32 = 0x80000000; const u = @bitCast(u64, x); - var ix0 = u32(u >> 32); - var ix1 = u32(u & 0xFFFFFFFF); + var ix0 = @intCast(u32, u >> 32); + var ix1 = @intCast(u32, u & 0xFFFFFFFF); // sqrt(nan) = nan, sqrt(+inf) = +inf, sqrt(-inf) = nan if (ix0 & 0x7FF00000 == 0x7FF00000) { @@ -245,7 +245,7 @@ export fn sqrt(x: f64) f64 { } // normalize x - var m = i32(ix0 >> 20); + var m = @intCast(i32, ix0 >> 20); if (m == 0) { // subnormal while (ix0 == 0) { @@ -259,9 +259,9 @@ export fn sqrt(x: f64) f64 { while (ix0 & 0x00100000 == 0) : (i += 1) { ix0 <<= 1; } - m -= i32(i) - 1; - ix0 |= ix1 >> u5(32 - i); - ix1 <<= u5(i); + m -= @intCast(i32, i) - 1; + ix0 |= ix1 >> @intCast(u5, 32 - i); + ix1 <<= @intCast(u5, i); } // unbias exponent @@ -345,10 +345,10 @@ export fn sqrt(x: f64) f64 { // NOTE: musl here appears to rely on signed twos-complement wraparound. +% has the same // behaviour at least. - var iix0 = i32(ix0); + var iix0 = @intCast(i32, ix0); iix0 = iix0 +% (m << 20); - const uz = (u64(iix0) << 32) | ix1; + const uz = (@intCast(u64, iix0) << 32) | ix1; return @bitCast(f64, uz); } diff --git a/std/special/compiler_rt/divti3.zig b/std/special/compiler_rt/divti3.zig index 60460ea62d..712cccba82 100644 --- a/std/special/compiler_rt/divti3.zig +++ b/std/special/compiler_rt/divti3.zig @@ -13,7 +13,7 @@ pub extern fn __divti3(a: i128, b: i128) i128 { const r = udivmod(u128, @bitCast(u128, an), @bitCast(u128, bn), null); const s = s_a ^ s_b; - return (i128(r) ^ s) -% s; + return (@bitCast(i128, r) ^ s) -% s; } pub extern fn __divti3_windows_x86_64(a: *const i128, b: *const i128) void { diff --git a/std/special/compiler_rt/fixuint.zig b/std/special/compiler_rt/fixuint.zig index bd9b2fc395..48d63ed914 100644 --- a/std/special/compiler_rt/fixuint.zig +++ b/std/special/compiler_rt/fixuint.zig @@ -32,14 +32,14 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t const aAbs: rep_t = aRep & absMask; const sign = if ((aRep & signBit) != 0) i32(-1) else i32(1); - const exponent = i32(aAbs >> significandBits) - exponentBias; + const exponent = @intCast(i32, aAbs >> significandBits) - exponentBias; const significand: rep_t = (aAbs & significandMask) | implicitBit; // If either the value or the exponent is negative, the result is zero. if (sign == -1 or exponent < 0) return 0; // If the value is too large for the integer type, saturate. - if (c_uint(exponent) >= fixuint_t.bit_count) return ~fixuint_t(0); + if (@intCast(c_uint, exponent) >= fixuint_t.bit_count) return ~fixuint_t(0); // If 0 <= exponent < significandBits, right shift to get the result. // Otherwise, shift left. @@ -47,11 +47,11 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t // TODO this is a workaround for the mysterious "integer cast truncated bits" // happening on the next line @setRuntimeSafety(false); - return fixuint_t(significand >> Log2Int(rep_t)(significandBits - exponent)); + return @intCast(fixuint_t, significand >> @intCast(Log2Int(rep_t), significandBits - exponent)); } else { // TODO this is a workaround for the mysterious "integer cast truncated bits" // happening on the next line @setRuntimeSafety(false); - return fixuint_t(significand) << Log2Int(fixuint_t)(exponent - significandBits); + return @intCast(fixuint_t, significand) << @intCast(Log2Int(fixuint_t), exponent - significandBits); } } diff --git a/std/special/compiler_rt/index.zig b/std/special/compiler_rt/index.zig index f952730353..dc95aa23f2 100644 --- a/std/special/compiler_rt/index.zig +++ b/std/special/compiler_rt/index.zig @@ -292,7 +292,7 @@ extern fn __udivmodsi4(a: u32, b: u32, rem: *u32) u32 { @setRuntimeSafety(is_test); const d = __udivsi3(a, b); - rem.* = u32(i32(a) -% (i32(d) * i32(b))); + rem.* = @bitCast(u32, @bitCast(i32, a) -% (@bitCast(i32, d) * @bitCast(i32, b))); return d; } @@ -316,12 +316,12 @@ extern fn __udivsi3(n: u32, d: u32) u32 { sr += 1; // 1 <= sr <= n_uword_bits - 1 // Not a special case - var q: u32 = n << u5(n_uword_bits - sr); - var r: u32 = n >> u5(sr); + var q: u32 = n << @intCast(u5, n_uword_bits - sr); + var r: u32 = n >> @intCast(u5, sr); var carry: u32 = 0; while (sr > 0) : (sr -= 1) { // r:q = ((r:q) << 1) | carry - r = (r << 1) | (q >> u5(n_uword_bits - 1)); + r = (r << 1) | (q >> @intCast(u5, n_uword_bits - 1)); q = (q << 1) | carry; // carry = 0; // if (r.all >= d.all) @@ -329,8 +329,8 @@ extern fn __udivsi3(n: u32, d: u32) u32 { // r.all -= d.all; // carry = 1; // } - const s = i32(d -% r -% 1) >> u5(n_uword_bits - 1); - carry = u32(s & 1); + const s = @intCast(i32, d -% r -% 1) >> @intCast(u5, n_uword_bits - 1); + carry = @intCast(u32, s & 1); r -= d & @bitCast(u32, s); } q = (q << 1) | carry; diff --git a/std/special/compiler_rt/udivmod.zig b/std/special/compiler_rt/udivmod.zig index 894dd02239..e6b4ee0482 100644 --- a/std/special/compiler_rt/udivmod.zig +++ b/std/special/compiler_rt/udivmod.zig @@ -71,7 +71,7 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: r[high] = n[high] & (d[high] - 1); rem.* = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 } - return n[high] >> Log2SingleInt(@ctz(d[high])); + return n[high] >> @intCast(Log2SingleInt, @ctz(d[high])); } // K K // --- @@ -88,10 +88,10 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // 1 <= sr <= SingleInt.bit_count - 1 // q.all = a << (DoubleInt.bit_count - sr); q[low] = 0; - q[high] = n[low] << Log2SingleInt(SingleInt.bit_count - sr); + q[high] = n[low] << @intCast(Log2SingleInt, SingleInt.bit_count - sr); // r.all = a >> sr; - r[high] = n[high] >> Log2SingleInt(sr); - r[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); + r[high] = n[high] >> @intCast(Log2SingleInt, sr); + r[low] = (n[high] << @intCast(Log2SingleInt, SingleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr)); } else { // d[low] != 0 if (d[high] == 0) { @@ -107,8 +107,8 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: return a; } sr = @ctz(d[low]); - q[high] = n[high] >> Log2SingleInt(sr); - q[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); + q[high] = n[high] >> @intCast(Log2SingleInt, sr); + q[low] = (n[high] << @intCast(Log2SingleInt, SingleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr)); return @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &q[0]).*; // TODO issue #421 } // K X @@ -126,15 +126,15 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: } else if (sr < SingleInt.bit_count) { // 2 <= sr <= SingleInt.bit_count - 1 q[low] = 0; - q[high] = n[low] << Log2SingleInt(SingleInt.bit_count - sr); - r[high] = n[high] >> Log2SingleInt(sr); - r[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); + q[high] = n[low] << @intCast(Log2SingleInt, SingleInt.bit_count - sr); + r[high] = n[high] >> @intCast(Log2SingleInt, sr); + r[low] = (n[high] << @intCast(Log2SingleInt, SingleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr)); } else { // SingleInt.bit_count + 1 <= sr <= DoubleInt.bit_count - 1 - q[low] = n[low] << Log2SingleInt(DoubleInt.bit_count - sr); - q[high] = (n[high] << Log2SingleInt(DoubleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr - SingleInt.bit_count)); + q[low] = n[low] << @intCast(Log2SingleInt, DoubleInt.bit_count - sr); + q[high] = (n[high] << @intCast(Log2SingleInt, DoubleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr - SingleInt.bit_count)); r[high] = 0; - r[low] = n[high] >> Log2SingleInt(sr - SingleInt.bit_count); + r[low] = n[high] >> @intCast(Log2SingleInt, sr - SingleInt.bit_count); } } else { // K X @@ -158,9 +158,9 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: r[high] = 0; r[low] = n[high]; } else { - r[high] = n[high] >> Log2SingleInt(sr); - r[low] = (n[high] << Log2SingleInt(SingleInt.bit_count - sr)) | (n[low] >> Log2SingleInt(sr)); - q[high] = n[low] << Log2SingleInt(SingleInt.bit_count - sr); + r[high] = n[high] >> @intCast(Log2SingleInt, sr); + r[low] = (n[high] << @intCast(Log2SingleInt, SingleInt.bit_count - sr)) | (n[low] >> @intCast(Log2SingleInt, sr)); + q[high] = n[low] << @intCast(Log2SingleInt, SingleInt.bit_count - sr); } } } @@ -184,8 +184,8 @@ pub fn udivmod(comptime DoubleInt: type, a: DoubleInt, b: DoubleInt, maybe_rem: // carry = 1; // } r_all = @ptrCast(*align(@alignOf(SingleInt)) DoubleInt, &r[0]).*; // TODO issue #421 - const s: SignedDoubleInt = SignedDoubleInt(b -% r_all -% 1) >> (DoubleInt.bit_count - 1); - carry = u32(s & 1); + const s: SignedDoubleInt = @intCast(SignedDoubleInt, b -% r_all -% 1) >> (DoubleInt.bit_count - 1); + carry = @intCast(u32, s & 1); r_all -= b & @bitCast(DoubleInt, s); r = @ptrCast(*[2]SingleInt, &r_all).*; // TODO issue #421 } diff --git a/std/unicode.zig b/std/unicode.zig index ec808ca4fe..9c329acc68 100644 --- a/std/unicode.zig +++ b/std/unicode.zig @@ -35,22 +35,22 @@ pub fn utf8Encode(c: u32, out: []u8) !u3 { // - Increasing the initial shift by 6 each time // - Each time after the first shorten the shifted // value to a max of 0b111111 (63) - 1 => out[0] = u8(c), // Can just do 0 + codepoint for initial range + 1 => out[0] = @intCast(u8, c), // Can just do 0 + codepoint for initial range 2 => { - out[0] = u8(0b11000000 | (c >> 6)); - out[1] = u8(0b10000000 | (c & 0b111111)); + out[0] = @intCast(u8, 0b11000000 | (c >> 6)); + out[1] = @intCast(u8, 0b10000000 | (c & 0b111111)); }, 3 => { if (0xd800 <= c and c <= 0xdfff) return error.Utf8CannotEncodeSurrogateHalf; - out[0] = u8(0b11100000 | (c >> 12)); - out[1] = u8(0b10000000 | ((c >> 6) & 0b111111)); - out[2] = u8(0b10000000 | (c & 0b111111)); + out[0] = @intCast(u8, 0b11100000 | (c >> 12)); + out[1] = @intCast(u8, 0b10000000 | ((c >> 6) & 0b111111)); + out[2] = @intCast(u8, 0b10000000 | (c & 0b111111)); }, 4 => { - out[0] = u8(0b11110000 | (c >> 18)); - out[1] = u8(0b10000000 | ((c >> 12) & 0b111111)); - out[2] = u8(0b10000000 | ((c >> 6) & 0b111111)); - out[3] = u8(0b10000000 | (c & 0b111111)); + out[0] = @intCast(u8, 0b11110000 | (c >> 18)); + out[1] = @intCast(u8, 0b10000000 | ((c >> 12) & 0b111111)); + out[2] = @intCast(u8, 0b10000000 | ((c >> 6) & 0b111111)); + out[3] = @intCast(u8, 0b10000000 | (c & 0b111111)); }, else => unreachable, } diff --git a/std/zig/tokenizer.zig b/std/zig/tokenizer.zig index 4534529f36..79f1871b64 100644 --- a/std/zig/tokenizer.zig +++ b/std/zig/tokenizer.zig @@ -1128,7 +1128,7 @@ pub const Tokenizer = struct { // check utf8-encoded character. const length = std.unicode.utf8ByteSequenceLength(c0) catch return 1; if (self.index + length > self.buffer.len) { - return u3(self.buffer.len - self.index); + return @intCast(u3, self.buffer.len - self.index); } const bytes = self.buffer[self.index .. self.index + length]; switch (length) { diff --git a/test/cases/cast.zig b/test/cases/cast.zig index 4c216010eb..7035740c54 100644 --- a/test/cases/cast.zig +++ b/test/cases/cast.zig @@ -343,7 +343,7 @@ fn testPeerErrorAndArray2(x: u8) error![]const u8 { test "explicit cast float number literal to integer if no fraction component" { const x = i32(1e4); assert(x == 10000); - const y = i32(f32(1e4)); + const y = @floatToInt(i32, f32(1e4)); assert(y == 10000); } @@ -398,3 +398,19 @@ test "cast *[1][*]const u8 to [*]const ?[*]const u8" { const x: [*]const ?[*]const u8 = &window_name; assert(mem.eql(u8, std.cstr.toSliceConst(x[0].?), "window name")); } + +test "@intCast comptime_int" { + const result = @intCast(i32, 1234); + assert(@typeOf(result) == i32); + assert(result == 1234); +} + +test "@floatCast comptime_int and comptime_float" { + const result = @floatCast(f32, 1234); + assert(@typeOf(result) == f32); + assert(result == 1234.0); + + const result2 = @floatCast(f32, 1234.0); + assert(@typeOf(result) == f32); + assert(result == 1234.0); +} diff --git a/test/cases/enum.zig b/test/cases/enum.zig index 5c78d73092..6a02a47784 100644 --- a/test/cases/enum.zig +++ b/test/cases/enum.zig @@ -99,7 +99,7 @@ test "int to enum" { testIntToEnumEval(3); } fn testIntToEnumEval(x: i32) void { - assert(IntToEnumNumber(u3(x)) == IntToEnumNumber.Three); + assert(IntToEnumNumber(@intCast(u3, x)) == IntToEnumNumber.Three); } const IntToEnumNumber = enum { Zero, diff --git a/test/cases/eval.zig b/test/cases/eval.zig index 08d3f3a841..6c919e17a6 100644 --- a/test/cases/eval.zig +++ b/test/cases/eval.zig @@ -5,7 +5,7 @@ const builtin = @import("builtin"); test "compile time recursion" { assert(some_data.len == 21); } -var some_data: [usize(fibonacci(7))]u8 = undefined; +var some_data: [@intCast(usize, fibonacci(7))]u8 = undefined; fn fibonacci(x: i32) i32 { if (x <= 1) return 1; return fibonacci(x - 1) + fibonacci(x - 2); @@ -356,7 +356,7 @@ const global_array = x: { test "compile-time downcast when the bits fit" { comptime { const spartan_count: u16 = 255; - const byte = u8(spartan_count); + const byte = @intCast(u8, spartan_count); assert(byte == 255); } } @@ -440,7 +440,7 @@ test "binary math operator in partially inlined function" { var b: [16]u8 = undefined; for (b) |*r, i| - r.* = u8(i + 1); + r.* = @intCast(u8, i + 1); copyWithPartialInline(s[0..], b[0..]); assert(s[0] == 0x1020304); @@ -480,7 +480,7 @@ fn generateTable(comptime T: type) [1010]T { var res: [1010]T = undefined; var i: usize = 0; while (i < 1010) : (i += 1) { - res[i] = T(i); + res[i] = @intCast(T, i); } return res; } diff --git a/test/cases/fn.zig b/test/cases/fn.zig index 12f22bfc35..47f7d5e688 100644 --- a/test/cases/fn.zig +++ b/test/cases/fn.zig @@ -80,7 +80,7 @@ test "function pointers" { fn4, }; for (fns) |f, i| { - assert(f() == u32(i) + 5); + assert(f() == @intCast(u32, i) + 5); } } fn fn1() u32 { diff --git a/test/cases/for.zig b/test/cases/for.zig index bdbab312f6..59d90c1b85 100644 --- a/test/cases/for.zig +++ b/test/cases/for.zig @@ -46,7 +46,7 @@ test "basic for loop" { buf_index += 1; } for (array) |item, index| { - buffer[buf_index] = u8(index); + buffer[buf_index] = @intCast(u8, index); buf_index += 1; } const unknown_size: []const u8 = array; @@ -55,7 +55,7 @@ test "basic for loop" { buf_index += 1; } for (unknown_size) |item, index| { - buffer[buf_index] = u8(index); + buffer[buf_index] = @intCast(u8, index); buf_index += 1; } diff --git a/test/cases/struct.zig b/test/cases/struct.zig index 6952611a8c..94a2ba6336 100644 --- a/test/cases/struct.zig +++ b/test/cases/struct.zig @@ -365,14 +365,14 @@ test "runtime struct initialization of bitfield" { .y = x1, }; const s2 = Nibbles{ - .x = u4(x2), - .y = u4(x2), + .x = @intCast(u4, x2), + .y = @intCast(u4, x2), }; assert(s1.x == x1); assert(s1.y == x1); - assert(s2.x == u4(x2)); - assert(s2.y == u4(x2)); + assert(s2.x == @intCast(u4, x2)); + assert(s2.y == @intCast(u4, x2)); } var x1 = u4(1); -- cgit v1.2.3