diff --git a/doc/docgen.zig b/doc/docgen.zig index d02987ab7e..f58c94f15c 100644 --- a/doc/docgen.zig +++ b/doc/docgen.zig @@ -1017,7 +1017,6 @@ fn tokenizeAndPrint(docgen_tokenizer: *Tokenizer, out: anytype, source_token: To } fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: anytype, zig_exe: []const u8, do_code_tests: bool) !void { - var code_progress_index: usize = 0; var progress = Progress{}; const root_node = try progress.start("Generating docgen examples", toc.nodes.len); defer root_node.end(); @@ -1090,7 +1089,6 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any switch (code.id) { Code.Id.Exe => |expected_outcome| code_block: { - const name_plus_bin_ext = try std.fmt.allocPrint(allocator, "{s}{s}", .{ code.name, exe_ext }); var build_args = std.ArrayList([]const u8).init(allocator); defer build_args.deinit(); try build_args.appendSlice(&[_][]const u8{ @@ -1361,19 +1359,9 @@ fn genHtml(allocator: *mem.Allocator, tokenizer: *Tokenizer, toc: *Toc, out: any }, Code.Id.Obj => |maybe_error_match| { const name_plus_obj_ext = try std.fmt.allocPrint(allocator, "{s}{s}", .{ code.name, obj_ext }); - const tmp_obj_file_name = try fs.path.join( - allocator, - &[_][]const u8{ tmp_dir_name, name_plus_obj_ext }, - ); var build_args = std.ArrayList([]const u8).init(allocator); defer build_args.deinit(); - const name_plus_h_ext = try std.fmt.allocPrint(allocator, "{s}.h", .{code.name}); - const output_h_file_name = try fs.path.join( - allocator, - &[_][]const u8{ tmp_dir_name, name_plus_h_ext }, - ); - try build_args.appendSlice(&[_][]const u8{ zig_exe, "build-obj", diff --git a/lib/std/Progress.zig b/lib/std/Progress.zig index 025f10ef0e..9afb93348a 100644 --- a/lib/std/Progress.zig +++ b/lib/std/Progress.zig @@ -295,7 +295,7 @@ fn refreshWithHeldLock(self: *Progress) void { end += 1; } - _ = file.write(self.output_buffer[0..end]) catch |e| { + _ = file.write(self.output_buffer[0..end]) catch { // Stop trying to write to this file once it errors. self.terminal = null; }; diff --git a/lib/std/SemanticVersion.zig b/lib/std/SemanticVersion.zig index 8e748184a8..e029952509 100644 --- a/lib/std/SemanticVersion.zig +++ b/lib/std/SemanticVersion.zig @@ -162,6 +162,7 @@ pub fn format( options: std.fmt.FormatOptions, out_stream: anytype, ) !void { + _ = options; if (fmt.len != 0) @compileError("Unknown format string: '" ++ fmt ++ "'"); try std.fmt.format(out_stream, "{d}.{d}.{d}", .{ self.major, self.minor, self.patch }); if (self.pre) |pre| try std.fmt.format(out_stream, "-{s}", .{pre}); @@ -259,7 +260,7 @@ test "SemanticVersion format" { // Invalid version string that may overflow. const big_invalid = "99999999999999999999999.999999999999999999.99999999999999999----RC-SNAPSHOT.12.09.1--------------------------------..12"; - if (parse(big_invalid)) |ver| std.debug.panic("expected error, found {}", .{ver}) else |err| {} + if (parse(big_invalid)) |ver| std.debug.panic("expected error, found {}", .{ver}) else |_| {} } test "SemanticVersion precedence" { diff --git a/lib/std/Thread.zig b/lib/std/Thread.zig index 76a865cf10..06fe2a84dc 100644 --- a/lib/std/Thread.zig +++ b/lib/std/Thread.zig @@ -518,8 +518,8 @@ pub fn cpuCount() CpuCountError!usize { }, .haiku => { var count: u32 = undefined; - var system_info: os.system_info = undefined; - const rc = os.system.get_system_info(&system_info); + // var system_info: os.system_info = undefined; + // const rc = os.system.get_system_info(&system_info); count = system_info.cpu_count; return @intCast(usize, count); }, diff --git a/lib/std/Thread/Condition.zig b/lib/std/Thread/Condition.zig index d88a6de31e..8485f84aa4 100644 --- a/lib/std/Thread/Condition.zig +++ b/lib/std/Thread/Condition.zig @@ -40,12 +40,18 @@ else pub const SingleThreadedCondition = struct { pub fn wait(cond: *SingleThreadedCondition, mutex: *Mutex) void { + _ = cond; + _ = mutex; unreachable; // deadlock detected } - pub fn signal(cond: *SingleThreadedCondition) void {} + pub fn signal(cond: *SingleThreadedCondition) void { + _ = cond; + } - pub fn broadcast(cond: *SingleThreadedCondition) void {} + pub fn broadcast(cond: *SingleThreadedCondition) void { + _ = cond; + } }; pub const WindowsCondition = struct { diff --git a/lib/std/Thread/StaticResetEvent.zig b/lib/std/Thread/StaticResetEvent.zig index 0a6a1d568e..6f869e0d89 100644 --- a/lib/std/Thread/StaticResetEvent.zig +++ b/lib/std/Thread/StaticResetEvent.zig @@ -105,6 +105,7 @@ pub const DebugEvent = struct { } pub fn timedWait(ev: *DebugEvent, timeout: u64) TimedWaitResult { + _ = timeout; switch (ev.state) { .unset => return .timed_out, .set => return .event_set, @@ -174,7 +175,10 @@ pub const AtomicEvent = struct { }; pub const SpinFutex = struct { - fn wake(waiters: *u32, wake_count: u32) void {} + fn wake(waiters: *u32, wake_count: u32) void { + _ = waiters; + _ = wake_count; + } fn wait(waiters: *u32, timeout: ?u64) !void { var timer: time.Timer = undefined; @@ -193,6 +197,7 @@ pub const AtomicEvent = struct { pub const LinuxFutex = struct { fn wake(waiters: *u32, wake_count: u32) void { + _ = wake_count; const waiting = std.math.maxInt(i32); // wake_count const ptr = @ptrCast(*const i32, waiters); const rc = linux.futex_wake(ptr, linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, waiting); diff --git a/lib/std/array_hash_map.zig b/lib/std/array_hash_map.zig index 1ddbfce20c..9bcecab47e 100644 --- a/lib/std/array_hash_map.zig +++ b/lib/std/array_hash_map.zig @@ -40,9 +40,11 @@ pub fn StringArrayHashMapUnmanaged(comptime V: type) type { pub const StringContext = struct { pub fn hash(self: @This(), s: []const u8) u32 { + _ = self; return hashString(s); } pub fn eql(self: @This(), a: []const u8, b: []const u8) bool { + _ = self; return eqlString(a, b); } }; @@ -1324,17 +1326,17 @@ pub fn ArrayHashMapUnmanaged( } fn removeFromIndexByIndexGeneric(self: *Self, entry_index: usize, ctx: ByIndexContext, header: *IndexHeader, comptime I: type, indexes: []Index(I)) void { const slot = self.getSlotByIndex(entry_index, ctx, header, I, indexes); - self.removeSlot(slot, header, I, indexes); + removeSlot(slot, header, I, indexes); } fn removeFromIndexByKey(self: *Self, key: anytype, ctx: anytype, header: *IndexHeader, comptime I: type, indexes: []Index(I)) ?usize { const slot = self.getSlotByKey(key, ctx, header, I, indexes) orelse return null; const removed_entry_index = indexes[slot].entry_index; - self.removeSlot(slot, header, I, indexes); + removeSlot(slot, header, I, indexes); return removed_entry_index; } - fn removeSlot(self: *Self, removed_slot: usize, header: *IndexHeader, comptime I: type, indexes: []Index(I)) void { + fn removeSlot(removed_slot: usize, header: *IndexHeader, comptime I: type, indexes: []Index(I)) void { const start_index = removed_slot +% 1; const end_index = start_index +% indexes.len; @@ -1619,13 +1621,13 @@ pub fn ArrayHashMapUnmanaged( if (self.index_header) |header| { p("\n", .{}); switch (header.capacityIndexType()) { - .u8 => self.dumpIndex(header, u8), - .u16 => self.dumpIndex(header, u16), - .u32 => self.dumpIndex(header, u32), + .u8 => dumpIndex(header, u8), + .u16 => dumpIndex(header, u16), + .u32 => dumpIndex(header, u32), } } } - fn dumpIndex(self: Self, header: *IndexHeader, comptime I: type) void { + fn dumpIndex(header: *IndexHeader, comptime I: type) void { const p = std.debug.print; p(" index len=0x{x} type={}\n", .{ header.length(), header.capacityIndexType() }); const indexes = header.indexes(I); @@ -1918,7 +1920,7 @@ test "iterator hash map" { try testing.expect(count == 3); try testing.expect(it.next() == null); - for (buffer) |v, i| { + for (buffer) |_, i| { try testing.expect(buffer[@intCast(usize, keys[i])] == values[i]); } @@ -1930,7 +1932,7 @@ test "iterator hash map" { if (count >= 2) break; } - for (buffer[0..2]) |v, i| { + for (buffer[0..2]) |_, i| { try testing.expect(buffer[@intCast(usize, keys[i])] == values[i]); } @@ -2154,6 +2156,7 @@ test "compile everything" { pub fn getHashPtrAddrFn(comptime K: type, comptime Context: type) (fn (Context, K) u32) { return struct { fn hash(ctx: Context, key: K) u32 { + _ = ctx; return getAutoHashFn(usize, void)({}, @ptrToInt(key)); } }.hash; @@ -2162,6 +2165,7 @@ pub fn getHashPtrAddrFn(comptime K: type, comptime Context: type) (fn (Context, pub fn getTrivialEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) { return struct { fn eql(ctx: Context, a: K, b: K) bool { + _ = ctx; return a == b; } }.eql; @@ -2177,6 +2181,7 @@ pub fn AutoContext(comptime K: type) type { pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) u32) { return struct { fn hash(ctx: Context, key: K) u32 { + _ = ctx; if (comptime trait.hasUniqueRepresentation(K)) { return @truncate(u32, Wyhash.hash(0, std.mem.asBytes(&key))); } else { @@ -2191,6 +2196,7 @@ pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) { return struct { fn eql(ctx: Context, a: K, b: K) bool { + _ = ctx; return meta.eql(a, b); } }.eql; @@ -2217,6 +2223,7 @@ pub fn autoEqlIsCheap(comptime K: type) bool { pub fn getAutoHashStratFn(comptime K: type, comptime Context: type, comptime strategy: std.hash.Strategy) (fn (Context, K) u32) { return struct { fn hash(ctx: Context, key: K) u32 { + _ = ctx; var hasher = Wyhash.init(0); std.hash.autoHashStrat(&hasher, key, strategy); return @truncate(u32, hasher.final()); diff --git a/lib/std/atomic/Atomic.zig b/lib/std/atomic/Atomic.zig index d137bc7552..80fb1ae297 100644 --- a/lib/std/atomic/Atomic.zig +++ b/lib/std/atomic/Atomic.zig @@ -232,6 +232,7 @@ test "Atomic.loadUnchecked" { test "Atomic.storeUnchecked" { inline for (atomicIntTypes()) |Int| { + _ = Int; var x = Atomic(usize).init(5); x.storeUnchecked(10); try testing.expectEqual(x.loadUnchecked(), 10); @@ -250,6 +251,7 @@ test "Atomic.load" { test "Atomic.store" { inline for (atomicIntTypes()) |Int| { inline for (.{ .Unordered, .Monotonic, .Release, .SeqCst }) |ordering| { + _ = Int; var x = Atomic(usize).init(5); x.store(10, ordering); try testing.expectEqual(x.load(.SeqCst), 10); diff --git a/lib/std/base64.zig b/lib/std/base64.zig index 1f37f07a28..4b01455112 100644 --- a/lib/std/base64.zig +++ b/lib/std/base64.zig @@ -112,9 +112,6 @@ pub const Base64Encoder = struct { const out_len = encoder.calcSize(source.len); assert(dest.len >= out_len); - const nibbles = source.len / 3; - const leftover = source.len - 3 * nibbles; - var acc: u12 = 0; var acc_len: u4 = 0; var out_idx: usize = 0; @@ -223,7 +220,6 @@ pub const Base64Decoder = struct { if (decoder.pad_char) |pad_char| { const padding_len = acc_len / 2; var padding_chars: usize = 0; - var i: usize = 0; for (leftover) |c| { if (c != pad_char) { return if (c == Base64Decoder.invalid_char) error.InvalidCharacter else error.InvalidPadding; @@ -302,7 +298,6 @@ pub const Base64DecoderWithIgnore = struct { var leftover = source[leftover_idx.?..]; if (decoder.pad_char) |pad_char| { var padding_chars: usize = 0; - var i: usize = 0; for (leftover) |c| { if (decoder_with_ignore.char_is_ignored[c]) continue; if (c != pad_char) { diff --git a/lib/std/bit_set.zig b/lib/std/bit_set.zig index 7187b564d2..f7339bfdcf 100644 --- a/lib/std/bit_set.zig +++ b/lib/std/bit_set.zig @@ -84,6 +84,7 @@ pub fn IntegerBitSet(comptime size: u16) type { /// Returns the number of bits in this bit set pub inline fn capacity(self: Self) usize { + _ = self; return bit_length; } @@ -311,6 +312,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type { /// Returns the number of bits in this bit set pub inline fn capacity(self: Self) usize { + _ = self; return bit_length; } @@ -373,7 +375,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type { /// Flips every bit in the bit set. pub fn toggleAll(self: *Self) void { - for (self.masks) |*mask, i| { + for (self.masks) |*mask| { mask.* = ~mask.*; } @@ -642,7 +644,7 @@ pub const DynamicBitSetUnmanaged = struct { if (bit_length == 0) return; const num_masks = numMasks(self.bit_length); - for (self.masks[0..num_masks]) |*mask, i| { + for (self.masks[0..num_masks]) |*mask| { mask.* = ~mask.*; } diff --git a/lib/std/build.zig b/lib/std/build.zig index 96af4a3071..8626d660f0 100644 --- a/lib/std/build.zig +++ b/lib/std/build.zig @@ -390,6 +390,7 @@ pub const Builder = struct { } pub fn version(self: *const Builder, major: u32, minor: u32, patch: u32) LibExeObjStep.SharedLibKind { + _ = self; return .{ .versioned = .{ .major = major, @@ -543,7 +544,7 @@ pub const Builder = struct { return null; }, .scalar => |s| { - const n = std.fmt.parseFloat(T, s) catch |err| { + const n = std.fmt.parseFloat(T, s) catch { warn("Expected -D{s} to be a float of type {s}.\n\n", .{ name, @typeName(T) }); self.markInvalidUserInput(); return null; @@ -3129,7 +3130,9 @@ pub const Step = struct { self.dependencies.append(other) catch unreachable; } - fn makeNoOp(self: *Step) anyerror!void {} + fn makeNoOp(self: *Step) anyerror!void { + _ = self; + } pub fn cast(step: *Step, comptime T: type) ?*T { if (step.id == T.base_id) { diff --git a/lib/std/build/InstallRawStep.zig b/lib/std/build/InstallRawStep.zig index f1d9608951..743b25f3cd 100644 --- a/lib/std/build/InstallRawStep.zig +++ b/lib/std/build/InstallRawStep.zig @@ -139,6 +139,7 @@ const BinaryElfOutput = struct { } fn segmentSortCompare(context: void, left: *BinaryElfSegment, right: *BinaryElfSegment) bool { + _ = context; if (left.physicalAddress < right.physicalAddress) { return true; } @@ -149,6 +150,7 @@ const BinaryElfOutput = struct { } fn sectionSortCompare(context: void, left: *BinaryElfSection, right: *BinaryElfSection) bool { + _ = context; return left.binaryOffset < right.binaryOffset; } }; diff --git a/lib/std/builtin.zig b/lib/std/builtin.zig index 4d9350bbdd..615df9b9af 100644 --- a/lib/std/builtin.zig +++ b/lib/std/builtin.zig @@ -65,6 +65,8 @@ pub const StackTrace = struct { options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = fmt; + _ = options; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const debug_info = std.debug.getSelfDebugInfo() catch |err| { @@ -521,6 +523,7 @@ pub const Version = struct { options: std.fmt.FormatOptions, out_stream: anytype, ) !void { + _ = options; if (fmt.len == 0) { if (self.patch == 0) { if (self.minor == 0) { diff --git a/lib/std/c/tokenizer.zig b/lib/std/c/tokenizer.zig index 0d4c646c39..f8709e12be 100644 --- a/lib/std/c/tokenizer.zig +++ b/lib/std/c/tokenizer.zig @@ -351,7 +351,6 @@ pub const Tokenizer = struct { pp_directive: bool = false, pub fn next(self: *Tokenizer) Token { - const start_index = self.index; var result = Token{ .id = .Eof, .start = self.index, @@ -1380,12 +1379,12 @@ test "operators" { test "keywords" { try expectTokens( - \\auto break case char const continue default do - \\double else enum extern float for goto if int - \\long register return short signed sizeof static - \\struct switch typedef union unsigned void volatile - \\while _Bool _Complex _Imaginary inline restrict _Alignas - \\_Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local + \\auto break case char const continue default do + \\double else enum extern float for goto if int + \\long register return short signed sizeof static + \\struct switch typedef union unsigned void volatile + \\while _Bool _Complex _Imaginary inline restrict _Alignas + \\_Alignof _Atomic _Generic _Noreturn _Static_assert _Thread_local \\ , &[_]Token.Id{ .Keyword_auto, diff --git a/lib/std/compress/gzip.zig b/lib/std/compress/gzip.zig index 387b64f59a..6f17601949 100644 --- a/lib/std/compress/gzip.zig +++ b/lib/std/compress/gzip.zig @@ -62,6 +62,8 @@ pub fn GzipStream(comptime ReaderType: type) type { const XFL = header[8]; // Operating system where the compression took place const OS = header[9]; + _ = XFL; + _ = OS; if (FLG & FEXTRA != 0) { // Skip the extra data, we could read and expose it to the user diff --git a/lib/std/compress/zlib.zig b/lib/std/compress/zlib.zig index 0ee154bf22..909bae4090 100644 --- a/lib/std/compress/zlib.zig +++ b/lib/std/compress/zlib.zig @@ -35,6 +35,7 @@ pub fn ZlibStream(comptime ReaderType: type) type { const CM = @truncate(u4, header[0]); const CINFO = @truncate(u4, header[0] >> 4); const FCHECK = @truncate(u5, header[1]); + _ = FCHECK; const FDICT = @truncate(u1, header[1] >> 5); if ((@as(u16, header[0]) << 8 | header[1]) % 31 != 0) diff --git a/lib/std/comptime_string_map.zig b/lib/std/comptime_string_map.zig index 0bf86167f9..7da24545ec 100644 --- a/lib/std/comptime_string_map.zig +++ b/lib/std/comptime_string_map.zig @@ -23,6 +23,7 @@ pub fn ComptimeStringMap(comptime V: type, comptime kvs: anytype) type { var sorted_kvs: [kvs.len]KV = undefined; const lenAsc = (struct { fn lenAsc(context: void, a: KV, b: KV) bool { + _ = context; return a.key.len < b.key.len; } }).lenAsc; diff --git a/lib/std/crypto/25519/ed25519.zig b/lib/std/crypto/25519/ed25519.zig index b6321e8d8c..4940f0dee6 100644 --- a/lib/std/crypto/25519/ed25519.zig +++ b/lib/std/crypto/25519/ed25519.zig @@ -346,7 +346,7 @@ test "ed25519 test vectors" { .expected = error.IdentityElement, // 11 - small-order A }, }; - for (entries) |entry, i| { + for (entries) |entry| { var msg: [entry.msg_hex.len / 2]u8 = undefined; _ = try fmt.hexToBytes(&msg, entry.msg_hex); var public_key: [32]u8 = undefined; diff --git a/lib/std/crypto/25519/scalar.zig b/lib/std/crypto/25519/scalar.zig index 46ab2017ca..bea054234e 100644 --- a/lib/std/crypto/25519/scalar.zig +++ b/lib/std/crypto/25519/scalar.zig @@ -330,13 +330,10 @@ pub const Scalar = struct { const carry9 = z02 >> 56; const c01 = carry9; const carry10 = (z12 + c01) >> 56; - const t21 = @truncate(u64, z12 + c01) & 0xffffffffffffff; const c11 = carry10; const carry11 = (z22 + c11) >> 56; - const t22 = @truncate(u64, z22 + c11) & 0xffffffffffffff; const c21 = carry11; const carry12 = (z32 + c21) >> 56; - const t23 = @truncate(u64, z32 + c21) & 0xffffffffffffff; const c31 = carry12; const carry13 = (z42 + c31) >> 56; const t24 = @truncate(u64, z42 + c31) & 0xffffffffffffff; @@ -605,13 +602,10 @@ const ScalarDouble = struct { const carry0 = z01 >> 56; const c00 = carry0; const carry1 = (z11 + c00) >> 56; - const t100 = @as(u64, @truncate(u64, z11 + c00)) & 0xffffffffffffff; const c10 = carry1; const carry2 = (z21 + c10) >> 56; - const t101 = @as(u64, @truncate(u64, z21 + c10)) & 0xffffffffffffff; const c20 = carry2; const carry3 = (z31 + c20) >> 56; - const t102 = @as(u64, @truncate(u64, z31 + c20)) & 0xffffffffffffff; const c30 = carry3; const carry4 = (z41 + c30) >> 56; const t103 = @as(u64, @truncate(u64, z41 + c30)) & 0xffffffffffffff; diff --git a/lib/std/crypto/aes/soft.zig b/lib/std/crypto/aes/soft.zig index 5eda9557ee..0d8a566793 100644 --- a/lib/std/crypto/aes/soft.zig +++ b/lib/std/crypto/aes/soft.zig @@ -49,8 +49,6 @@ pub const Block = struct { /// Encrypt a block with a round key. pub inline fn encrypt(block: Block, round_key: Block) Block { - const src = &block.repr; - const s0 = block.repr[0]; const s1 = block.repr[1]; const s2 = block.repr[2]; @@ -66,8 +64,6 @@ pub const Block = struct { /// Encrypt a block with the last round key. pub inline fn encryptLast(block: Block, round_key: Block) Block { - const src = &block.repr; - const t0 = block.repr[0]; const t1 = block.repr[1]; const t2 = block.repr[2]; @@ -88,8 +84,6 @@ pub const Block = struct { /// Decrypt a block with a round key. pub inline fn decrypt(block: Block, round_key: Block) Block { - const src = &block.repr; - const s0 = block.repr[0]; const s1 = block.repr[1]; const s2 = block.repr[2]; @@ -105,8 +99,6 @@ pub const Block = struct { /// Decrypt a block with the last round key. pub inline fn decryptLast(block: Block, round_key: Block) Block { - const src = &block.repr; - const t0 = block.repr[0]; const t1 = block.repr[1]; const t2 = block.repr[2]; diff --git a/lib/std/crypto/aes_gcm.zig b/lib/std/crypto/aes_gcm.zig index cc2a423f70..492a1a5223 100644 --- a/lib/std/crypto/aes_gcm.zig +++ b/lib/std/crypto/aes_gcm.zig @@ -114,7 +114,6 @@ test "Aes256Gcm - Empty message and no associated data" { const ad = ""; const m = ""; var c: [m.len]u8 = undefined; - var m2: [m.len]u8 = undefined; var tag: [Aes256Gcm.tag_length]u8 = undefined; Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key); diff --git a/lib/std/crypto/aes_ocb.zig b/lib/std/crypto/aes_ocb.zig index 48548f942f..6aaa7fc8cb 100644 --- a/lib/std/crypto/aes_ocb.zig +++ b/lib/std/crypto/aes_ocb.zig @@ -271,7 +271,6 @@ test "AesOcb test vector 1" { var c: [0]u8 = undefined; Aes128Ocb.encrypt(&c, &tag, "", "", nonce, k); - var expected_c: [c.len]u8 = undefined; var expected_tag: [tag.len]u8 = undefined; _ = try hexToBytes(&expected_tag, "785407BFFFC8AD9EDCC5520AC9111EE6"); diff --git a/lib/std/crypto/bcrypt.zig b/lib/std/crypto/bcrypt.zig index c1ad239e90..07c2142a97 100644 --- a/lib/std/crypto/bcrypt.zig +++ b/lib/std/crypto/bcrypt.zig @@ -48,7 +48,6 @@ const State = struct { fn expand0(state: *State, key: []const u8) void { var i: usize = 0; var j: usize = 0; - var t: u32 = undefined; while (i < state.subkeys.len) : (i += 1) { state.subkeys[i] ^= toWord(key, &j); } @@ -75,7 +74,6 @@ const State = struct { fn expand(state: *State, data: []const u8, key: []const u8) void { var i: usize = 0; var j: usize = 0; - var t: u32 = undefined; while (i < state.subkeys.len) : (i += 1) { state.subkeys[i] ^= toWord(key, &j); } diff --git a/lib/std/crypto/blake3.zig b/lib/std/crypto/blake3.zig index c4ef40de3d..75aba06da0 100644 --- a/lib/std/crypto/blake3.zig +++ b/lib/std/crypto/blake3.zig @@ -394,6 +394,7 @@ pub const Blake3 = struct { /// Construct a new `Blake3` for the key derivation function. The context /// string should be hardcoded, globally unique, and application-specific. pub fn initKdf(context: []const u8, options: KdfOptions) Blake3 { + _ = options; var context_hasher = Blake3.init_internal(IV, DERIVE_KEY_CONTEXT); context_hasher.update(context); var context_key: [KEY_LEN]u8 = undefined; diff --git a/lib/std/crypto/chacha20.zig b/lib/std/crypto/chacha20.zig index b89a35cbd4..592116ddd4 100644 --- a/lib/std/crypto/chacha20.zig +++ b/lib/std/crypto/chacha20.zig @@ -444,7 +444,6 @@ fn ChaChaWith64BitNonce(comptime rounds_nb: usize) type { if (comptime @sizeOf(usize) > 4) { // A big block is giant: 256 GiB, but we can avoid this limitation var remaining_blocks: u32 = @intCast(u32, (in.len / big_block)); - var i: u32 = 0; while (remaining_blocks > 0) : (remaining_blocks -= 1) { ChaChaImpl(rounds_nb).chacha20Xor(out[cursor .. cursor + big_block], in[cursor .. cursor + big_block], k, c); c[1] += 1; // upper 32-bit of counter, generic chacha20Xor() doesn't know about this. diff --git a/lib/std/crypto/gimli.zig b/lib/std/crypto/gimli.zig index b55466e639..7aa67212e4 100644 --- a/lib/std/crypto/gimli.zig +++ b/lib/std/crypto/gimli.zig @@ -219,6 +219,7 @@ pub const Hash = struct { const Self = @This(); pub fn init(options: Options) Self { + _ = options; return Self{ .state = State{ .data = [_]u32{0} ** (State.BLOCKBYTES / 4) }, .buf_off = 0, diff --git a/lib/std/crypto/md5.zig b/lib/std/crypto/md5.zig index d4109eed8a..ef9907d18b 100644 --- a/lib/std/crypto/md5.zig +++ b/lib/std/crypto/md5.zig @@ -45,6 +45,7 @@ pub const Md5 = struct { total_len: u64, pub fn init(options: Options) Self { + _ = options; return Self{ .s = [_]u32{ 0x67452301, diff --git a/lib/std/crypto/pcurves/p256/scalar.zig b/lib/std/crypto/pcurves/p256/scalar.zig index 02474bae08..afdc3fb502 100644 --- a/lib/std/crypto/pcurves/p256/scalar.zig +++ b/lib/std/crypto/pcurves/p256/scalar.zig @@ -63,7 +63,7 @@ pub fn add(a: CompressedScalar, b: CompressedScalar, endian: builtin.Endian) Non /// Return -s (mod L) pub fn neg(s: CompressedScalar, endian: builtin.Endian) NonCanonicalError!CompressedScalar { - return (try Scalar.fromBytes(a, endian)).neg().toBytes(endian); + return (try Scalar.fromBytes(s, endian)).neg().toBytes(endian); } /// Return (a-b) (mod L) diff --git a/lib/std/crypto/sha1.zig b/lib/std/crypto/sha1.zig index 6bf6b469e2..e167a50710 100644 --- a/lib/std/crypto/sha1.zig +++ b/lib/std/crypto/sha1.zig @@ -43,6 +43,7 @@ pub const Sha1 = struct { total_len: u64 = 0, pub fn init(options: Options) Self { + _ = options; return Self{ .s = [_]u32{ 0x67452301, diff --git a/lib/std/crypto/sha2.zig b/lib/std/crypto/sha2.zig index ece2a3abfb..eb0eccfa84 100644 --- a/lib/std/crypto/sha2.zig +++ b/lib/std/crypto/sha2.zig @@ -95,6 +95,7 @@ fn Sha2x32(comptime params: Sha2Params32) type { total_len: u64 = 0, pub fn init(options: Options) Self { + _ = options; return Self{ .s = [_]u32{ params.iv0, @@ -462,6 +463,7 @@ fn Sha2x64(comptime params: Sha2Params64) type { total_len: u128 = 0, pub fn init(options: Options) Self { + _ = options; return Self{ .s = [_]u64{ params.iv0, diff --git a/lib/std/crypto/sha3.zig b/lib/std/crypto/sha3.zig index d642d631e0..a4637c7fd4 100644 --- a/lib/std/crypto/sha3.zig +++ b/lib/std/crypto/sha3.zig @@ -28,6 +28,7 @@ fn Keccak(comptime bits: usize, comptime delim: u8) type { rate: usize, pub fn init(options: Options) Self { + _ = options; return Self{ .s = [_]u8{0} ** 200, .offset = 0, .rate = 200 - (bits / 4) }; } diff --git a/lib/std/crypto/tlcsprng.zig b/lib/std/crypto/tlcsprng.zig index c2cb119d4a..15a356d3d3 100644 --- a/lib/std/crypto/tlcsprng.zig +++ b/lib/std/crypto/tlcsprng.zig @@ -84,7 +84,7 @@ fn tlsCsprngFill(_: *const std.rand.Random, buffer: []u8) void { os.MAP_PRIVATE | os.MAP_ANONYMOUS, -1, 0, - ) catch |err| { + ) catch { // Could not allocate memory for the local state, fall back to // the OS syscall. return fillWithOsEntropy(buffer); diff --git a/lib/std/debug.zig b/lib/std/debug.zig index 926e518ca1..fa87e5898c 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -325,6 +325,7 @@ pub fn writeStackTrace( debug_info: *DebugInfo, tty_config: TTY.Config, ) !void { + _ = allocator; if (builtin.strip_debug_info) return error.MissingDebugInfo; var frame_index: usize = 0; var frames_left: usize = std.math.min(stack_trace.index, stack_trace.instruction_addresses.len); @@ -680,6 +681,7 @@ fn readCoffDebugInfo(allocator: *mem.Allocator, coff_file: File) !ModuleDebugInf try di.coff.loadSections(); if (di.coff.getSection(".debug_info")) |sec| { // This coff file has embedded DWARF debug info + _ = sec; // TODO: free the section data slices const debug_info_data = di.coff.getSectionData(".debug_info", allocator) catch null; const debug_abbrev_data = di.coff.getSectionData(".debug_abbrev", allocator) catch null; @@ -896,7 +898,6 @@ fn printLineFromFileAnyOs(out_stream: anytype, line_info: LineInfo) !void { var buf: [mem.page_size]u8 = undefined; var line: usize = 1; var column: usize = 1; - var abs_index: usize = 0; while (true) { const amt_read = try f.read(buf[0..]); const slice = buf[0..amt_read]; @@ -931,6 +932,7 @@ const MachoSymbol = struct { } fn addressLessThan(context: void, lhs: MachoSymbol, rhs: MachoSymbol) bool { + _ = context; return lhs.address() < rhs.address(); } }; @@ -1135,6 +1137,7 @@ pub const DebugInfo = struct { if (os.dl_iterate_phdr(&ctx, anyerror, struct { fn callback(info: *os.dl_phdr_info, size: usize, context: *CtxTy) !void { + _ = size; // The base address is too high if (context.address < info.dlpi_addr) return; @@ -1190,6 +1193,8 @@ pub const DebugInfo = struct { } fn lookupModuleHaiku(self: *DebugInfo, address: usize) !*ModuleDebugInfo { + _ = self; + _ = address; @panic("TODO implement lookup module for Haiku"); } }; diff --git a/lib/std/dwarf.zig b/lib/std/dwarf.zig index 116f5b01ff..eb22dba7c0 100644 --- a/lib/std/dwarf.zig +++ b/lib/std/dwarf.zig @@ -283,6 +283,7 @@ fn parseFormValueBlock(allocator: *mem.Allocator, in_stream: anytype, endian: bu } fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: anytype, signed: bool, endian: builtin.Endian, comptime size: i32) !FormValue { + _ = allocator; // TODO: Please forgive me, I've worked around zig not properly spilling some intermediate values here. // `nosuspend` should be removed from all the function calls once it is fixed. return FormValue{ @@ -310,6 +311,7 @@ fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: anytype, signed: // TODO the nosuspends here are workarounds fn parseFormValueRef(allocator: *mem.Allocator, in_stream: anytype, endian: builtin.Endian, size: i32) !FormValue { + _ = allocator; return FormValue{ .Ref = switch (size) { 1 => try nosuspend in_stream.readInt(u8, endian), @@ -453,13 +455,13 @@ pub const DwarfInfo = struct { if (this_die_obj.getAttr(AT_name)) |_| { const name = try this_die_obj.getAttrString(di, AT_name); break :x name; - } else if (this_die_obj.getAttr(AT_abstract_origin)) |ref| { + } else if (this_die_obj.getAttr(AT_abstract_origin)) |_| { // Follow the DIE it points to and repeat const ref_offset = try this_die_obj.getAttrRef(AT_abstract_origin); if (ref_offset > next_offset) return error.InvalidDebugInfo; try seekable.seekTo(this_unit_offset + ref_offset); this_die_obj = (try di.parseDie(in, abbrev_table, is_64)) orelse return error.InvalidDebugInfo; - } else if (this_die_obj.getAttr(AT_specification)) |ref| { + } else if (this_die_obj.getAttr(AT_specification)) |_| { // Follow the DIE it points to and repeat const ref_offset = try this_die_obj.getAttrRef(AT_specification); if (ref_offset > next_offset) return error.InvalidDebugInfo; diff --git a/lib/std/dynamic_library.zig b/lib/std/dynamic_library.zig index 098d245a4a..d1750ef761 100644 --- a/lib/std/dynamic_library.zig +++ b/lib/std/dynamic_library.zig @@ -66,6 +66,7 @@ pub fn get_DYNAMIC() ?[*]elf.Dyn { } pub fn linkmap_iterator(phdrs: []elf.Phdr) !LinkMap.Iterator { + _ = phdrs; const _DYNAMIC = get_DYNAMIC() orelse { // No PT_DYNAMIC means this is either a statically-linked program or a // badly corrupted dynamically-linked one. @@ -407,7 +408,7 @@ test "dynamic_library" { else => return error.SkipZigTest, }; - const dynlib = DynLib.open(libname) catch |err| { + _ = DynLib.open(libname) catch |err| { try testing.expect(err == error.FileNotFound); return; }; diff --git a/lib/std/enums.zig b/lib/std/enums.zig index ac0b543559..95c6fc7ec7 100644 --- a/lib/std/enums.zig +++ b/lib/std/enums.zig @@ -18,7 +18,7 @@ const EnumField = std.builtin.TypeInfo.EnumField; pub fn EnumFieldStruct(comptime E: type, comptime Data: type, comptime field_default: ?Data) type { const StructField = std.builtin.TypeInfo.StructField; var fields: []const StructField = &[_]StructField{}; - for (std.meta.fields(E)) |field, i| { + for (std.meta.fields(E)) |field| { fields = fields ++ &[_]StructField{.{ .name = field.name, .field_type = Data, @@ -144,7 +144,7 @@ pub fn directEnumArrayDefault( ) [directEnumArrayLen(E, max_unused_slots)]Data { const len = comptime directEnumArrayLen(E, max_unused_slots); var result: [len]Data = if (default) |d| [_]Data{d} ** len else undefined; - inline for (@typeInfo(@TypeOf(init_values)).Struct.fields) |f, i| { + inline for (@typeInfo(@TypeOf(init_values)).Struct.fields) |f| { const enum_value = @field(E, f.name); const index = @intCast(usize, @enumToInt(enum_value)); result[index] = @field(init_values, f.name); @@ -334,6 +334,7 @@ pub fn EnumArray(comptime E: type, comptime V: type) type { /// TODO: Once #8169 is fixed, consider switching this param /// back to an optional. pub fn NoExtension(comptime Self: type) type { + _ = Self; return NoExt; } const NoExt = struct {}; @@ -729,6 +730,7 @@ test "std.enums.ensureIndexer" { } fn ascByValue(ctx: void, comptime a: EnumField, comptime b: EnumField) bool { + _ = ctx; return a.value < b.value; } pub fn EnumIndexer(comptime E: type) type { @@ -743,9 +745,11 @@ pub fn EnumIndexer(comptime E: type) type { pub const Key = E; pub const count: usize = 0; pub fn indexOf(e: E) usize { + _ = e; unreachable; } pub fn keyForIndex(i: usize) E { + _ = i; unreachable; } }; @@ -753,10 +757,11 @@ pub fn EnumIndexer(comptime E: type) type { std.sort.sort(EnumField, &fields, {}, ascByValue); const min = fields[0].value; const max = fields[fields.len - 1].value; + const fields_len = fields.len; if (max - min == fields.len - 1) { return struct { pub const Key = E; - pub const count = fields.len; + pub const count = fields_len; pub fn indexOf(e: E) usize { return @intCast(usize, @enumToInt(e) - min); } @@ -774,7 +779,7 @@ pub fn EnumIndexer(comptime E: type) type { return struct { pub const Key = E; - pub const count = fields.len; + pub const count = fields_len; pub fn indexOf(e: E) usize { for (keys) |k, i| { if (k == e) return i; diff --git a/lib/std/event/channel.zig b/lib/std/event/channel.zig index f9c2d4b533..3880d6e286 100644 --- a/lib/std/event/channel.zig +++ b/lib/std/event/channel.zig @@ -308,7 +308,6 @@ test "std.event.Channel wraparound" { // add items to channel and pull them out until // the buffer wraps around, make sure it doesn't crash. - var result: i32 = undefined; channel.put(5); try testing.expectEqual(@as(i32, 5), channel.get()); channel.put(6); diff --git a/lib/std/event/group.zig b/lib/std/event/group.zig index 7ac27a13f2..1d12689aff 100644 --- a/lib/std/event/group.zig +++ b/lib/std/event/group.zig @@ -130,7 +130,7 @@ test "std.event.Group" { // TODO this file has bit-rotted. repair it if (true) return error.SkipZigTest; - const handle = async testGroup(std.heap.page_allocator); + _ = async testGroup(std.heap.page_allocator); } fn testGroup(allocator: *Allocator) callconv(.Async) void { var count: usize = 0; diff --git a/lib/std/event/loop.zig b/lib/std/event/loop.zig index ca55a366f8..bfc204919c 100644 --- a/lib/std/event/loop.zig +++ b/lib/std/event/loop.zig @@ -345,7 +345,7 @@ pub const Loop = struct { ); errdefer windows.CloseHandle(self.os_data.io_port); - for (self.eventfd_resume_nodes) |*eventfd_node, i| { + for (self.eventfd_resume_nodes) |*eventfd_node| { eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{ .data = ResumeNode.EventFd{ .base = ResumeNode{ @@ -680,7 +680,7 @@ pub const Loop = struct { fn run(func_args: Args, loop: *Loop, allocator: *mem.Allocator) void { loop.beginOneEvent(); loop.yield(); - const result = @call(.{}, func, func_args); + @call(.{}, func, func_args); // compile error when called with non-void ret type suspend { loop.finishOneEvent(); allocator.destroy(@frame()); diff --git a/lib/std/event/rwlock.zig b/lib/std/event/rwlock.zig index 714e50b2a9..3bd0c86035 100644 --- a/lib/std/event/rwlock.zig +++ b/lib/std/event/rwlock.zig @@ -225,7 +225,7 @@ test "std.event.RwLock" { var lock = RwLock.init(); defer lock.deinit(); - const handle = testLock(std.heap.page_allocator, &lock); + _ = testLock(std.heap.page_allocator, &lock); const expected_result = [1]i32{shared_it_count * @intCast(i32, shared_test_data.len)} ** shared_test_data.len; try testing.expectEqualSlices(i32, expected_result, shared_test_data); diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index 81b505c952..9ba7b8262c 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -369,6 +369,7 @@ pub fn format( } pub fn formatAddress(value: anytype, options: FormatOptions, writer: anytype) @TypeOf(writer).Error!void { + _ = options; const T = @TypeOf(value); switch (@typeInfo(T)) { @@ -553,7 +554,7 @@ pub fn formatType( .Many, .C => { if (actual_fmt.len == 0) @compileError("cannot format pointer without a specifier (i.e. {s} or {*})"); - if (ptr_info.sentinel) |sentinel| { + if (ptr_info.sentinel) |_| { return formatType(mem.span(value), actual_fmt, options, writer, max_depth); } if (ptr_info.child == u8) { @@ -741,6 +742,8 @@ fn formatSliceHexImpl(comptime case: Case) type { options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = fmt; + _ = options; var buf: [2]u8 = undefined; for (bytes) |c| { @@ -777,6 +780,8 @@ fn formatSliceEscapeImpl(comptime case: Case) type { options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = fmt; + _ = options; var buf: [4]u8 = undefined; buf[0] = '\\'; @@ -820,6 +825,7 @@ fn formatSizeImpl(comptime radix: comptime_int) type { options: FormatOptions, writer: anytype, ) !void { + _ = fmt; if (value == 0) { return writer.writeAll("0B"); } @@ -903,6 +909,7 @@ pub fn formatAsciiChar( options: FormatOptions, writer: anytype, ) !void { + _ = options; return writer.writeAll(@as(*const [1]u8, &c)); } @@ -1140,7 +1147,7 @@ pub fn formatFloatHexadecimal( // +1 for the decimal part. var buf: [1 + mantissa_digits]u8 = undefined; - const N = formatIntBuf(&buf, mantissa, 16, .lower, .{ .fill = '0', .width = 1 + mantissa_digits }); + _ = formatIntBuf(&buf, mantissa, 16, .lower, .{ .fill = '0', .width = 1 + mantissa_digits }); try writer.writeAll("0x"); try writer.writeByte(buf[0]); @@ -1362,6 +1369,8 @@ pub fn formatIntBuf(out_buf: []u8, value: anytype, base: u8, case: Case, options } fn formatDuration(ns: u64, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { + _ = fmt; + _ = options; var ns_remaining = ns; inline for (.{ .{ .ns = 365 * std.time.ns_per_day, .sep = 'y' }, @@ -2152,6 +2161,7 @@ test "custom" { options: FormatOptions, writer: anytype, ) !void { + _ = options; if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "p")) { return std.fmt.format(writer, "({d:.3},{d:.3})", .{ self.x, self.y }); } else if (comptime std.mem.eql(u8, fmt, "d")) { @@ -2162,7 +2172,6 @@ test "custom" { } }; - var buf1: [32]u8 = undefined; var value = Vec2{ .x = 10.2, .y = 2.22, @@ -2220,7 +2229,7 @@ test "union" { try std.testing.expect(mem.eql(u8, uu_result[0..3], "UU@")); const eu_result = try bufPrint(buf[0..], "{}", .{eu_inst}); - try std.testing.expect(mem.eql(u8, uu_result[0..3], "EU@")); + try std.testing.expect(mem.eql(u8, eu_result[0..3], "EU@")); } test "enum" { @@ -2341,6 +2350,7 @@ test "formatType max_depth" { options: FormatOptions, writer: anytype, ) !void { + _ = options; if (fmt.len == 0) { return std.fmt.format(writer, "({d:.3},{d:.3})", .{ self.x, self.y }); } else { diff --git a/lib/std/fmt/parse_float.zig b/lib/std/fmt/parse_float.zig index 1f6d7222ac..6178398b17 100644 --- a/lib/std/fmt/parse_float.zig +++ b/lib/std/fmt/parse_float.zig @@ -200,7 +200,6 @@ const ParseResult = enum { fn parseRepr(s: []const u8, n: *FloatRepr) !ParseResult { var digit_index: usize = 0; - var negative = false; var negative_exp = false; var exponent: i32 = 0; diff --git a/lib/std/fs.zig b/lib/std/fs.zig index c69a6ca5cd..9a39bc0425 100644 --- a/lib/std/fs.zig +++ b/lib/std/fs.zig @@ -477,7 +477,7 @@ pub const Dir = struct { } var stat_info: os.libc_stat = undefined; - const rc2 = os.system._kern_read_stat( + _ = os.system._kern_read_stat( self.dir.fd, &haiku_entry.d_name, false, @@ -1541,7 +1541,7 @@ pub const Dir = struct { self: Dir, target_path: []const u8, sym_link_path: []const u8, - flags: SymLinkFlags, + _: SymLinkFlags, ) !void { return os.symlinkatWasi(target_path, self.fd, sym_link_path); } @@ -1879,6 +1879,7 @@ pub const Dir = struct { /// * NtDll prefixed /// TODO currently this ignores `flags`. pub fn accessW(self: Dir, sub_path_w: [*:0]const u16, flags: File.OpenFlags) AccessError!void { + _ = flags; return os.faccessatW(self.fd, sub_path_w, 0, 0); } @@ -2438,7 +2439,7 @@ pub fn selfExePath(out_buffer: []u8) SelfExePathError![]u8 { }) catch continue; var real_path_buf: [MAX_PATH_BYTES]u8 = undefined; - if (os.realpathZ(&resolved_path_buf, &real_path_buf)) |real_path| { + if (os.realpathZ(resolved_path, &real_path_buf)) |real_path| { // found a file, and hope it is the right file if (real_path.len > out_buffer.len) return error.NameTooLong; diff --git a/lib/std/fs/path.zig b/lib/std/fs/path.zig index fd5c46ff9f..04404a61bb 100644 --- a/lib/std/fs/path.zig +++ b/lib/std/fs/path.zig @@ -579,7 +579,7 @@ pub fn resolveWindows(allocator: *Allocator, paths: []const []const u8) ![]u8 { // Now we know the disk designator to use, if any, and what kind it is. And our result // is big enough to append all the paths to. var correct_disk_designator = true; - for (paths[first_index..]) |p, i| { + for (paths[first_index..]) |p| { const parsed = windowsParsePath(p); if (parsed.kind != WindowsPath.Kind.None) { @@ -660,7 +660,7 @@ pub fn resolvePosix(allocator: *Allocator, paths: []const []const u8) ![]u8 { } errdefer allocator.free(result); - for (paths[first_index..]) |p, i| { + for (paths[first_index..]) |p| { var it = mem.tokenize(p, "/"); while (it.next()) |component| { if (mem.eql(u8, component, ".")) { diff --git a/lib/std/fs/test.zig b/lib/std/fs/test.zig index a20ec4c1bc..3c7a95432c 100644 --- a/lib/std/fs/test.zig +++ b/lib/std/fs/test.zig @@ -541,6 +541,7 @@ test "makePath, put some files in it, deleteTree" { try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "b" ++ fs.path.sep_str ++ "file2.txt", "blah"); try tmp.dir.deleteTree("os_test_tmp"); if (tmp.dir.openDir("os_test_tmp", .{})) |dir| { + _ = dir; @panic("expected error"); } else |err| { try testing.expect(err == error.FileNotFound); @@ -638,6 +639,7 @@ test "access file" { try tmp.dir.makePath("os_test_tmp"); if (tmp.dir.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{})) |ok| { + _ = ok; @panic("expected error"); } else |err| { try testing.expect(err == error.FileNotFound); diff --git a/lib/std/fs/wasi.zig b/lib/std/fs/wasi.zig index adc20883e5..c41c9a7614 100644 --- a/lib/std/fs/wasi.zig +++ b/lib/std/fs/wasi.zig @@ -36,6 +36,8 @@ pub const PreopenType = union(PreopenTypeTag) { } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype) !void { + _ = fmt; + _ = options; try out_stream.print("PreopenType{{ ", .{}); switch (self) { PreopenType.Dir => |path| try out_stream.print(".Dir = '{}'", .{std.zig.fmtId(path)}), diff --git a/lib/std/hash/cityhash.zig b/lib/std/hash/cityhash.zig index 920a006b8f..8796eb0075 100644 --- a/lib/std/hash/cityhash.zig +++ b/lib/std/hash/cityhash.zig @@ -353,7 +353,6 @@ fn SMHasherTest(comptime hash_fn: anytype) u32 { var key: [256]u8 = undefined; var hashes_bytes: [256 * @sizeOf(HashResult)]u8 = undefined; - var final: HashResult = 0; std.mem.set(u8, &key, 0); std.mem.set(u8, &hashes_bytes, 0); @@ -376,6 +375,7 @@ fn SMHasherTest(comptime hash_fn: anytype) u32 { } fn CityHash32hashIgnoreSeed(str: []const u8, seed: u32) u32 { + _ = seed; return CityHash32.hash(str); } diff --git a/lib/std/hash/wyhash.zig b/lib/std/hash/wyhash.zig index 4b9afe6355..83cd5e097c 100644 --- a/lib/std/hash/wyhash.zig +++ b/lib/std/hash/wyhash.zig @@ -166,8 +166,6 @@ pub const Wyhash = struct { } pub fn final(self: *Wyhash) u64 { - const seed = self.state.seed; - const rem_len = @intCast(u5, self.buf_len); const rem_key = self.buf[0..self.buf_len]; return self.state.final(rem_key); diff --git a/lib/std/hash_map.zig b/lib/std/hash_map.zig index fdd7db51c9..d64e122aaf 100644 --- a/lib/std/hash_map.zig +++ b/lib/std/hash_map.zig @@ -29,6 +29,7 @@ pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) return struct { fn hash(ctx: Context, key: K) u64 { + _ = ctx; if (comptime trait.hasUniqueRepresentation(K)) { return Wyhash.hash(0, std.mem.asBytes(&key)); } else { @@ -43,6 +44,7 @@ pub fn getAutoHashFn(comptime K: type, comptime Context: type) (fn (Context, K) pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) { return struct { fn eql(ctx: Context, a: K, b: K) bool { + _ = ctx; return meta.eql(a, b); } }.eql; @@ -78,9 +80,11 @@ pub fn StringHashMapUnmanaged(comptime V: type) type { pub const StringContext = struct { pub fn hash(self: @This(), s: []const u8) u64 { + _ = self; return hashString(s); } pub fn eql(self: @This(), a: []const u8, b: []const u8) bool { + _ = self; return eqlString(a, b); } }; @@ -1809,7 +1813,7 @@ test "std.hash_map getOrPut" { i = 0; while (i < 20) : (i += 1) { - var n = try map.getOrPutValue(i, 1); + _ = try map.getOrPutValue(i, 1); } i = 0; @@ -1887,9 +1891,11 @@ test "std.hash_map clone" { test "std.hash_map getOrPutAdapted" { const AdaptedContext = struct { fn eql(self: @This(), adapted_key: []const u8, test_key: u64) bool { + _ = self; return std.fmt.parseInt(u64, adapted_key, 10) catch unreachable == test_key; } fn hash(self: @This(), adapted_key: []const u8) u64 { + _ = self; const key = std.fmt.parseInt(u64, adapted_key, 10) catch unreachable; return (AutoContext(u64){}).hash(key); } diff --git a/lib/std/heap.zig b/lib/std/heap.zig index a5150e50fe..088d6b39bb 100644 --- a/lib/std/heap.zig +++ b/lib/std/heap.zig @@ -108,6 +108,8 @@ const CAllocator = struct { len_align: u29, return_address: usize, ) error{OutOfMemory}![]u8 { + _ = allocator; + _ = return_address; assert(len > 0); assert(std.math.isPowerOfTwo(alignment)); @@ -134,6 +136,9 @@ const CAllocator = struct { len_align: u29, return_address: usize, ) Allocator.Error!usize { + _ = allocator; + _ = buf_align; + _ = return_address; if (new_len == 0) { alignedFree(buf.ptr); return 0; @@ -178,6 +183,9 @@ fn rawCAlloc( len_align: u29, ret_addr: usize, ) Allocator.Error![]u8 { + _ = self; + _ = len_align; + _ = ret_addr; assert(ptr_align <= @alignOf(std.c.max_align_t)); const ptr = @ptrCast([*]u8, c.malloc(len) orelse return error.OutOfMemory); return ptr[0..len]; @@ -191,6 +199,9 @@ fn rawCResize( len_align: u29, ret_addr: usize, ) Allocator.Error!usize { + _ = self; + _ = old_align; + _ = ret_addr; if (new_len == 0) { c.free(buf.ptr); return 0; @@ -231,6 +242,8 @@ pub var next_mmap_addr_hint: ?[*]align(mem.page_size) u8 = null; const PageAllocator = struct { fn alloc(allocator: *Allocator, n: usize, alignment: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 { + _ = allocator; + _ = ra; assert(n > 0); const aligned_len = mem.alignForward(n, mem.page_size); @@ -334,6 +347,9 @@ const PageAllocator = struct { len_align: u29, return_address: usize, ) Allocator.Error!usize { + _ = allocator; + _ = buf_align; + _ = return_address; const new_size_aligned = mem.alignForward(new_size, mem.page_size); if (builtin.os.tag == .windows) { @@ -482,6 +498,8 @@ const WasmPageAllocator = struct { } fn alloc(allocator: *Allocator, len: usize, alignment: u29, len_align: u29, ra: usize) error{OutOfMemory}![]u8 { + _ = allocator; + _ = ra; const page_count = nPages(len); const page_idx = try allocPages(page_count, alignment); return @intToPtr([*]u8, page_idx * mem.page_size)[0..alignPageAllocLen(page_count * mem.page_size, len, len_align)]; @@ -542,6 +560,9 @@ const WasmPageAllocator = struct { len_align: u29, return_address: usize, ) error{OutOfMemory}!usize { + _ = allocator; + _ = buf_align; + _ = return_address; const aligned_len = mem.alignForward(buf.len, mem.page_size); if (new_len > aligned_len) return error.OutOfMemory; const current_n = nPages(aligned_len); @@ -588,6 +609,7 @@ pub const HeapAllocator = switch (builtin.os.tag) { len_align: u29, return_address: usize, ) error{OutOfMemory}![]u8 { + _ = return_address; const self = @fieldParentPtr(HeapAllocator, "allocator", allocator); const amt = n + ptr_align - 1 + @sizeOf(usize); @@ -622,6 +644,8 @@ pub const HeapAllocator = switch (builtin.os.tag) { len_align: u29, return_address: usize, ) error{OutOfMemory}!usize { + _ = buf_align; + _ = return_address; const self = @fieldParentPtr(HeapAllocator, "allocator", allocator); if (new_size == 0) { os.windows.HeapFree(self.heap_handle.?, 0, @intToPtr(*c_void, getRecordPtr(buf).*)); @@ -694,6 +718,8 @@ pub const FixedBufferAllocator = struct { } fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 { + _ = len_align; + _ = ra; const self = @fieldParentPtr(FixedBufferAllocator, "allocator", allocator); const adjust_off = mem.alignPointerOffset(self.buffer.ptr + self.end_index, ptr_align) orelse return error.OutOfMemory; @@ -716,6 +742,8 @@ pub const FixedBufferAllocator = struct { len_align: u29, return_address: usize, ) Allocator.Error!usize { + _ = buf_align; + _ = return_address; const self = @fieldParentPtr(FixedBufferAllocator, "allocator", allocator); assert(self.ownsSlice(buf)); // sanity check @@ -766,6 +794,8 @@ pub const ThreadSafeFixedBufferAllocator = blk: { } fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 { + _ = len_align; + _ = ra; const self = @fieldParentPtr(ThreadSafeFixedBufferAllocator, "allocator", allocator); var end_index = @atomicLoad(usize, &self.end_index, builtin.AtomicOrder.SeqCst); while (true) { diff --git a/lib/std/heap/arena_allocator.zig b/lib/std/heap/arena_allocator.zig index 1b301bbb50..356d5c5d81 100644 --- a/lib/std/heap/arena_allocator.zig +++ b/lib/std/heap/arena_allocator.zig @@ -66,6 +66,8 @@ pub const ArenaAllocator = struct { } fn alloc(allocator: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 { + _ = len_align; + _ = ra; const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator); var cur_node = if (self.state.buffer_list.first) |first_node| first_node else try self.createNode(0, n + ptr_align); @@ -95,6 +97,9 @@ pub const ArenaAllocator = struct { } fn resize(allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) Allocator.Error!usize { + _ = buf_align; + _ = len_align; + _ = ret_addr; const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator); const cur_node = self.state.buffer_list.first orelse return error.OutOfMemory; diff --git a/lib/std/heap/log_to_writer_allocator.zig b/lib/std/heap/log_to_writer_allocator.zig index 96c6971f38..c2fd687e0c 100644 --- a/lib/std/heap/log_to_writer_allocator.zig +++ b/lib/std/heap/log_to_writer_allocator.zig @@ -37,9 +37,9 @@ pub fn LogToWriterAllocator(comptime Writer: type) type { const self = @fieldParentPtr(Self, "allocator", allocator); self.writer.print("alloc : {}", .{len}) catch {}; const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ra); - if (result) |buff| { + if (result) |_| { self.writer.print(" success!\n", .{}) catch {}; - } else |err| { + } else |_| { self.writer.print(" failure!\n", .{}) catch {}; } return result; diff --git a/lib/std/heap/logging_allocator.zig b/lib/std/heap/logging_allocator.zig index ea63a76b72..7baa857f00 100644 --- a/lib/std/heap/logging_allocator.zig +++ b/lib/std/heap/logging_allocator.zig @@ -65,7 +65,7 @@ pub fn ScopedLoggingAllocator( ) error{OutOfMemory}![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ra); - if (result) |buff| { + if (result) |_| { logHelper( success_log_level, "alloc - success - len: {}, ptr_align: {}, len_align: {}", diff --git a/lib/std/io.zig b/lib/std/io.zig index 1264ba4aef..8bb9c4d2c0 100644 --- a/lib/std/io.zig +++ b/lib/std/io.zig @@ -161,6 +161,7 @@ pub const null_writer = @as(NullWriter, .{ .context = {} }); const NullWriter = Writer(void, error{}, dummyWrite); fn dummyWrite(context: void, data: []const u8) error{}!usize { + _ = context; return data.len; } diff --git a/lib/std/io/bit_reader.zig b/lib/std/io/bit_reader.zig index 16411b4fa6..9092c8a62d 100644 --- a/lib/std/io/bit_reader.zig +++ b/lib/std/io/bit_reader.zig @@ -149,7 +149,7 @@ pub fn BitReader(endian: builtin.Endian, comptime ReaderType: type) type { var out_bits_total = @as(usize, 0); //@NOTE: I'm not sure this is a good idea, maybe alignToByte should be forced if (self.bit_count > 0) { - for (buffer) |*b, i| { + for (buffer) |*b| { b.* = try self.readBits(u8, u8_bit_count, &out_bits); out_bits_total += out_bits; } diff --git a/lib/std/io/bit_writer.zig b/lib/std/io/bit_writer.zig index 7f80251543..daa0718a18 100644 --- a/lib/std/io/bit_writer.zig +++ b/lib/std/io/bit_writer.zig @@ -128,7 +128,7 @@ pub fn BitWriter(endian: builtin.Endian, comptime WriterType: type) type { pub fn write(self: *Self, buffer: []const u8) Error!usize { // TODO: I'm not sure this is a good idea, maybe flushBits should be forced if (self.bit_count > 0) { - for (buffer) |b, i| + for (buffer) |b| try self.writeBits(b, u8_bit_count); return buffer.len; } diff --git a/lib/std/json.zig b/lib/std/json.zig index 847d38f08d..8759469327 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -1221,11 +1221,11 @@ test "json.token premature object close" { pub fn validate(s: []const u8) bool { var p = StreamingParser.init(); - for (s) |c, i| { + for (s) |c| { var token1: ?Token = undefined; var token2: ?Token = undefined; - p.feed(c, &token1, &token2) catch |err| { + p.feed(c, &token1, &token2) catch { return false; }; } @@ -1410,7 +1410,7 @@ fn parsedEqual(a: anytype, b: @TypeOf(a)) bool { if (a == null or b == null) return false; return parsedEqual(a.?, b.?); }, - .Union => |unionInfo| { + .Union => { if (info.tag_type) |UnionTag| { const tag_a = std.meta.activeTag(a); const tag_b = std.meta.activeTag(b); @@ -1771,7 +1771,7 @@ fn parseInternal(comptime T: type, token: Token, tokens: *TokenStream, options: const source_slice = stringToken.slice(tokens.slice, tokens.i - 1); switch (stringToken.escapes) { .None => return allocator.dupe(u8, source_slice), - .Some => |some_escapes| { + .Some => { const output = try allocator.alloc(u8, stringToken.decodedLength()); errdefer allocator.free(output); try unescapeValidString(output, source_slice); @@ -2391,7 +2391,7 @@ pub const Parser = struct { const slice = s.slice(input, i); switch (s.escapes) { .None => return Value{ .String = if (p.copy_strings) try allocator.dupe(u8, slice) else slice }, - .Some => |some_escapes| { + .Some => { const output = try allocator.alloc(u8, s.decodedLength()); errdefer allocator.free(output); try unescapeValidString(output, slice); @@ -2401,6 +2401,7 @@ pub const Parser = struct { } fn parseNumber(p: *Parser, n: std.meta.TagPayload(Token, Token.Number), input: []const u8, i: usize) !Value { + _ = p; return if (n.is_integer) Value{ .Integer = std.fmt.parseInt(i64, n.slice(input, i), 10) catch |e| switch (e) { @@ -2815,7 +2816,7 @@ pub fn stringify( if (child_options.whitespace) |*child_whitespace| { child_whitespace.indent_level += 1; } - inline for (S.fields) |Field, field_i| { + inline for (S.fields) |Field| { // don't include void fields if (Field.field_type == void) continue; @@ -3114,6 +3115,7 @@ test "stringify struct with custom stringifier" { options: StringifyOptions, out_stream: anytype, ) !void { + _ = value; try out_stream.writeAll("[\"something special\","); try stringify(42, options, out_stream); try out_stream.writeByte(']'); diff --git a/lib/std/leb128.zig b/lib/std/leb128.zig index b1f56e21ab..6535c867f8 100644 --- a/lib/std/leb128.zig +++ b/lib/std/leb128.zig @@ -198,7 +198,7 @@ fn test_read_ileb128_seq(comptime T: type, comptime N: usize, encoded: []const u var reader = std.io.fixedBufferStream(encoded); var i: usize = 0; while (i < N) : (i += 1) { - const v1 = try readILEB128(T, reader.reader()); + _ = try readILEB128(T, reader.reader()); } } @@ -206,7 +206,7 @@ fn test_read_uleb128_seq(comptime T: type, comptime N: usize, encoded: []const u var reader = std.io.fixedBufferStream(encoded); var i: usize = 0; while (i < N) : (i += 1) { - const v1 = try readULEB128(T, reader.reader()); + _ = try readULEB128(T, reader.reader()); } } @@ -309,7 +309,6 @@ fn test_write_leb128(value: anytype) !void { const B = std.meta.Int(signedness, larger_type_bits); const bytes_needed = bn: { - const S = std.meta.Int(signedness, @sizeOf(T) * 8); if (@typeInfo(T).Int.bits <= 7) break :bn @as(u16, 1); const unused_bits = if (value < 0) @clz(T, ~value) else @clz(T, value); diff --git a/lib/std/linked_list.zig b/lib/std/linked_list.zig index 49006343c5..7bab3e2188 100644 --- a/lib/std/linked_list.zig +++ b/lib/std/linked_list.zig @@ -359,8 +359,8 @@ test "basic TailQueue test" { } } - var first = list.popFirst(); // {2, 3, 4, 5} - var last = list.pop(); // {2, 3, 4} + _ = list.popFirst(); // {2, 3, 4, 5} + _ = list.pop(); // {2, 3, 4} list.remove(&three); // {2, 4} try testing.expect(list.first.?.data == 2); diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index b2997536a6..cbae123189 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -458,6 +458,7 @@ pub const Mutable = struct { /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. pub fn sqrNoAlias(rma: *Mutable, a: Const, opt_allocator: ?*Allocator) void { + _ = opt_allocator; assert(rma.limbs.ptr != a.limbs.ptr); // illegal aliasing mem.set(Limb, rma.limbs, 0); @@ -676,6 +677,7 @@ pub const Mutable = struct { /// /// `limbs_buffer` is used for temporary storage during the operation. pub fn gcdNoAlias(rma: *Mutable, x: Const, y: Const, limbs_buffer: *std.ArrayList(Limb)) !void { + _ = limbs_buffer; assert(rma.limbs.ptr != x.limbs.ptr); // illegal aliasing assert(rma.limbs.ptr != y.limbs.ptr); // illegal aliasing return gcdLehmer(rma, x, y, allocator); @@ -1141,6 +1143,7 @@ pub const Const = struct { options: std.fmt.FormatOptions, out_stream: anytype, ) !void { + _ = options; comptime var radix = 10; comptime var case: std.fmt.Case = .lower; @@ -1618,6 +1621,7 @@ pub const Managed = struct { /// Converts self to a string in the requested base. Memory is allocated from the provided /// allocator and not the one present in self. pub fn toString(self: Managed, allocator: *Allocator, base: u8, case: std.fmt.Case) ![]u8 { + _ = allocator; if (base < 2 or base > 16) return error.InvalidBase; return self.toConst().toStringAlloc(self.allocator, base, case); } @@ -2000,8 +2004,6 @@ fn llmulacc_karatsuba(allocator: *Allocator, r: []Limb, x: []const Limb, y: []co } else { llsub(j1, y0[0..y0_len], y1[0..y1_len]); } - const j0_len = llnormalize(j0); - const j1_len = llnormalize(j1); if (x_cmp == y_cmp) { mem.set(Limb, tmp[0..length], 0); llmulacc(allocator, tmp, j0, j1); diff --git a/lib/std/math/big/rational.zig b/lib/std/math/big/rational.zig index 987889feca..8b7c2d45d6 100644 --- a/lib/std/math/big/rational.zig +++ b/lib/std/math/big/rational.zig @@ -204,7 +204,6 @@ pub const Rational = struct { const esize = math.floatExponentBits(T); const ebias = (1 << (esize - 1)) - 1; const emin = 1 - ebias; - const emax = ebias; if (self.p.eqZero()) { return 0; diff --git a/lib/std/math/complex/ldexp.zig b/lib/std/math/complex/ldexp.zig index 51ac105256..c0a6c7a934 100644 --- a/lib/std/math/complex/ldexp.zig +++ b/lib/std/math/complex/ldexp.zig @@ -12,8 +12,8 @@ const std = @import("../../std.zig"); const debug = std.debug; const math = std.math; -const cmath = math.complex; const testing = std.testing; +const cmath = math.complex; const Complex = cmath.Complex; /// Returns exp(z) scaled to avoid overflow. diff --git a/lib/std/math/expm1.zig b/lib/std/math/expm1.zig index d7a2e6a844..ebc76165ba 100644 --- a/lib/std/math/expm1.zig +++ b/lib/std/math/expm1.zig @@ -316,16 +316,12 @@ test "math.expm1_64" { } test "math.expm1_32.special" { - const epsilon = 0.000001; - try expect(math.isPositiveInf(expm1_32(math.inf(f32)))); try expect(expm1_32(-math.inf(f32)) == -1.0); try expect(math.isNan(expm1_32(math.nan(f32)))); } test "math.expm1_64.special" { - const epsilon = 0.000001; - try expect(math.isPositiveInf(expm1_64(math.inf(f64)))); try expect(expm1_64(-math.inf(f64)) == -1.0); try expect(math.isNan(expm1_64(math.nan(f64)))); diff --git a/lib/std/math/modf.zig b/lib/std/math/modf.zig index 6eef6fdd37..2a8cf00bbb 100644 --- a/lib/std/math/modf.zig +++ b/lib/std/math/modf.zig @@ -12,6 +12,7 @@ const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; const maxInt = std.math.maxInt; fn modf_result(comptime T: type) type { @@ -131,11 +132,7 @@ test "math.modf" { const a = modf(@as(f32, 1.0)); const b = modf32(1.0); // NOTE: No struct comparison on generic return type function? non-named, makes sense, but still. - try expect(a.ipart == b.ipart and a.fpart == b.fpart); - - const c = modf(@as(f64, 1.0)); - const d = modf64(1.0); - try expect(a.ipart == b.ipart and a.fpart == b.fpart); + try expectEqual(a, b); } test "math.modf32" { diff --git a/lib/std/mem.zig b/lib/std/mem.zig index ecdad6d314..2273db34cb 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -139,6 +139,11 @@ var failAllocator = Allocator{ .resizeFn = Allocator.noResize, }; fn failAllocatorAlloc(self: *Allocator, n: usize, alignment: u29, len_align: u29, ra: usize) Allocator.Error![]u8 { + _ = self; + _ = n; + _ = alignment; + _ = len_align; + _ = ra; return error.OutOfMemory; } diff --git a/lib/std/mem/Allocator.zig b/lib/std/mem/Allocator.zig index 6cc888fa10..1e13ed97b7 100644 --- a/lib/std/mem/Allocator.zig +++ b/lib/std/mem/Allocator.zig @@ -55,6 +55,10 @@ pub fn noResize( len_align: u29, ret_addr: usize, ) Error!usize { + _ = self; + _ = buf_align; + _ = len_align; + _ = ret_addr; if (new_len > buf.len) return error.OutOfMemory; return new_len; diff --git a/lib/std/meta.zig b/lib/std/meta.zig index e19208cd84..03fb4f80f1 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -654,7 +654,6 @@ pub fn TagPayload(comptime U: type, tag: Tag(U)) type { try testing.expect(trait.is(.Union)(U)); const info = @typeInfo(U).Union; - const tag_info = @typeInfo(Tag(U)).Enum; inline for (info.fields) |field_info| { if (comptime mem.eql(u8, field_info.name, @tagName(tag))) @@ -757,12 +756,6 @@ test "std.meta.eql" { .c = "12345".*, }; - const s_2 = S{ - .a = 1, - .b = 123.3, - .c = "54321".*, - }; - var s_3 = S{ .a = 134, .b = 123.3, @@ -850,6 +843,7 @@ pub const refAllDecls = @compileError("refAllDecls has been moved from std.meta pub fn declList(comptime Namespace: type, comptime Decl: type) []const *const Decl { const S = struct { fn declNameLessThan(context: void, lhs: *const Decl, rhs: *const Decl) bool { + _ = context; return mem.lessThan(u8, lhs.name, rhs.name); } }; diff --git a/lib/std/meta/trailer_flags.zig b/lib/std/meta/trailer_flags.zig index 94f2043b00..595f6917d9 100644 --- a/lib/std/meta/trailer_flags.zig +++ b/lib/std/meta/trailer_flags.zig @@ -96,18 +96,18 @@ pub fn TrailerFlags(comptime Fields: type) type { pub fn ptr(self: Self, p: [*]align(@alignOf(Fields)) u8, comptime field: FieldEnum) *Field(field) { if (@sizeOf(Field(field)) == 0) return undefined; - const off = self.offset(p, field); + const off = self.offset(field); return @ptrCast(*Field(field), @alignCast(@alignOf(Field(field)), p + off)); } pub fn ptrConst(self: Self, p: [*]align(@alignOf(Fields)) const u8, comptime field: FieldEnum) *const Field(field) { if (@sizeOf(Field(field)) == 0) return undefined; - const off = self.offset(p, field); + const off = self.offset(field); return @ptrCast(*const Field(field), @alignCast(@alignOf(Field(field)), p + off)); } - pub fn offset(self: Self, p: [*]align(@alignOf(Fields)) const u8, comptime field: FieldEnum) usize { + pub fn offset(self: Self, comptime field: FieldEnum) usize { var off: usize = 0; inline for (@typeInfo(Fields).Struct.fields) |field_info, i| { const active = (self.bits & (1 << i)) != 0; diff --git a/lib/std/multi_array_list.zig b/lib/std/multi_array_list.zig index 7a071a8928..9707c0634a 100644 --- a/lib/std/multi_array_list.zig +++ b/lib/std/multi_array_list.zig @@ -92,6 +92,7 @@ pub fn MultiArrayList(comptime S: type) type { } const Sort = struct { fn lessThan(trash: *i32, lhs: Data, rhs: Data) bool { + _ = trash; return lhs.alignment > rhs.alignment; } }; @@ -221,7 +222,7 @@ pub fn MultiArrayList(comptime S: type) type { /// retain list ordering. pub fn swapRemove(self: *Self, index: usize) void { const slices = self.slice(); - inline for (fields) |field_info, i| { + inline for (fields) |_, i| { const field_slice = slices.items(@intToEnum(Field, i)); field_slice[index] = field_slice[self.len - 1]; field_slice[self.len - 1] = undefined; @@ -233,7 +234,7 @@ pub fn MultiArrayList(comptime S: type) type { /// after it to preserve order. pub fn orderedRemove(self: *Self, index: usize) void { const slices = self.slice(); - inline for (fields) |field_info, field_index| { + inline for (fields) |_, field_index| { const field_slice = slices.items(@intToEnum(Field, field_index)); var i = index; while (i < self.len - 1) : (i += 1) { diff --git a/lib/std/net.zig b/lib/std/net.zig index ff0e299a7e..46d9bee15d 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -270,6 +270,8 @@ pub const Ip4Address = extern struct { options: std.fmt.FormatOptions, out_stream: anytype, ) !void { + _ = fmt; + _ = options; const bytes = @ptrCast(*const [4]u8, &self.sa.addr); try std.fmt.format(out_stream, "{}.{}.{}.{}:{}", .{ bytes[0], @@ -281,6 +283,7 @@ pub const Ip4Address = extern struct { } pub fn getOsSockLen(self: Ip4Address) os.socklen_t { + _ = self; return @sizeOf(os.sockaddr_in); } }; @@ -556,6 +559,8 @@ pub const Ip6Address = extern struct { options: std.fmt.FormatOptions, out_stream: anytype, ) !void { + _ = fmt; + _ = options; const port = mem.bigToNative(u16, self.sa.port); if (mem.eql(u8, self.sa.addr[0..12], &[_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff })) { try std.fmt.format(out_stream, "[::ffff:{}.{}.{}.{}]:{}", .{ @@ -598,6 +603,7 @@ pub const Ip6Address = extern struct { } pub fn getOsSockLen(self: Ip6Address) os.socklen_t { + _ = self; return @sizeOf(os.sockaddr_in6); } }; @@ -1062,6 +1068,7 @@ fn IN6_IS_ADDR_SITELOCAL(a: [16]u8) bool { // Parameters `b` and `a` swapped to make this descending. fn addrCmpLessThan(context: void, b: LookupAddr, a: LookupAddr) bool { + _ = context; return a.sortkey < b.sortkey; } diff --git a/lib/std/once.zig b/lib/std/once.zig index c56e572570..05f003c796 100644 --- a/lib/std/once.zig +++ b/lib/std/once.zig @@ -61,6 +61,7 @@ test "Once executes its function just once" { for (threads) |*handle| { handle.* = try std.Thread.spawn(struct { fn thread_fn(x: u8) void { + _ = x; global_once.call(); } }.thread_fn, 0); diff --git a/lib/std/os.zig b/lib/std/os.zig index 8598eceb6e..968d0a26f6 100644 --- a/lib/std/os.zig +++ b/lib/std/os.zig @@ -1164,6 +1164,7 @@ fn openOptionsFromFlags(flags: u32) windows.OpenFileOptions { /// TODO currently, this function does not handle all flag combinations /// or makes use of perm argument. pub fn openW(file_path_w: []const u16, flags: u32, perm: mode_t) OpenError!fd_t { + _ = perm; var options = openOptionsFromFlags(flags); options.dir = std.fs.cwd().fd; return windows.OpenFile(file_path_w, options) catch |err| switch (err) { @@ -1273,6 +1274,7 @@ pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t) /// TODO currently, this function does not handle all flag combinations /// or makes use of perm argument. pub fn openatW(dir_fd: fd_t, file_path_w: []const u16, flags: u32, mode: mode_t) OpenError!fd_t { + _ = mode; var options = openOptionsFromFlags(flags); options.dir = dir_fd; return windows.OpenFile(file_path_w, options) catch |err| switch (err) { @@ -2169,6 +2171,7 @@ pub fn mkdirat(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!v pub const mkdiratC = @compileError("deprecated: renamed to mkdiratZ"); pub fn mkdiratWasi(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!void { + _ = mode; switch (wasi.path_create_directory(dir_fd, sub_dir_path.ptr, sub_dir_path.len)) { wasi.ESUCCESS => return, wasi.EACCES => return error.AccessDenied, @@ -2216,6 +2219,7 @@ pub fn mkdiratZ(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirErr } pub fn mkdiratW(dir_fd: fd_t, sub_path_w: []const u16, mode: u32) MakeDirError!void { + _ = mode; const sub_dir_handle = windows.OpenFile(sub_path_w, .{ .dir = dir_fd, .access_mask = windows.GENERIC_READ | windows.SYNCHRONIZE, @@ -2291,6 +2295,7 @@ pub fn mkdirZ(dir_path: [*:0]const u8, mode: u32) MakeDirError!void { /// Windows-only. Same as `mkdir` but the parameters is WTF16 encoded. pub fn mkdirW(dir_path_w: []const u16, mode: u32) MakeDirError!void { + _ = mode; const sub_dir_handle = windows.OpenFile(dir_path_w, .{ .dir = std.fs.cwd().fd, .access_mask = windows.GENERIC_READ | windows.SYNCHRONIZE, @@ -3868,6 +3873,7 @@ pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void { /// Otherwise use `access` or `accessC`. /// TODO currently this ignores `mode`. pub fn accessW(path: [*:0]const u16, mode: u32) windows.GetFileAttributesError!void { + _ = mode; const ret = try windows.GetFileAttributesW(path); if (ret != windows.INVALID_FILE_ATTRIBUTES) { return; @@ -3918,6 +3924,8 @@ pub fn faccessatZ(dirfd: fd_t, path: [*:0]const u8, mode: u32, flags: u32) Acces /// is NtDll-prefixed, null-terminated, WTF-16 encoded. /// TODO currently this ignores `mode` and `flags` pub fn faccessatW(dirfd: fd_t, sub_path_w: [*:0]const u16, mode: u32, flags: u32) AccessError!void { + _ = mode; + _ = flags; if (sub_path_w[0] == '.' and sub_path_w[1] == 0) { return; } @@ -4895,6 +4903,8 @@ pub fn res_mkquery( newrr: ?[*]const u8, buf: []u8, ) usize { + _ = data; + _ = newrr; // This implementation is ported from musl libc. // A more idiomatic "ziggy" implementation would be welcome. var name = dname; @@ -5341,7 +5351,7 @@ pub fn sendfile( ENXIO => return error.Unseekable, ESPIPE => return error.Unseekable, else => |err| { - const discard = unexpectedErrno(err); + unexpectedErrno(err) catch {}; break :sf; }, } @@ -5422,7 +5432,7 @@ pub fn sendfile( EPIPE => return error.BrokenPipe, else => { - const discard = unexpectedErrno(err); + unexpectedErrno(err) catch {}; if (amt != 0) { return amt; } else { @@ -5484,7 +5494,7 @@ pub fn sendfile( EPIPE => return error.BrokenPipe, else => { - const discard = unexpectedErrno(err); + unexpectedErrno(err) catch {}; if (amt != 0) { return amt; } else { diff --git a/lib/std/os/bits/linux.zig b/lib/std/os/bits/linux.zig index d4491da6d0..7501d54bbe 100644 --- a/lib/std/os/bits/linux.zig +++ b/lib/std/os/bits/linux.zig @@ -1286,7 +1286,7 @@ pub const CAP_BLOCK_SUSPEND = 36; pub const CAP_AUDIT_READ = 37; pub const CAP_LAST_CAP = CAP_AUDIT_READ; -pub fn cap_valid(u8: x) bool { +pub fn cap_valid(x: u8) bool { return x >= 0 and x <= CAP_LAST_CAP; } diff --git a/lib/std/os/linux.zig b/lib/std/os/linux.zig index 792b4dff96..26f489a345 100644 --- a/lib/std/os/linux.zig +++ b/lib/std/os/linux.zig @@ -70,6 +70,7 @@ fn splitValueLE64(val: i64) [2]u32 { }; } fn splitValueBE64(val: i64) [2]u32 { + const u = @bitCast(u64, val); return [2]u32{ @truncate(u32, u >> 32), @truncate(u32, u), @@ -1022,7 +1023,7 @@ pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize for (msgvec[0..kvlen]) |*msg, i| { var size: i32 = 0; const msg_iovlen = @intCast(usize, msg.msg_hdr.msg_iovlen); // kernel side this is treated as unsigned - for (msg.msg_hdr.msg_iov[0..msg_iovlen]) |iov, j| { + for (msg.msg_hdr.msg_iov[0..msg_iovlen]) |iov| { if (iov.iov_len > std.math.maxInt(i32) or @addWithOverflow(i32, size, @intCast(i32, iov.iov_len), &size)) { // batch-send all messages up to the current message if (next_unsent < i) { diff --git a/lib/std/os/linux/bpf.zig b/lib/std/os/linux/bpf.zig index 4249e7774b..86993083e3 100644 --- a/lib/std/os/linux/bpf.zig +++ b/lib/std/os/linux/bpf.zig @@ -1513,7 +1513,7 @@ pub fn map_create(map_type: MapType, key_size: u32, value_size: u32, max_entries EINVAL => error.MapTypeOrAttrInvalid, ENOMEM => error.SystemResources, EPERM => error.AccessDenied, - else => |err| unexpectedErrno(rc), + else => |err| unexpectedErrno(err), }; } @@ -1539,7 +1539,7 @@ pub fn map_lookup_elem(fd: fd_t, key: []const u8, value: []u8) !void { EINVAL => return error.FieldInAttrNeedsZeroing, ENOENT => return error.NotFound, EPERM => return error.AccessDenied, - else => |err| return unexpectedErrno(rc), + else => |err| return unexpectedErrno(err), } } diff --git a/lib/std/os/linux/io_uring.zig b/lib/std/os/linux/io_uring.zig index ca80a381f5..dd7956f0c1 100644 --- a/lib/std/os/linux/io_uring.zig +++ b/lib/std/os/linux/io_uring.zig @@ -284,6 +284,7 @@ pub const IO_Uring = struct { } fn copy_cqes_ready(self: *IO_Uring, cqes: []io_uring_cqe, wait_nr: u32) u32 { + _ = wait_nr; const ready = self.cq_ready(); const count = std.math.min(cqes.len, ready); var head = self.cq.head.*; @@ -320,6 +321,7 @@ pub const IO_Uring = struct { /// Not idempotent, calling more than once will result in other CQEs being lost. /// Matches the implementation of cqe_seen() in liburing. pub fn cqe_seen(self: *IO_Uring, cqe: *io_uring_cqe) void { + _ = cqe; self.cq_advance(1); } @@ -728,6 +730,7 @@ pub const CompletionQueue = struct { } pub fn deinit(self: *CompletionQueue) void { + _ = self; // A no-op since we now share the mmap with the submission queue. // Here for symmetry with the submission queue, and for any future feature support. } @@ -1272,12 +1275,12 @@ test "accept/connect/send/recv" { var accept_addr: os.sockaddr = undefined; var accept_addr_len: os.socklen_t = @sizeOf(@TypeOf(accept_addr)); - const accept = try ring.accept(0xaaaaaaaa, server, &accept_addr, &accept_addr_len, 0); + _ = try ring.accept(0xaaaaaaaa, server, &accept_addr, &accept_addr_len, 0); try testing.expectEqual(@as(u32, 1), try ring.submit()); const client = try os.socket(address.any.family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0); defer os.close(client); - const connect = try ring.connect(0xcccccccc, client, &address.any, address.getOsSockLen()); + _ = try ring.connect(0xcccccccc, client, &address.any, address.getOsSockLen()); try testing.expectEqual(@as(u32, 1), try ring.submit()); var cqe_accept = try ring.copy_cqe(); @@ -1305,7 +1308,7 @@ test "accept/connect/send/recv" { const send = try ring.send(0xeeeeeeee, client, buffer_send[0..], 0); send.flags |= linux.IOSQE_IO_LINK; - const recv = try ring.recv(0xffffffff, cqe_accept.res, buffer_recv[0..], 0); + _ = try ring.recv(0xffffffff, cqe_accept.res, buffer_recv[0..], 0); try testing.expectEqual(@as(u32, 2), try ring.submit()); const cqe_send = try ring.copy_cqe(); diff --git a/lib/std/os/linux/mips.zig b/lib/std/os/linux/mips.zig index ddb3103cfa..a04a592f3b 100644 --- a/lib/std/os/linux/mips.zig +++ b/lib/std/os/linux/mips.zig @@ -31,7 +31,8 @@ pub fn syscall_pipe(fd: *[2]i32) usize { \\ sw $3, 4($4) \\ 2: : [ret] "={$2}" (-> usize) - : [number] "{$2}" (@enumToInt(SYS.pipe)) + : [number] "{$2}" (@enumToInt(SYS.pipe)), + [fd] "{$4}" (fd) : "memory", "cc", "$7" ); } diff --git a/lib/std/os/linux/vdso.zig b/lib/std/os/linux/vdso.zig index f2e4f1f5bc..f42bb06452 100644 --- a/lib/std/os/linux/vdso.zig +++ b/lib/std/os/linux/vdso.zig @@ -15,7 +15,6 @@ pub fn lookup(vername: []const u8, name: []const u8) usize { const eh = @intToPtr(*elf.Ehdr, vdso_addr); var ph_addr: usize = vdso_addr + eh.e_phoff; - const ph = @intToPtr(*elf.Phdr, ph_addr); var maybe_dynv: ?[*]usize = null; var base: usize = maxInt(usize); diff --git a/lib/std/os/test.zig b/lib/std/os/test.zig index 6e2aa2aeb9..7a88ecd7ca 100644 --- a/lib/std/os/test.zig +++ b/lib/std/os/test.zig @@ -353,6 +353,7 @@ test "spawn threads" { } fn start1(ctx: void) u8 { + _ = ctx; return 0; } @@ -379,6 +380,7 @@ test "thread local storage" { threadlocal var x: i32 = 1234; fn testTls(context: void) !void { + _ = context; if (x != 1234) return error.TlsBadStartValue; x += 1; if (x != 1235) return error.TlsBadEndValue; @@ -425,6 +427,7 @@ const IterFnError = error{ }; fn iter_fn(info: *dl_phdr_info, size: usize, counter: *usize) IterFnError!void { + _ = size; // Count how many libraries are loaded counter.* += @as(usize, 1); @@ -731,6 +734,7 @@ test "sigaction" { const S = struct { fn handler(sig: i32, info: *const os.siginfo_t, ctx_ptr: ?*const c_void) callconv(.C) void { + _ = ctx_ptr; // Check that we received the correct signal. switch (native_os) { .netbsd => { diff --git a/lib/std/os/uefi.zig b/lib/std/os/uefi.zig index 1942165999..4bb8e37559 100644 --- a/lib/std/os/uefi.zig +++ b/lib/std/os/uefi.zig @@ -37,6 +37,7 @@ pub const Guid = extern struct { options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = options; if (f.len == 0) { return std.fmt.format(writer, "{x:0>8}-{x:0>4}-{x:0>4}-{x:0>2}{x:0>2}-{x:0>12}", .{ self.time_low, diff --git a/lib/std/os/uefi/protocols/managed_network_protocol.zig b/lib/std/os/uefi/protocols/managed_network_protocol.zig index 6652107a1a..0da6d902f3 100644 --- a/lib/std/os/uefi/protocols/managed_network_protocol.zig +++ b/lib/std/os/uefi/protocols/managed_network_protocol.zig @@ -35,6 +35,7 @@ pub const ManagedNetworkProtocol = extern struct { /// Translates an IP multicast address to a hardware (MAC) multicast address. /// This function may be unsupported in some MNP implementations. pub fn mcastIpToMac(self: *const ManagedNetworkProtocol, ipv6flag: bool, ipaddress: *const c_void, mac_address: *MacAddress) Status { + _ = mac_address; return self._mcast_ip_to_mac(self, ipv6flag, ipaddress); } diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index 23252011c2..1fade2a462 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -1156,7 +1156,6 @@ pub fn GetFinalPathNameByHandle( &mount_points_struct.MountPoints[0], )[0..mount_points_struct.NumberOfMountPoints]; - var found: bool = false; for (mount_points) |mount_point| { const symlink = @ptrCast( [*]const u16, diff --git a/lib/std/packed_int_array.zig b/lib/std/packed_int_array.zig index ec401e98e2..571aae6e4d 100644 --- a/lib/std/packed_int_array.zig +++ b/lib/std/packed_int_array.zig @@ -194,6 +194,7 @@ pub fn PackedIntArrayEndian(comptime Int: type, comptime endian: Endian, comptim ///Returns the number of elements in the packed array pub fn len(self: Self) usize { + _ = self; return int_count; } diff --git a/lib/std/pdb.zig b/lib/std/pdb.zig index 4f3962ceb5..30b98941b0 100644 --- a/lib/std/pdb.zig +++ b/lib/std/pdb.zig @@ -594,6 +594,7 @@ pub const Pdb = struct { error.InvalidValue => return error.InvalidDebugInfo, else => |e| return e, }; + _ = version; sect_cont_offset += @sizeOf(u32); } while (sect_cont_offset != section_contrib_size) { @@ -617,6 +618,7 @@ pub const Pdb = struct { // Parse the InfoStreamHeader. const version = try reader.readIntLittle(u32); const signature = try reader.readIntLittle(u32); + _ = signature; const age = try reader.readIntLittle(u32); const guid = try reader.readBytesNoEof(16); @@ -673,6 +675,7 @@ pub const Pdb = struct { } pub fn getSymbolName(self: *Pdb, module: *Module, address: u64) ?[]const u8 { + _ = self; std.debug.assert(module.populated); var symbol_i: usize = 0; @@ -904,7 +907,7 @@ const Msf = struct { // These streams are not used, but still participate in the file // and must be taken into account when resolving stream indices. const Nil = 0xFFFFFFFF; - for (stream_sizes) |*s, i| { + for (stream_sizes) |*s| { const size = try directory.reader().readIntLittle(u32); s.* = if (size == Nil) 0 else blockCountFromSize(size, superblock.BlockSize); } diff --git a/lib/std/priority_dequeue.zig b/lib/std/priority_dequeue.zig index 0bb1f13503..81329a0a74 100644 --- a/lib/std/priority_dequeue.zig +++ b/lib/std/priority_dequeue.zig @@ -428,7 +428,7 @@ pub fn PriorityDequeue(comptime T: type) type { warn("{}, ", .{e}); } warn("array: ", .{}); - for (self.items) |e, i| { + for (self.items) |e| { warn("{}, ", .{e}); } warn("len: {} ", .{self.len}); diff --git a/lib/std/priority_queue.zig b/lib/std/priority_queue.zig index 4e5320a92b..de68442ea7 100644 --- a/lib/std/priority_queue.zig +++ b/lib/std/priority_queue.zig @@ -249,7 +249,7 @@ pub fn PriorityQueue(comptime T: type) type { warn("{}, ", .{e}); } warn("array: ", .{}); - for (self.items) |e, i| { + for (self.items) |e| { warn("{}, ", .{e}); } warn("len: {} ", .{self.len}); diff --git a/lib/std/process.zig b/lib/std/process.zig index d5a2045699..83926ee5af 100644 --- a/lib/std/process.zig +++ b/lib/std/process.zig @@ -419,6 +419,7 @@ pub const ArgIteratorWindows = struct { }; } fn emitBackslashes(self: *ArgIteratorWindows, buf: *std.ArrayList(u16), emit_count: usize) !void { + _ = self; var i: usize = 0; while (i < emit_count) : (i += 1) { try buf.append(std.mem.nativeToLittle(u16, '\\')); @@ -748,6 +749,7 @@ pub fn getSelfExeSharedLibPaths(allocator: *Allocator) error{OutOfMemory}![][:0] } try os.dl_iterate_phdr(&paths, error{OutOfMemory}, struct { fn callback(info: *os.dl_phdr_info, size: usize, list: *List) !void { + _ = size; const name = info.dlpi_name orelse return; if (name[0] == '/') { const item = try list.allocator.dupeZ(u8, mem.spanZ(name)); diff --git a/lib/std/rand/ziggurat.zig b/lib/std/rand/ziggurat.zig index fe120943d7..c01f7c659a 100644 --- a/lib/std/rand/ziggurat.zig +++ b/lib/std/rand/ziggurat.zig @@ -175,5 +175,5 @@ test "exp dist sanity" { test "table gen" { if (please_windows_dont_oom) return error.SkipZigTest; - const table = NormDist; + _ = NormDist; } diff --git a/lib/std/sort.zig b/lib/std/sort.zig index 2d84beaef6..67a4394b1e 100644 --- a/lib/std/sort.zig +++ b/lib/std/sort.zig @@ -37,9 +37,11 @@ pub fn binarySearch( test "binarySearch" { const S = struct { fn order_u32(context: void, lhs: u32, rhs: u32) math.Order { + _ = context; return math.order(lhs, rhs); } fn order_i32(context: void, lhs: i32, rhs: i32) math.Order { + _ = context; return math.order(lhs, rhs); } }; @@ -1133,6 +1135,7 @@ fn swap( pub fn asc(comptime T: type) fn (void, T, T) bool { const impl = struct { fn inner(context: void, a: T, b: T) bool { + _ = context; return a < b; } }; @@ -1144,6 +1147,7 @@ pub fn asc(comptime T: type) fn (void, T, T) bool { pub fn desc(comptime T: type) fn (void, T, T) bool { const impl = struct { fn inner(context: void, a: T, b: T) bool { + _ = context; return a > b; } }; diff --git a/lib/std/special/c.zig b/lib/std/special/c.zig index 1377212870..a6de965f90 100644 --- a/lib/std/special/c.zig +++ b/lib/std/special/c.zig @@ -160,6 +160,7 @@ fn strncmp(_l: [*:0]const u8, _r: [*:0]const u8, _n: usize) callconv(.C) c_int { } fn strerror(errnum: c_int) callconv(.C) [*:0]const u8 { + _ = errnum; return "TODO strerror implementation"; } @@ -173,6 +174,7 @@ test "strncmp" { // Avoid dragging in the runtime safety mechanisms into this .o file, // unless we're trying to test this file. pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { + _ = error_return_trace; if (builtin.is_test) { @setCold(true); std.debug.panic("{s}", .{msg}); diff --git a/lib/std/special/compiler_rt.zig b/lib/std/special/compiler_rt.zig index a777067800..dcbdebec73 100644 --- a/lib/std/special/compiler_rt.zig +++ b/lib/std/special/compiler_rt.zig @@ -602,6 +602,7 @@ pub usingnamespace @import("compiler_rt/atomics.zig"); // Avoid dragging in the runtime safety mechanisms into this .o file, // unless we're trying to test this file. pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { + _ = error_return_trace; @setCold(true); if (is_test) { std.debug.panic("{s}", .{msg}); diff --git a/lib/std/special/compiler_rt/addXf3.zig b/lib/std/special/compiler_rt/addXf3.zig index 5a2f3c976c..c5c7397680 100644 --- a/lib/std/special/compiler_rt/addXf3.zig +++ b/lib/std/special/compiler_rt/addXf3.zig @@ -83,7 +83,6 @@ fn addXf3(comptime T: type, a: T, b: T) T { const signBit = (@as(Z, 1) << (significandBits + exponentBits)); const maxExponent = ((1 << exponentBits) - 1); - const exponentBias = (maxExponent >> 1); const implicitBit = (@as(Z, 1) << significandBits); const quietBit = implicitBit >> 1; @@ -98,10 +97,6 @@ fn addXf3(comptime T: type, a: T, b: T) T { const aAbs = aRep & absMask; const bAbs = bRep & absMask; - const negative = (aRep & signBit) != 0; - const exponent = @intCast(i32, aAbs >> significandBits) - exponentBias; - const significand = (aAbs & significandMask) | implicitBit; - const infRep = @bitCast(Z, std.math.inf(T)); // Detect if a or b is zero, infinity, or NaN. diff --git a/lib/std/special/compiler_rt/atomics.zig b/lib/std/special/compiler_rt/atomics.zig index e448a580ca..1b592da019 100644 --- a/lib/std/special/compiler_rt/atomics.zig +++ b/lib/std/special/compiler_rt/atomics.zig @@ -80,18 +80,21 @@ var spinlocks: SpinlockTable = SpinlockTable{}; // Those work on any object no matter the pointer alignment nor its size. fn __atomic_load(size: u32, src: [*]u8, dest: [*]u8, model: i32) callconv(.C) void { + _ = model; var sl = spinlocks.get(@ptrToInt(src)); defer sl.release(); @memcpy(dest, src, size); } fn __atomic_store(size: u32, dest: [*]u8, src: [*]u8, model: i32) callconv(.C) void { + _ = model; var sl = spinlocks.get(@ptrToInt(dest)); defer sl.release(); @memcpy(dest, src, size); } fn __atomic_exchange(size: u32, ptr: [*]u8, val: [*]u8, old: [*]u8, model: i32) callconv(.C) void { + _ = model; var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); @memcpy(old, ptr, size); @@ -106,6 +109,8 @@ fn __atomic_compare_exchange( success: i32, failure: i32, ) callconv(.C) i32 { + _ = success; + _ = failure; var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); for (ptr[0..size]) |b, i| { @@ -135,6 +140,7 @@ comptime { fn atomicLoadFn(comptime T: type) fn (*T, i32) callconv(.C) T { return struct { fn atomic_load_N(src: *T, model: i32) callconv(.C) T { + _ = model; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(src)); defer sl.release(); @@ -162,6 +168,7 @@ comptime { fn atomicStoreFn(comptime T: type) fn (*T, T, i32) callconv(.C) void { return struct { fn atomic_store_N(dst: *T, value: T, model: i32) callconv(.C) void { + _ = model; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(dst)); defer sl.release(); @@ -189,6 +196,7 @@ comptime { fn atomicExchangeFn(comptime T: type) fn (*T, T, i32) callconv(.C) T { return struct { fn atomic_exchange_N(ptr: *T, val: T, model: i32) callconv(.C) T { + _ = model; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); @@ -218,6 +226,8 @@ comptime { fn atomicCompareExchangeFn(comptime T: type) fn (*T, *T, T, i32, i32) callconv(.C) i32 { return struct { fn atomic_compare_exchange_N(ptr: *T, expected: *T, desired: T, success: i32, failure: i32) callconv(.C) i32 { + _ = success; + _ = failure; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); @@ -255,6 +265,7 @@ comptime { fn fetchFn(comptime T: type, comptime op: builtin.AtomicRmwOp) fn (*T, T, i32) callconv(.C) T { return struct { pub fn fetch_op_N(ptr: *T, val: T, model: i32) callconv(.C) T { + _ = model; if (@sizeOf(T) > largest_atomic_size) { var sl = spinlocks.get(@ptrToInt(ptr)); defer sl.release(); diff --git a/lib/std/special/compiler_rt/comparedf2_test.zig b/lib/std/special/compiler_rt/comparedf2_test.zig index b0916c10ae..018d95c0ae 100644 --- a/lib/std/special/compiler_rt/comparedf2_test.zig +++ b/lib/std/special/compiler_rt/comparedf2_test.zig @@ -100,7 +100,7 @@ const test_vectors = init: { }; test "compare f64" { - for (test_vectors) |vector, i| { + for (test_vectors) |vector| { try std.testing.expect(test__cmpdf2(vector)); } } diff --git a/lib/std/special/compiler_rt/comparesf2_test.zig b/lib/std/special/compiler_rt/comparesf2_test.zig index 9719873f62..10ffc3c063 100644 --- a/lib/std/special/compiler_rt/comparesf2_test.zig +++ b/lib/std/special/compiler_rt/comparesf2_test.zig @@ -100,7 +100,7 @@ const test_vectors = init: { }; test "compare f32" { - for (test_vectors) |vector, i| { + for (test_vectors) |vector| { try std.testing.expect(test__cmpsf2(vector)); } } diff --git a/lib/std/special/compiler_rt/divtf3.zig b/lib/std/special/compiler_rt/divtf3.zig index 9c18e79dd5..d8ef463e49 100644 --- a/lib/std/special/compiler_rt/divtf3.zig +++ b/lib/std/special/compiler_rt/divtf3.zig @@ -12,7 +12,6 @@ const wideMultiply = @import("divdf3.zig").wideMultiply; pub fn __divtf3(a: f128, b: f128) callconv(.C) f128 { @setRuntimeSafety(builtin.is_test); const Z = std.meta.Int(.unsigned, 128); - const SignedZ = std.meta.Int(.signed, 128); const significandBits = std.math.floatMantissaBits(f128); const exponentBits = std.math.floatExponentBits(f128); diff --git a/lib/std/special/compiler_rt/extendXfYf2.zig b/lib/std/special/compiler_rt/extendXfYf2.zig index 59be8441fa..9a42a938b9 100644 --- a/lib/std/special/compiler_rt/extendXfYf2.zig +++ b/lib/std/special/compiler_rt/extendXfYf2.zig @@ -46,7 +46,6 @@ fn extendXfYf2(comptime dst_t: type, comptime src_t: type, a: std.meta.Int(.unsi const dst_rep_t = std.meta.Int(.unsigned, @typeInfo(dst_t).Float.bits); const srcSigBits = std.math.floatMantissaBits(src_t); const dstSigBits = std.math.floatMantissaBits(dst_t); - const SrcShift = std.math.Log2Int(src_rep_t); const DstShift = std.math.Log2Int(dst_rep_t); // Various constants whose values follow from the type parameters. diff --git a/lib/std/special/compiler_rt/fixuint.zig b/lib/std/special/compiler_rt/fixuint.zig index 755e1b8bb2..518b5de4e4 100644 --- a/lib/std/special/compiler_rt/fixuint.zig +++ b/lib/std/special/compiler_rt/fixuint.zig @@ -16,7 +16,6 @@ pub fn fixuint(comptime fp_t: type, comptime fixuint_t: type, a: fp_t) fixuint_t else => unreachable, }; const typeWidth = @typeInfo(rep_t).Int.bits; - const srep_t = @import("std").meta.Int(.signed, typeWidth); const significandBits = switch (fp_t) { f32 => 23, f64 => 52, diff --git a/lib/std/special/compiler_rt/truncXfYf2.zig b/lib/std/special/compiler_rt/truncXfYf2.zig index e85aa363db..9f34812199 100644 --- a/lib/std/special/compiler_rt/truncXfYf2.zig +++ b/lib/std/special/compiler_rt/truncXfYf2.zig @@ -50,7 +50,6 @@ fn truncXfYf2(comptime dst_t: type, comptime src_t: type, a: src_t) dst_t { const srcSigBits = std.math.floatMantissaBits(src_t); const dstSigBits = std.math.floatMantissaBits(dst_t); const SrcShift = std.math.Log2Int(src_rep_t); - const DstShift = std.math.Log2Int(dst_rep_t); // Various constants whose values follow from the type parameters. // Any reasonable optimizer will fold and propagate all of these. diff --git a/lib/std/special/ssp.zig b/lib/std/special/ssp.zig index 81db44a534..6eda11b2e2 100644 --- a/lib/std/special/ssp.zig +++ b/lib/std/special/ssp.zig @@ -27,6 +27,8 @@ extern fn memmove(dest: ?[*]u8, src: ?[*]const u8, n: usize) callconv(.C) ?[*]u8 // Avoid dragging in the runtime safety mechanisms into this .o file. pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { + _ = msg; + _ = error_return_trace; @setCold(true); if (@hasDecl(std.os, "abort")) std.os.abort(); diff --git a/lib/std/target.zig b/lib/std/target.zig index faebe665ab..02ce44d477 100644 --- a/lib/std/target.zig +++ b/lib/std/target.zig @@ -157,7 +157,7 @@ pub const Target = struct { pub fn format( self: WindowsVersion, comptime fmt: []const u8, - options: std.fmt.FormatOptions, + _: std.fmt.FormatOptions, out_stream: anytype, ) !void { if (fmt.len > 0 and fmt[0] == 's') { diff --git a/lib/std/testing.zig b/lib/std/testing.zig index be3e76dcdb..a370c21c29 100644 --- a/lib/std/testing.zig +++ b/lib/std/testing.zig @@ -191,7 +191,6 @@ test "expectEqual.union(enum)" { }; const a10 = T{ .a = 10 }; - const a20 = T{ .a = 20 }; try expectEqual(a10, a10); } diff --git a/lib/std/unicode.zig b/lib/std/unicode.zig index 48310e17da..0b0e470efb 100644 --- a/lib/std/unicode.zig +++ b/lib/std/unicode.zig @@ -210,7 +210,7 @@ pub fn utf8ValidateSlice(s: []const u8) bool { return false; } i += cp_len; - } else |err| { + } else |_| { return false; } } diff --git a/lib/std/unicode/throughput_test.zig b/lib/std/unicode/throughput_test.zig index 8f9f9d9cb7..e49da8ceaf 100644 --- a/lib/std/unicode/throughput_test.zig +++ b/lib/std/unicode/throughput_test.zig @@ -47,8 +47,6 @@ fn benchmarkCodepointCount(buf: []const u8) !ResultCount { pub fn main() !void { const stdout = std.io.getStdOut().writer(); - const args = try std.process.argsAlloc(std.heap.page_allocator); - try stdout.print("short ASCII strings\n", .{}); { const result = try benchmarkCodepointCount("abc"); diff --git a/lib/std/x/net/ip.zig b/lib/std/x/net/ip.zig index 7f2d82d208..409a8ebadf 100644 --- a/lib/std/x/net/ip.zig +++ b/lib/std/x/net/ip.zig @@ -53,6 +53,8 @@ pub const Address = union(enum) { opts: fmt.FormatOptions, writer: anytype, ) !void { + _ = opts; + _ = layout; switch (self) { .ipv4 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }), .ipv6 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }), diff --git a/lib/std/x/os/io.zig b/lib/std/x/os/io.zig index 1c0e0e9130..b0df3f947e 100644 --- a/lib/std/x/os/io.zig +++ b/lib/std/x/os/io.zig @@ -122,7 +122,6 @@ test "reactor/linux: drive async tcp client/listener pair" { const IPv4 = std.x.os.IPv4; const IPv6 = std.x.os.IPv6; - const Socket = std.x.os.Socket; const reactor = try Reactor.init(.{ .close_on_exec = true }); defer reactor.deinit(); diff --git a/lib/std/x/os/net.zig b/lib/std/x/os/net.zig index bbb2c105a7..d946926932 100644 --- a/lib/std/x/os/net.zig +++ b/lib/std/x/os/net.zig @@ -143,6 +143,7 @@ pub const IPv4 = extern struct { opts: fmt.FormatOptions, writer: anytype, ) !void { + _ = opts; if (comptime layout.len != 0 and layout[0] != 's') { @compileError("Unsupported format specifier for IPv4 type '" ++ layout ++ "'."); } @@ -352,6 +353,7 @@ pub const IPv6 = extern struct { opts: fmt.FormatOptions, writer: anytype, ) !void { + _ = opts; const specifier = comptime &[_]u8{if (layout.len == 0) 'x' else switch (layout[0]) { 'x', 'X' => |specifier| specifier, 's' => 'x', diff --git a/lib/std/x/os/socket.zig b/lib/std/x/os/socket.zig index 61e47939f8..9da74d5b0e 100644 --- a/lib/std/x/os/socket.zig +++ b/lib/std/x/os/socket.zig @@ -117,7 +117,7 @@ pub const Socket = struct { }; } - /// Returns the number of bytes that make up the `sockaddr` equivalent to the address. + /// Returns the number of bytes that make up the `sockaddr` equivalent to the address. pub fn getNativeSize(self: Socket.Address) u32 { return switch (self) { .ipv4 => @sizeOf(os.sockaddr_in), @@ -132,6 +132,8 @@ pub const Socket = struct { opts: fmt.FormatOptions, writer: anytype, ) !void { + _ = opts; + _ = layout; switch (self) { .ipv4 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }), .ipv6 => |address| try fmt.format(writer, "{}:{}", .{ address.host, address.port }), @@ -280,7 +282,7 @@ pub const Socket = struct { /// /// Microsoft's documentation and glibc denote the fields to be unsigned /// short's on Windows, whereas glibc and musl denote the fields to be - /// int's on every other platform. + /// int's on every other platform. pub const Linger = extern struct { pub const Field = switch (native_os.tag) { .windows => c_ushort, diff --git a/lib/std/x/os/socket_windows.zig b/lib/std/x/os/socket_windows.zig index d479d8619a..c08931fedf 100644 --- a/lib/std/x/os/socket_windows.zig +++ b/lib/std/x/os/socket_windows.zig @@ -292,6 +292,7 @@ pub fn Mixin(comptime Socket: type) type { /// with a set of flags specified. It returns the number of bytes that were /// read into the buffer provided. pub fn readMessage(self: Socket, msg: *Socket.Message, flags: u32) !usize { + _ = flags; const call = try windows.loadWinsockExtensionFunction(ws2_32.LPFN_WSARECVMSG, self.fd, ws2_32.WSAID_WSARECVMSG); var num_bytes: u32 = undefined; @@ -367,16 +368,19 @@ pub fn Mixin(comptime Socket: type) type { /// Query and return the latest cached error on the socket. pub fn getError(self: Socket) !void { + _ = self; return {}; } /// Query the read buffer size of the socket. pub fn getReadBufferSize(self: Socket) !u32 { + _ = self; return 0; } /// Query the write buffer size of the socket. pub fn getWriteBufferSize(self: Socket) !u32 { + _ = self; return 0; } @@ -406,7 +410,7 @@ pub fn Mixin(comptime Socket: type) type { /// On connection-oriented sockets, have keep-alive messages be sent periodically. The timing in which keep-alive /// messages are sent are dependant on operating system settings. It returns `error.UnsupportedSocketOption` if - /// the host does not support periodically sending keep-alive messages on connection-oriented sockets. + /// the host does not support periodically sending keep-alive messages on connection-oriented sockets. pub fn setKeepAlive(self: Socket, enabled: bool) !void { return self.setOption(ws2_32.SOL_SOCKET, ws2_32.SO_KEEPALIVE, mem.asBytes(&@as(u32, @boolToInt(enabled)))); } @@ -438,7 +442,7 @@ pub fn Mixin(comptime Socket: type) type { /// WARNING: Timeouts only affect blocking sockets. It is undefined behavior if a timeout is /// set on a non-blocking socket. - /// + /// /// Set a timeout on the socket that is to occur if no messages are successfully written /// to its bound destination after a specified number of milliseconds. A subsequent write /// to the socket will thereafter return `error.WouldBlock` should the timeout be exceeded. @@ -448,7 +452,7 @@ pub fn Mixin(comptime Socket: type) type { /// WARNING: Timeouts only affect blocking sockets. It is undefined behavior if a timeout is /// set on a non-blocking socket. - /// + /// /// Set a timeout on the socket that is to occur if no messages are successfully read /// from its bound destination after a specified number of milliseconds. A subsequent /// read from the socket will thereafter return `error.WouldBlock` should the timeout be diff --git a/lib/std/zig/ast.zig b/lib/std/zig/ast.zig index 6658092398..59fe2fdff1 100644 --- a/lib/std/zig/ast.zig +++ b/lib/std/zig/ast.zig @@ -1866,7 +1866,7 @@ pub const Tree = struct { } fn fullStructInit(tree: Tree, info: full.StructInit.Ast) full.StructInit { - const token_tags = tree.tokens.items(.tag); + _ = tree; var result: full.StructInit = .{ .ast = info, }; diff --git a/lib/std/zig/c_builtins.zig b/lib/std/zig/c_builtins.zig index d8a23ec8f1..afa3ae0a87 100644 --- a/lib/std/zig/c_builtins.zig +++ b/lib/std/zig/c_builtins.zig @@ -136,6 +136,7 @@ pub inline fn __builtin_strcmp(s1: [*c]const u8, s2: [*c]const u8) c_int { } pub inline fn __builtin_object_size(ptr: ?*const c_void, ty: c_int) usize { + _ = ptr; // clang semantics match gcc's: https://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html // If it is not possible to determine which objects ptr points to at compile time, // __builtin_object_size should return (size_t) -1 for type 0 or 1 and (size_t) 0 @@ -186,6 +187,7 @@ pub inline fn __builtin_memcpy( /// The return value of __builtin_expect is `expr`. `c` is the expected value /// of `expr` and is used as a hint to the compiler in C. Here it is unused. pub inline fn __builtin_expect(expr: c_long, c: c_long) c_long { + _ = c; return expr; } diff --git a/lib/std/zig/fmt.zig b/lib/std/zig/fmt.zig index 3a55b5df30..2afbe1d91b 100644 --- a/lib/std/zig/fmt.zig +++ b/lib/std/zig/fmt.zig @@ -8,6 +8,7 @@ pub fn formatId( options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = fmt; if (isValidId(bytes)) { return writer.writeAll(bytes); } @@ -41,6 +42,7 @@ pub fn formatEscapes( options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = options; for (bytes) |byte| switch (byte) { '\n' => try writer.writeAll("\\n"), '\r' => try writer.writeAll("\\r"), diff --git a/lib/std/zig/parse.zig b/lib/std/zig/parse.zig index 3390e29426..5bafcce5b1 100644 --- a/lib/std/zig/parse.zig +++ b/lib/std/zig/parse.zig @@ -586,7 +586,7 @@ const Parser = struct { const thread_local_token = p.eatToken(.keyword_threadlocal); const var_decl = try p.parseVarDecl(); if (var_decl != 0) { - const semicolon_token = try p.expectToken(.semicolon); + _ = try p.expectToken(.semicolon); return var_decl; } if (thread_local_token != null) { @@ -614,7 +614,7 @@ const Parser = struct { fn expectUsingNamespace(p: *Parser) !Node.Index { const usingnamespace_token = p.assertToken(.keyword_usingnamespace); const expr = try p.expectExpr(); - const semicolon_token = try p.expectToken(.semicolon); + _ = try p.expectToken(.semicolon); return p.addNode(.{ .tag = .@"usingnamespace", .main_token = usingnamespace_token, @@ -647,7 +647,7 @@ const Parser = struct { const align_expr = try p.parseByteAlign(); const section_expr = try p.parseLinkSection(); const callconv_expr = try p.parseCallconv(); - const bang_token = p.eatToken(.bang); + _ = p.eatToken(.bang); const return_type_expr = try p.parseTypeExpr(); if (return_type_expr == 0) { @@ -775,7 +775,7 @@ const Parser = struct { /// ContainerField <- KEYWORD_comptime? IDENTIFIER (COLON (KEYWORD_anytype / TypeExpr) ByteAlign?)? (EQUAL Expr)? fn expectContainerField(p: *Parser) !Node.Index { - const comptime_token = p.eatToken(.keyword_comptime); + _ = p.eatToken(.keyword_comptime); const name_token = p.assertToken(.identifier); var align_expr: Node.Index = 0; @@ -967,7 +967,7 @@ const Parser = struct { _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); - const then_payload = try p.parsePtrPayload(); + _ = try p.parsePtrPayload(); // TODO propose to change the syntax so that semicolons are always required // inside if statements, even if there is an `else`. @@ -992,7 +992,7 @@ const Parser = struct { else_required = true; break :blk assign_expr; }; - const else_token = p.eatToken(.keyword_else) orelse { + _ = p.eatToken(.keyword_else) orelse { if (else_required) { try p.warn(.expected_semi_or_else); } @@ -1005,7 +1005,7 @@ const Parser = struct { }, }); }; - const else_payload = try p.parsePayload(); + _ = try p.parsePayload(); const else_expr = try p.expectStatement(); return p.addNode(.{ .tag = .@"if", @@ -1087,7 +1087,7 @@ const Parser = struct { else_required = true; break :blk assign_expr; }; - const else_token = p.eatToken(.keyword_else) orelse { + _ = p.eatToken(.keyword_else) orelse { if (else_required) { try p.warn(.expected_semi_or_else); } @@ -1122,7 +1122,7 @@ const Parser = struct { _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); - const then_payload = try p.parsePtrPayload(); + _ = try p.parsePtrPayload(); const cont_expr = try p.parseWhileContinueExpr(); // TODO propose to change the syntax so that semicolons are always required @@ -1162,7 +1162,7 @@ const Parser = struct { else_required = true; break :blk assign_expr; }; - const else_token = p.eatToken(.keyword_else) orelse { + _ = p.eatToken(.keyword_else) orelse { if (else_required) { try p.warn(.expected_semi_or_else); } @@ -1189,7 +1189,7 @@ const Parser = struct { }); } }; - const else_payload = try p.parsePayload(); + _ = try p.parsePayload(); const else_expr = try p.expectStatement(); return p.addNode(.{ .tag = .@"while", @@ -1550,7 +1550,7 @@ const Parser = struct { }, .l_bracket => switch (p.token_tags[p.tok_i + 1]) { .asterisk => { - const lbracket = p.nextToken(); + _ = p.nextToken(); const asterisk = p.nextToken(); var sentinel: Node.Index = 0; prefix: { @@ -1907,7 +1907,7 @@ const Parser = struct { if (found_payload == 0) try p.warn(.expected_loop_payload); const then_expr = try p.expectExpr(); - const else_token = p.eatToken(.keyword_else) orelse { + _ = p.eatToken(.keyword_else) orelse { return p.addNode(.{ .tag = .for_simple, .main_token = for_token, @@ -1938,11 +1938,11 @@ const Parser = struct { _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); - const then_payload = try p.parsePtrPayload(); + _ = try p.parsePtrPayload(); const cont_expr = try p.parseWhileContinueExpr(); const then_expr = try p.expectExpr(); - const else_token = p.eatToken(.keyword_else) orelse { + _ = p.eatToken(.keyword_else) orelse { if (cont_expr == 0) { return p.addNode(.{ .tag = .while_simple, @@ -1966,7 +1966,7 @@ const Parser = struct { }); } }; - const else_payload = try p.parsePayload(); + _ = try p.parsePayload(); const else_expr = try p.expectExpr(); return p.addNode(.{ .tag = .@"while", @@ -2104,7 +2104,7 @@ const Parser = struct { /// FnCallArguments <- LPAREN ExprList RPAREN /// ExprList <- (Expr COMMA)* Expr? fn parseSuffixExpr(p: *Parser) !Node.Index { - if (p.eatToken(.keyword_async)) |async_token| { + if (p.eatToken(.keyword_async)) |_| { var res = try p.expectPrimaryTypeExpr(); while (true) { const node = try p.parseSuffixOp(res); @@ -2565,8 +2565,8 @@ const Parser = struct { p.tok_i += 2; while (true) { if (p.eatToken(.r_brace)) |_| break; - const doc_comment = try p.eatDocComments(); - const identifier = try p.expectToken(.identifier); + _ = try p.eatDocComments(); + _ = try p.expectToken(.identifier); switch (p.token_tags[p.tok_i]) { .comma => p.tok_i += 1, .r_brace => { @@ -2634,7 +2634,7 @@ const Parser = struct { if (found_payload == 0) try p.warn(.expected_loop_payload); const then_expr = try p.expectTypeExpr(); - const else_token = p.eatToken(.keyword_else) orelse { + _ = p.eatToken(.keyword_else) orelse { return p.addNode(.{ .tag = .for_simple, .main_token = for_token, @@ -2665,11 +2665,11 @@ const Parser = struct { _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); - const then_payload = try p.parsePtrPayload(); + _ = try p.parsePtrPayload(); const cont_expr = try p.parseWhileContinueExpr(); const then_expr = try p.expectTypeExpr(); - const else_token = p.eatToken(.keyword_else) orelse { + _ = p.eatToken(.keyword_else) orelse { if (cont_expr == 0) { return p.addNode(.{ .tag = .while_simple, @@ -2693,7 +2693,7 @@ const Parser = struct { }); } }; - const else_payload = try p.parsePayload(); + _ = try p.parsePayload(); const else_expr = try p.expectTypeExpr(); return p.addNode(.{ .tag = .@"while", @@ -3570,12 +3570,12 @@ const Parser = struct { _ = try p.expectToken(.l_paren); const condition = try p.expectExpr(); _ = try p.expectToken(.r_paren); - const then_payload = try p.parsePtrPayload(); + _ = try p.parsePtrPayload(); const then_expr = try bodyParseFn(p); if (then_expr == 0) return p.fail(.invalid_token); - const else_token = p.eatToken(.keyword_else) orelse return p.addNode(.{ + _ = p.eatToken(.keyword_else) orelse return p.addNode(.{ .tag = .if_simple, .main_token = if_token, .data = .{ @@ -3583,7 +3583,7 @@ const Parser = struct { .rhs = then_expr, }, }); - const else_payload = try p.parsePayload(); + _ = try p.parsePayload(); const else_expr = try bodyParseFn(p); if (else_expr == 0) return p.fail(.invalid_token); diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index e2797a33f8..907e06a1a6 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -5201,7 +5201,6 @@ fn testParse(source: []const u8, allocator: *mem.Allocator, anything_changed: *b defer tree.deinit(allocator); for (tree.errors) |parse_error| { - const token_start = tree.tokens.items(.start)[parse_error.token]; const loc = tree.tokenLocation(0, parse_error.token); try stderr.print("(memory buffer):{d}:{d}: error: ", .{ loc.line + 1, loc.column + 1 }); try tree.renderError(parse_error, stderr); diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 95b5c7a8d8..36fb7f5e14 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -1086,8 +1086,6 @@ fn renderWhile(gpa: *Allocator, ais: *Ais, tree: ast.Tree, while_node: ast.full. } if (while_node.ast.else_expr != 0) { - const first_else_expr_tok = tree.firstToken(while_node.ast.else_expr); - if (indent_then_expr) { ais.pushIndent(); try renderExpression(gpa, ais, tree, while_node.ast.then_expr, .newline); @@ -1133,7 +1131,6 @@ fn renderContainerField( field: ast.full.ContainerField, space: Space, ) Error!void { - const main_tokens = tree.nodes.items(.main_token); if (field.comptime_token) |t| { try renderToken(ais, tree, t, .space); // comptime } @@ -1519,7 +1516,6 @@ fn renderBlock( ) Error!void { const token_tags = tree.tokens.items(.tag); const node_tags = tree.nodes.items(.tag); - const nodes_data = tree.nodes.items(.data); const lbrace = tree.nodes.items(.main_token)[block_node]; if (token_tags[lbrace - 1] == .colon and @@ -1617,7 +1613,6 @@ fn renderArrayInit( space: Space, ) Error!void { const token_tags = tree.tokens.items(.tag); - const token_starts = tree.tokens.items(.start); if (array_init.ast.type_expr == 0) { try renderToken(ais, tree, array_init.ast.lbrace - 1, .none); // . @@ -2046,7 +2041,6 @@ fn renderCall( space: Space, ) Error!void { const token_tags = tree.tokens.items(.tag); - const main_tokens = tree.nodes.items(.main_token); if (call.async_token) |async_token| { try renderToken(ais, tree, async_token, .space); diff --git a/lib/std/zig/system.zig b/lib/std/zig/system.zig index bc099b8ec6..a4939b8347 100644 --- a/lib/std/zig/system.zig +++ b/lib/std/zig/system.zig @@ -200,6 +200,7 @@ pub const NativePaths = struct { } fn appendArray(self: *NativePaths, array: *ArrayList([:0]u8), s: []const u8) !void { + _ = self; const item = try array.allocator.dupeZ(u8, s); errdefer array.allocator.free(item); try array.append(item); @@ -332,7 +333,7 @@ pub const NativeTargetInfo = struct { if (std.builtin.Version.parse(buf[0 .. len - 1])) |ver| { os.version_range.semver.min = ver; os.version_range.semver.max = ver; - } else |err| { + } else |_| { return error.OSVersionDetectionFail; } }, @@ -478,13 +479,6 @@ pub const NativeTargetInfo = struct { } const ld_info_list = ld_info_list_buffer[0..ld_info_list_len]; - if (cross_target.dynamic_linker.get()) |explicit_ld| { - const explicit_ld_basename = fs.path.basename(explicit_ld); - for (ld_info_list) |ld_info| { - const standard_ld_basename = fs.path.basename(ld_info.ld.get().?); - } - } - // Best case scenario: the executable is dynamically linked, and we can iterate // over our own shared objects and find a dynamic linker. self_exe: { @@ -838,7 +832,7 @@ pub const NativeTargetInfo = struct { if (dynstr) |ds| { const strtab_len = std.math.min(ds.size, strtab_buf.len); - const strtab_read_len = try preadMin(file, &strtab_buf, ds.offset, shstrtab_len); + const strtab_read_len = try preadMin(file, &strtab_buf, ds.offset, strtab_len); const strtab = strtab_buf[0..strtab_read_len]; // TODO this pointer cast should not be necessary const rpoff_usize = std.math.cast(usize, rpoff) catch |err| switch (err) { diff --git a/lib/std/zig/system/macos.zig b/lib/std/zig/system/macos.zig index 0b3e639582..ae450ecae5 100644 --- a/lib/std/zig/system/macos.zig +++ b/lib/std/zig/system/macos.zig @@ -68,10 +68,10 @@ pub fn detect(target_os: *Target.Os) !void { return; } continue; - } else |err| { + } else |_| { return error.OSVersionDetectionFail; } - } else |err| { + } else |_| { return error.OSVersionDetectionFail; } } diff --git a/lib/std/zig/system/x86.zig b/lib/std/zig/system/x86.zig index 9a33a1daaf..1d9a22d5d2 100644 --- a/lib/std/zig/system/x86.zig +++ b/lib/std/zig/system/x86.zig @@ -28,6 +28,7 @@ inline fn hasMask(input: u32, mask: u32) bool { } pub fn detectNativeCpuAndFeatures(arch: Target.Cpu.Arch, os: Target.Os, cross_target: CrossTarget) Target.Cpu { + _ = cross_target; var cpu = Target.Cpu{ .arch = arch, .model = Target.Cpu.Model.generic(arch), diff --git a/lib/std/zig/tokenizer.zig b/lib/std/zig/tokenizer.zig index f44b140c63..94a20d958b 100644 --- a/lib/std/zig/tokenizer.zig +++ b/lib/std/zig/tokenizer.zig @@ -416,7 +416,6 @@ pub const Tokenizer = struct { self.pending_invalid_token = null; return token; } - const start_index = self.index; var state: State = .start; var result = Token{ .tag = .eof, diff --git a/src/AstGen.zig b/src/AstGen.zig index 1eb12af99d..c79d74fdd9 100644 --- a/src/AstGen.zig +++ b/src/AstGen.zig @@ -206,7 +206,6 @@ pub const ResultLoc = union(enum) { }; fn strategy(rl: ResultLoc, block_scope: *GenZir) Strategy { - var elide_store_to_block_ptr_instructions = false; switch (rl) { // In this branch there will not be any store_to_block_ptr instructions. .discard, .none, .none_or_ref, .ty, .ref => return .{ @@ -482,61 +481,61 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr .assign => { try assign(gz, scope, node); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_bit_shift_left => { try assignShift(gz, scope, node, .shl); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_bit_shift_right => { try assignShift(gz, scope, node, .shr); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_bit_and => { try assignOp(gz, scope, node, .bit_and); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_bit_or => { try assignOp(gz, scope, node, .bit_or); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_bit_xor => { try assignOp(gz, scope, node, .xor); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_div => { try assignOp(gz, scope, node, .div); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_sub => { try assignOp(gz, scope, node, .sub); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_sub_wrap => { try assignOp(gz, scope, node, .subwrap); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_mod => { try assignOp(gz, scope, node, .mod_rem); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_add => { try assignOp(gz, scope, node, .add); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_add_wrap => { try assignOp(gz, scope, node, .addwrap); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_mul => { try assignOp(gz, scope, node, .mul); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .assign_mul_wrap => { try assignOp(gz, scope, node, .mulwrap); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, // zig fmt: off @@ -598,10 +597,10 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr .asm_simple => return asmExpr(gz, scope, rl, node, tree.asmSimple(node)), .@"asm" => return asmExpr(gz, scope, rl, node, tree.asmFull(node)), - .string_literal => return stringLiteral(gz, scope, rl, node), - .multiline_string_literal => return multilineStringLiteral(gz, scope, rl, node), + .string_literal => return stringLiteral(gz, rl, node), + .multiline_string_literal => return multilineStringLiteral(gz, rl, node), - .integer_literal => return integerLiteral(gz, scope, rl, node), + .integer_literal => return integerLiteral(gz, rl, node), // zig fmt: on .builtin_call_two, .builtin_call_two_comma => { @@ -641,7 +640,7 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr }, .@"return" => return ret(gz, scope, node), .field_access => return fieldAccess(gz, scope, rl, node), - .float_literal => return floatLiteral(gz, scope, rl, node), + .float_literal => return floatLiteral(gz, rl, node), .if_simple => return ifExpr(gz, scope, rl, node, tree.ifSimple(node)), .@"if" => return ifExpr(gz, scope, rl, node, tree.ifFull(node)), @@ -660,7 +659,7 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr .lhs = lhs, .start = start, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .slice => { const lhs = try expr(gz, scope, .ref, node_datas[node].lhs); @@ -672,7 +671,7 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr .start = start, .end = end, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .slice_sentinel => { const lhs = try expr(gz, scope, .ref, node_datas[node].lhs); @@ -686,7 +685,7 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr .end = end, .sentinel = sentinel, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .deref => { @@ -695,22 +694,22 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr .ref, .none_or_ref => return lhs, else => { const result = try gz.addUnNode(.load, lhs, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, } }, .address_of => { const result = try expr(gz, scope, .ref, node_datas[node].lhs); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, - .undefined_literal => return rvalue(gz, scope, rl, .undef, node), - .true_literal => return rvalue(gz, scope, rl, .bool_true, node), - .false_literal => return rvalue(gz, scope, rl, .bool_false, node), - .null_literal => return rvalue(gz, scope, rl, .null_value, node), + .undefined_literal => return rvalue(gz, rl, .undef, node), + .true_literal => return rvalue(gz, rl, .bool_true, node), + .false_literal => return rvalue(gz, rl, .bool_false, node), + .null_literal => return rvalue(gz, rl, .null_value, node), .optional_type => { const operand = try typeExpr(gz, scope, node_datas[node].lhs); const result = try gz.addUnNode(.optional_type, operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .unwrap_optional => switch (rl) { .ref => return gz.addUnNode( @@ -718,7 +717,7 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr try expr(gz, scope, .ref, node_datas[node].lhs), node, ), - else => return rvalue(gz, scope, rl, try gz.addUnNode( + else => return rvalue(gz, rl, try gz.addUnNode( .optional_payload_safe, try expr(gz, scope, .none, node_datas[node].lhs), node, @@ -738,13 +737,13 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr const statements = tree.extra_data[node_datas[node].lhs..node_datas[node].rhs]; return blockExpr(gz, scope, rl, node, statements); }, - .enum_literal => return simpleStrTok(gz, scope, rl, main_tokens[node], node, .enum_literal), - .error_value => return simpleStrTok(gz, scope, rl, node_datas[node].rhs, node, .error_value), - .anyframe_literal => return rvalue(gz, scope, rl, .anyframe_type, node), + .enum_literal => return simpleStrTok(gz, rl, main_tokens[node], node, .enum_literal), + .error_value => return simpleStrTok(gz, rl, node_datas[node].rhs, node, .error_value), + .anyframe_literal => return rvalue(gz, rl, .anyframe_type, node), .anyframe_type => { const return_type = try typeExpr(gz, scope, node_datas[node].rhs); const result = try gz.addUnNode(.anyframe_type, return_type, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .@"catch" => { const catch_token = main_tokens[node]; @@ -838,14 +837,14 @@ fn expr(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerEr .grouped_expression => return expr(gz, scope, rl, node_datas[node].lhs), .array_type => return arrayType(gz, scope, rl, node), .array_type_sentinel => return arrayTypeSentinel(gz, scope, rl, node), - .char_literal => return charLiteral(gz, scope, rl, node), - .error_set_decl => return errorSetDecl(gz, scope, rl, node), + .char_literal => return charLiteral(gz, rl, node), + .error_set_decl => return errorSetDecl(gz, rl, node), .array_access => return arrayAccess(gz, scope, rl, node), .@"comptime" => return comptimeExprAst(gz, scope, rl, node), .@"switch", .switch_comma => return switchExpr(gz, scope, rl, node), .@"nosuspend" => return nosuspendExpr(gz, scope, rl, node), - .@"suspend" => return suspendExpr(gz, scope, rl, node), + .@"suspend" => return suspendExpr(gz, scope, node), .@"await" => return awaitExpr(gz, scope, rl, node), .@"resume" => return resumeExpr(gz, scope, rl, node), @@ -905,7 +904,6 @@ fn nosuspendExpr( node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; - const gpa = astgen.gpa; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const body_node = node_datas[node].lhs; @@ -918,13 +916,12 @@ fn nosuspendExpr( gz.nosuspend_node = node; const result = try expr(gz, scope, rl, body_node); gz.nosuspend_node = 0; - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn suspendExpr( gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; @@ -980,7 +977,7 @@ fn awaitExpr( const operand = try expr(gz, scope, .none, rhs_node); const tag: Zir.Inst.Tag = if (gz.nosuspend_node != 0) .await_nosuspend else .@"await"; const result = try gz.addUnNode(tag, operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn resumeExpr( @@ -995,7 +992,7 @@ fn resumeExpr( const rhs_node = node_datas[node].lhs; const operand = try expr(gz, scope, .none, rhs_node); const result = try gz.addUnNode(.@"resume", operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn fnProtoExpr( @@ -1101,7 +1098,7 @@ fn fnProtoExpr( .is_test = false, .is_extern = false, }); - return rvalue(gz, scope, rl, result, fn_proto.ast.proto_node); + return rvalue(gz, rl, result, fn_proto.ast.proto_node); } fn arrayInitExpr( @@ -1113,7 +1110,6 @@ fn arrayInitExpr( ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; - const gpa = astgen.gpa; const node_tags = tree.nodes.items(.tag); const main_tokens = tree.nodes.items(.main_token); @@ -1173,32 +1169,32 @@ fn arrayInitExpr( }, .ref => { if (types.array != .none) { - return arrayInitExprRlTy(gz, scope, rl, node, array_init.ast.elements, types.array, types.elem, .array_init_ref); + return arrayInitExprRlTy(gz, scope, node, array_init.ast.elements, types.elem, .array_init_ref); } else { - return arrayInitExprRlNone(gz, scope, rl, node, array_init.ast.elements, .array_init_anon_ref); + return arrayInitExprRlNone(gz, scope, node, array_init.ast.elements, .array_init_anon_ref); } }, .none, .none_or_ref => { if (types.array != .none) { - return arrayInitExprRlTy(gz, scope, rl, node, array_init.ast.elements, types.array, types.elem, .array_init); + return arrayInitExprRlTy(gz, scope, node, array_init.ast.elements, types.elem, .array_init); } else { - return arrayInitExprRlNone(gz, scope, rl, node, array_init.ast.elements, .array_init_anon); + return arrayInitExprRlNone(gz, scope, node, array_init.ast.elements, .array_init_anon); } }, .ty => |ty_inst| { if (types.array != .none) { - const result = try arrayInitExprRlTy(gz, scope, rl, node, array_init.ast.elements, types.array, types.elem, .array_init); - return rvalue(gz, scope, rl, result, node); + const result = try arrayInitExprRlTy(gz, scope, node, array_init.ast.elements, types.elem, .array_init); + return rvalue(gz, rl, result, node); } else { const elem_type = try gz.addUnNode(.elem_type, ty_inst, node); - return arrayInitExprRlTy(gz, scope, rl, node, array_init.ast.elements, ty_inst, elem_type, .array_init); + return arrayInitExprRlTy(gz, scope, node, array_init.ast.elements, elem_type, .array_init); } }, .ptr, .inferred_ptr => |ptr_inst| { - return arrayInitExprRlPtr(gz, scope, rl, node, array_init.ast.elements, ptr_inst); + return arrayInitExprRlPtr(gz, scope, node, array_init.ast.elements, ptr_inst); }, .block_ptr => |block_gz| { - return arrayInitExprRlPtr(gz, scope, rl, node, array_init.ast.elements, block_gz.rl_ptr); + return arrayInitExprRlPtr(gz, scope, node, array_init.ast.elements, block_gz.rl_ptr); }, } } @@ -1206,7 +1202,6 @@ fn arrayInitExpr( fn arrayInitExprRlNone( gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, elements: []const ast.Node.Index, tag: Zir.Inst.Tag, @@ -1229,10 +1224,8 @@ fn arrayInitExprRlNone( fn arrayInitExprRlTy( gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, elements: []const ast.Node.Index, - array_ty_inst: Zir.Inst.Ref, elem_ty_inst: Zir.Inst.Ref, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { @@ -1257,7 +1250,6 @@ fn arrayInitExprRlTy( fn arrayInitExprRlPtr( gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, elements: []const ast.Node.Index, result_ptr: Zir.Inst.Ref, @@ -1293,11 +1285,10 @@ fn structInitExpr( ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; - const gpa = astgen.gpa; if (struct_init.ast.fields.len == 0) { if (struct_init.ast.type_expr == 0) { - return rvalue(gz, scope, rl, .empty_struct, node); + return rvalue(gz, rl, .empty_struct, node); } array: { const node_tags = tree.nodes.items(.tag); @@ -1319,15 +1310,17 @@ fn structInitExpr( break :blk try gz.addArrayTypeSentinel(.zero_usize, elem_type, sentinel); }; const result = try gz.addUnNode(.struct_init_empty, array_type_inst, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } } const ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr); const result = try gz.addUnNode(.struct_init_empty, ty_inst, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } switch (rl) { .discard => { + if (struct_init.ast.type_expr != 0) + _ = try typeExpr(gz, scope, struct_init.ast.type_expr); for (struct_init.ast.fields) |field_init| { _ = try expr(gz, scope, .discard, field_init); } @@ -1336,36 +1329,35 @@ fn structInitExpr( .ref => { if (struct_init.ast.type_expr != 0) { const ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr); - return structInitExprRlTy(gz, scope, rl, node, struct_init, ty_inst, .struct_init_ref); + return structInitExprRlTy(gz, scope, node, struct_init, ty_inst, .struct_init_ref); } else { - return structInitExprRlNone(gz, scope, rl, node, struct_init, .struct_init_anon_ref); + return structInitExprRlNone(gz, scope, node, struct_init, .struct_init_anon_ref); } }, .none, .none_or_ref => { if (struct_init.ast.type_expr != 0) { const ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr); - return structInitExprRlTy(gz, scope, rl, node, struct_init, ty_inst, .struct_init); + return structInitExprRlTy(gz, scope, node, struct_init, ty_inst, .struct_init); } else { - return structInitExprRlNone(gz, scope, rl, node, struct_init, .struct_init_anon); + return structInitExprRlNone(gz, scope, node, struct_init, .struct_init_anon); } }, .ty => |ty_inst| { if (struct_init.ast.type_expr == 0) { - return structInitExprRlTy(gz, scope, rl, node, struct_init, ty_inst, .struct_init); + return structInitExprRlTy(gz, scope, node, struct_init, ty_inst, .struct_init); } const inner_ty_inst = try typeExpr(gz, scope, struct_init.ast.type_expr); - const result = try structInitExprRlTy(gz, scope, rl, node, struct_init, inner_ty_inst, .struct_init); - return rvalue(gz, scope, rl, result, node); + const result = try structInitExprRlTy(gz, scope, node, struct_init, inner_ty_inst, .struct_init); + return rvalue(gz, rl, result, node); }, - .ptr, .inferred_ptr => |ptr_inst| return structInitExprRlPtr(gz, scope, rl, node, struct_init, ptr_inst), - .block_ptr => |block_gz| return structInitExprRlPtr(gz, scope, rl, node, struct_init, block_gz.rl_ptr), + .ptr, .inferred_ptr => |ptr_inst| return structInitExprRlPtr(gz, scope, node, struct_init, ptr_inst), + .block_ptr => |block_gz| return structInitExprRlPtr(gz, scope, node, struct_init, block_gz.rl_ptr), } } fn structInitExprRlNone( gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, struct_init: ast.full.StructInit, tag: Zir.Inst.Tag, @@ -1400,7 +1392,6 @@ fn structInitExprRlNone( fn structInitExprRlPtr( gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, struct_init: ast.full.StructInit, result_ptr: Zir.Inst.Ref, @@ -1412,6 +1403,9 @@ fn structInitExprRlPtr( const field_ptr_list = try gpa.alloc(Zir.Inst.Index, struct_init.ast.fields.len); defer gpa.free(field_ptr_list); + if (struct_init.ast.type_expr != 0) + _ = try typeExpr(gz, scope, struct_init.ast.type_expr); + for (struct_init.ast.fields) |field_init, i| { const name_token = tree.firstToken(field_init) - 2; const str_index = try astgen.identAsString(name_token); @@ -1432,7 +1426,6 @@ fn structInitExprRlPtr( fn structInitExprRlTy( gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, struct_init: ast.full.StructInit, ty_inst: Zir.Inst.Ref, @@ -1657,8 +1650,8 @@ fn blockExpr( return labeledBlockExpr(gz, scope, rl, block_node, statements, .block); } - try blockExprStmts(gz, scope, block_node, statements); - return rvalue(gz, scope, rl, .void_value, block_node); + try blockExprStmts(gz, scope, statements); + return rvalue(gz, rl, .void_value, block_node); } fn checkLabelRedefinition(astgen: *AstGen, parent_scope: *Scope, label: ast.TokenIndex) !void { @@ -1670,9 +1663,6 @@ fn checkLabelRedefinition(astgen: *AstGen, parent_scope: *Scope, label: ast.Toke const gen_zir = scope.cast(GenZir).?; if (gen_zir.label) |prev_label| { if (try astgen.tokenIdentEql(label, prev_label.token)) { - const tree = astgen.tree; - const main_tokens = tree.nodes.items(.main_token); - const label_name = try astgen.identifierTokenString(label); return astgen.failTokNotes(label, "redefinition of label '{s}'", .{ label_name, @@ -1735,7 +1725,7 @@ fn labeledBlockExpr( defer block_scope.labeled_breaks.deinit(astgen.gpa); defer block_scope.labeled_store_to_block_ptr_list.deinit(astgen.gpa); - try blockExprStmts(&block_scope, &block_scope.base, block_node, statements); + try blockExprStmts(&block_scope, &block_scope.base, statements); if (!block_scope.label.?.used) { return astgen.failTok(label_token, "unused block label", .{}); @@ -1771,21 +1761,15 @@ fn labeledBlockExpr( const block_ref = gz.indexToRef(block_inst); switch (rl) { .ref => return block_ref, - else => return rvalue(gz, parent_scope, rl, block_ref, block_node), + else => return rvalue(gz, rl, block_ref, block_node), } }, } } -fn blockExprStmts( - gz: *GenZir, - parent_scope: *Scope, - node: ast.Node.Index, - statements: []const ast.Node.Index, -) !void { +fn blockExprStmts(gz: *GenZir, parent_scope: *Scope, statements: []const ast.Node.Index) !void { const astgen = gz.astgen; const tree = astgen.tree; - const main_tokens = tree.nodes.items(.main_token); const node_tags = tree.nodes.items(.tag); var block_arena = std.heap.ArenaAllocator.init(gz.astgen.gpa); @@ -1800,8 +1784,8 @@ fn blockExprStmts( .simple_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.simpleVarDecl(statement)), .aligned_var_decl => scope = try varDecl(gz, scope, statement, &block_arena.allocator, tree.alignedVarDecl(statement)), - .@"defer" => scope = try deferStmt(gz, scope, statement, &block_arena.allocator, .defer_normal), - .@"errdefer" => scope = try deferStmt(gz, scope, statement, &block_arena.allocator, .defer_error), + .@"defer" => scope = try makeDeferScope(scope, statement, &block_arena.allocator, .defer_normal), + .@"errdefer" => scope = try makeDeferScope(scope, statement, &block_arena.allocator, .defer_error), .assign => try assign(gz, scope, statement), @@ -1826,6 +1810,7 @@ fn blockExprStmts( } try genDefers(gz, parent_scope, scope, .none); + try checkUsed(gz, parent_scope, scope); } fn unusedResultExpr(gz: *GenZir, scope: *Scope, statement: ast.Node.Index) InnerError!void { @@ -2119,6 +2104,7 @@ fn genDefers( inner_scope: *Scope, err_code: Zir.Inst.Ref, ) InnerError!void { + _ = err_code; const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); @@ -2154,8 +2140,49 @@ fn genDefers( } } -fn deferStmt( +fn checkUsed( gz: *GenZir, + outer_scope: *Scope, + inner_scope: *Scope, +) InnerError!void { + const astgen = gz.astgen; + + var scope = inner_scope; + while (scope != outer_scope) { + switch (scope.tag) { + .gen_zir => scope = scope.cast(GenZir).?.parent, + .local_val => { + const s = scope.cast(Scope.LocalVal).?; + switch (s.used) { + .used => {}, + .fn_param => return astgen.failTok(s.token_src, "unused function parameter", .{}), + .constant => return astgen.failTok(s.token_src, "unused local constant", .{}), + .variable => unreachable, + .loop_index => unreachable, + .capture => return astgen.failTok(s.token_src, "unused capture", .{}), + } + scope = s.parent; + }, + .local_ptr => { + const s = scope.cast(Scope.LocalPtr).?; + switch (s.used) { + .used => {}, + .fn_param => unreachable, + .constant => return astgen.failTok(s.token_src, "unused local constant", .{}), + .variable => return astgen.failTok(s.token_src, "unused local variable", .{}), + .loop_index => return astgen.failTok(s.token_src, "unused loop index capture", .{}), + .capture => unreachable, + } + scope = s.parent; + }, + .defer_normal, .defer_error => scope = scope.cast(Scope.Defer).?.parent, + .namespace => unreachable, + .top => unreachable, + } + } +} + +fn makeDeferScope( scope: *Scope, node: ast.Node.Index, block_arena: *Allocator, @@ -2274,6 +2301,7 @@ fn varDecl( .name = ident_name, .inst = init_inst, .token_src = name_token, + .used = .constant, }; return &sub_scope.base; } @@ -2341,6 +2369,7 @@ fn varDecl( .name = ident_name, .inst = init_inst, .token_src = name_token, + .used = .constant, }; return &sub_scope.base; } @@ -2369,7 +2398,8 @@ fn varDecl( .name = ident_name, .ptr = init_scope.rl_ptr, .token_src = name_token, - .is_comptime = true, + .maybe_comptime = true, + .used = .constant, }; return &sub_scope.base; }, @@ -2414,7 +2444,7 @@ fn varDecl( resolve_inferred_alloc = alloc; break :a .{ .alloc = alloc, .result_loc = .{ .inferred_ptr = alloc } }; }; - const init_inst = try expr(gz, scope, var_data.result_loc, var_decl.ast.init_node); + _ = try expr(gz, scope, var_data.result_loc, var_decl.ast.init_node); if (resolve_inferred_alloc != .none) { _ = try gz.addUnNode(.resolve_inferred_alloc, resolve_inferred_alloc, node); } @@ -2425,7 +2455,8 @@ fn varDecl( .name = ident_name, .ptr = var_data.alloc, .token_src = name_token, - .is_comptime = is_comptime, + .maybe_comptime = is_comptime, + .used = .variable, }; return &sub_scope.base; }, @@ -2441,7 +2472,6 @@ fn emitDbgNode(gz: *GenZir, node: ast.Node.Index) !void { const astgen = gz.astgen; const tree = astgen.tree; - const node_tags = tree.nodes.items(.tag); const token_starts = tree.tokens.items(.start); const decl_start = token_starts[tree.firstToken(gz.decl_node_index)]; const node_start = token_starts[tree.firstToken(node)]; @@ -2530,7 +2560,7 @@ fn boolNot(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) Inne const operand = try expr(gz, scope, bool_rl, node_datas[node].lhs); const result = try gz.addUnNode(.bool_not, operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn bitNot(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { @@ -2540,7 +2570,7 @@ fn bitNot(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) Inner const operand = try expr(gz, scope, .none, node_datas[node].lhs); const result = try gz.addUnNode(.bit_not, operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn negation( @@ -2556,7 +2586,7 @@ fn negation( const operand = try expr(gz, scope, .none, node_datas[node].lhs); const result = try gz.addUnNode(tag, operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn ptrType( @@ -2566,9 +2596,6 @@ fn ptrType( node: ast.Node.Index, ptr_info: ast.full.PtrType, ) InnerError!Zir.Inst.Ref { - const astgen = gz.astgen; - const tree = astgen.tree; - const elem_type = try typeExpr(gz, scope, ptr_info.ast.child_type); const simple = ptr_info.ast.align_node == 0 and @@ -2585,7 +2612,7 @@ fn ptrType( .elem_type = elem_type, }, } }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } var sentinel_ref: Zir.Inst.Ref = .none; @@ -2645,7 +2672,7 @@ fn ptrType( } }); gz.instructions.appendAssumeCapacity(new_index); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn arrayType(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !Zir.Inst.Ref { @@ -2665,7 +2692,7 @@ fn arrayType(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !Z const elem_type = try typeExpr(gz, scope, node_datas[node].rhs); const result = try gz.addBin(.array_type, len, elem_type); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn arrayTypeSentinel(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !Zir.Inst.Ref { @@ -2687,7 +2714,7 @@ fn arrayTypeSentinel(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.I const sentinel = try expr(gz, scope, .{ .ty = elem_type }, extra.sentinel); const result = try gz.addArrayTypeSentinel(len, elem_type, sentinel); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } const WipDecls = struct { @@ -2918,6 +2945,10 @@ fn fnDecl( const name_token = param.name_token orelse { return astgen.failNode(param.type_expr, "missing parameter name", .{}); }; + if (param.type_expr != 0) + _ = try typeExpr(&fn_gz, params_scope, param.type_expr); + if (mem.eql(u8, "_", tree.tokenSlice(name_token))) + continue; const param_name = try astgen.identAsString(name_token); // Create an arg instruction. This is needed to emit a semantic analysis // error for shadowing decls. @@ -2930,16 +2961,19 @@ fn fnDecl( .name = param_name, .inst = arg_inst, .token_src = name_token, + .used = .fn_param, }; params_scope = &sub_scope.base; // Additionally put the param name into `string_bytes` and reference it with // `extra` so that we have access to the data in codegen, for debug info. const str_index = try astgen.identAsString(name_token); - astgen.extra.appendAssumeCapacity(str_index); + try astgen.extra.append(astgen.gpa, str_index); } + _ = try typeExpr(&fn_gz, params_scope, fn_proto.ast.return_type); _ = try expr(&fn_gz, params_scope, .none, body_node); + try checkUsed(gz, &fn_gz.base, params_scope); } const need_implicit_ret = blk: { @@ -3632,7 +3666,7 @@ fn unionDeclInner( }; defer block_scope.instructions.deinit(gpa); - var namespace: Scope.Namespace = .{ .parent = &gz.base }; + var namespace: Scope.Namespace = .{ .parent = scope }; defer namespace.decls.deinit(gpa); var wip_decls: WipDecls = .{}; @@ -3916,7 +3950,7 @@ fn containerDecl( assert(arg_inst == .none); const result = try structDeclInner(gz, scope, node, container_decl, layout); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .keyword_union => { const layout = if (container_decl.layout_token) |t| switch (token_tags[t]) { @@ -3928,7 +3962,7 @@ fn containerDecl( const have_auto_enum = container_decl.ast.enum_token != null; const result = try unionDeclInner(gz, scope, node, container_decl.ast.members, layout, arg_inst, have_auto_enum); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .keyword_enum => { if (container_decl.layout_token) |t| { @@ -4033,7 +4067,7 @@ fn containerDecl( }; defer block_scope.instructions.deinit(gpa); - var namespace: Scope.Namespace = .{ .parent = &gz.base }; + var namespace: Scope.Namespace = .{ .parent = scope }; defer namespace.decls.deinit(gpa); var wip_decls: WipDecls = .{}; @@ -4257,20 +4291,18 @@ fn containerDecl( astgen.extra.appendAssumeCapacity(cur_bit_bag); astgen.extra.appendSliceAssumeCapacity(fields_data.items); - return rvalue(gz, scope, rl, gz.indexToRef(decl_inst), node); + return rvalue(gz, rl, gz.indexToRef(decl_inst), node); }, .keyword_opaque => { - var namespace: Scope.Namespace = .{ .parent = &gz.base }; + var namespace: Scope.Namespace = .{ .parent = scope }; defer namespace.decls.deinit(gpa); var wip_decls: WipDecls = .{}; defer wip_decls.deinit(gpa); for (container_decl.ast.members) |member_node| { - const member = switch (node_tags[member_node]) { - .container_field_init => tree.containerFieldInit(member_node), - .container_field_align => tree.containerFieldAlign(member_node), - .container_field => tree.containerField(member_node), + switch (node_tags[member_node]) { + .container_field_init, .container_field_align, .container_field => {}, .fn_decl => { const fn_proto = node_datas[member_node].lhs; @@ -4391,7 +4423,7 @@ fn containerDecl( continue; }, else => unreachable, - }; + } } { const empty_slot_count = WipDecls.fields_per_u32 - (wip_decls.decl_index % WipDecls.fields_per_u32); @@ -4420,18 +4452,13 @@ fn containerDecl( } astgen.extra.appendSliceAssumeCapacity(wip_decls.payload.items); - return rvalue(gz, scope, rl, gz.indexToRef(decl_inst), node); + return rvalue(gz, rl, gz.indexToRef(decl_inst), node); }, else => unreachable, } } -fn errorSetDecl( - gz: *GenZir, - scope: *Scope, - rl: ResultLoc, - node: ast.Node.Index, -) InnerError!Zir.Inst.Ref { +fn errorSetDecl(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const gpa = astgen.gpa; const tree = astgen.tree; @@ -4459,16 +4486,11 @@ fn errorSetDecl( } } - const tag: Zir.Inst.Tag = switch (gz.anon_name_strategy) { - .parent => .error_set_decl, - .anon => .error_set_decl_anon, - .func => .error_set_decl_func, - }; const result = try gz.addPlNode(.error_set_decl, node, Zir.Inst.ErrorSetDecl{ .fields_len = @intCast(u32, field_names.items.len), }); try astgen.extra.appendSlice(gpa, field_names.items); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn tryExpr( @@ -4479,7 +4501,6 @@ fn tryExpr( operand_node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = parent_gz.astgen; - const tree = astgen.tree; const fn_block = astgen.fn_block orelse { return astgen.failNode(node, "invalid 'try' outside function scope", .{}); @@ -4528,12 +4549,11 @@ fn tryExpr( const unwrapped_payload = try else_scope.addUnNode(err_ops[2], operand, node); const else_result = switch (rl) { .ref => unwrapped_payload, - else => try rvalue(&else_scope, &else_scope.base, block_scope.break_result_loc, unwrapped_payload, node), + else => try rvalue(&else_scope, block_scope.break_result_loc, unwrapped_payload, node), }; return finishThenElseBlock( parent_gz, - scope, rl, node, &block_scope, @@ -4541,8 +4561,6 @@ fn tryExpr( &else_scope, condbr, cond, - node, - node, then_result, else_result, block, @@ -4603,12 +4621,15 @@ fn orelseCatchExpr( .name = err_name, .inst = try then_scope.addUnNode(unwrap_code_op, operand, node), .token_src = payload, + .used = .capture, }; break :blk &err_val_scope.base; }; block_scope.break_count += 1; const then_result = try expr(&then_scope, then_sub_scope, block_scope.break_result_loc, rhs); + try checkUsed(parent_gz, &then_scope.base, then_sub_scope); + // We hold off on the break instructions as well as copying the then/else // instructions into place until we know whether to keep store_to_block_ptr // instructions or not. @@ -4620,12 +4641,11 @@ fn orelseCatchExpr( const unwrapped_payload = try else_scope.addUnNode(unwrap_op, operand, node); const else_result = switch (rl) { .ref => unwrapped_payload, - else => try rvalue(&else_scope, &else_scope.base, block_scope.break_result_loc, unwrapped_payload, node), + else => try rvalue(&else_scope, block_scope.break_result_loc, unwrapped_payload, node), }; return finishThenElseBlock( parent_gz, - scope, rl, node, &block_scope, @@ -4633,8 +4653,6 @@ fn orelseCatchExpr( &else_scope, condbr, cond, - node, - node, then_result, else_result, block, @@ -4645,7 +4663,6 @@ fn orelseCatchExpr( fn finishThenElseBlock( parent_gz: *GenZir, - parent_scope: *Scope, rl: ResultLoc, node: ast.Node.Index, block_scope: *GenZir, @@ -4653,8 +4670,6 @@ fn finishThenElseBlock( else_scope: *GenZir, condbr: Zir.Inst.Index, cond: Zir.Inst.Ref, - then_src: ast.Node.Index, - else_src: ast.Node.Index, then_result: Zir.Inst.Ref, else_result: Zir.Inst.Ref, main_block: Zir.Inst.Index, @@ -4664,7 +4679,6 @@ fn finishThenElseBlock( // We now have enough information to decide whether the result instruction should // be communicated via result location pointer or break instructions. const strat = rl.strategy(block_scope); - const astgen = block_scope.astgen; switch (strat.tag) { .break_void => { if (!parent_gz.refIsNoReturn(then_result)) { @@ -4697,7 +4711,7 @@ fn finishThenElseBlock( const block_ref = parent_gz.indexToRef(main_block); switch (rl) { .ref => return block_ref, - else => return rvalue(parent_gz, parent_scope, rl, block_ref, node), + else => return rvalue(parent_gz, rl, block_ref, node), } }, } @@ -4733,7 +4747,7 @@ fn fieldAccess( .lhs = try expr(gz, scope, .ref, object_node), .field_name_start = str_index, }), - else => return rvalue(gz, scope, rl, try gz.addPlNode(.field_val, node, Zir.Inst.Field{ + else => return rvalue(gz, rl, try gz.addPlNode(.field_val, node, Zir.Inst.Field{ .lhs = try expr(gz, scope, .none_or_ref, object_node), .field_name_start = str_index, }), node), @@ -4748,7 +4762,6 @@ fn arrayAccess( ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; - const main_tokens = tree.nodes.items(.main_token); const node_datas = tree.nodes.items(.data); switch (rl) { .ref => return gz.addBin( @@ -4756,7 +4769,7 @@ fn arrayAccess( try expr(gz, scope, .ref, node_datas[node].lhs), try expr(gz, scope, .{ .ty = .usize_type }, node_datas[node].rhs), ), - else => return rvalue(gz, scope, rl, try gz.addBin( + else => return rvalue(gz, rl, try gz.addBin( .elem_val, try expr(gz, scope, .none_or_ref, node_datas[node].lhs), try expr(gz, scope, .{ .ty = .usize_type }, node_datas[node].rhs), @@ -4779,12 +4792,11 @@ fn simpleBinOp( .lhs = try expr(gz, scope, .none, node_datas[node].lhs), .rhs = try expr(gz, scope, .none, node_datas[node].rhs), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn simpleStrTok( gz: *GenZir, - scope: *Scope, rl: ResultLoc, ident_token: ast.TokenIndex, node: ast.Node.Index, @@ -4793,7 +4805,7 @@ fn simpleStrTok( const astgen = gz.astgen; const str_index = try astgen.identAsString(ident_token); const result = try gz.addStrTok(op_inst_tag, str_index, ident_token); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn boolBinOp( @@ -4819,7 +4831,7 @@ fn boolBinOp( try rhs_scope.setBoolBrBody(bool_br); const block_ref = gz.indexToRef(bool_br); - return rvalue(gz, scope, rl, block_ref, node); + return rvalue(gz, rl, block_ref, node); } fn ifExpr( @@ -4846,7 +4858,7 @@ fn ifExpr( inst: Zir.Inst.Ref, bool_bit: Zir.Inst.Ref, } = c: { - if (if_full.error_token) |error_token| { + if (if_full.error_token) |_| { const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const err_union = try expr(&block_scope, &block_scope.base, cond_rl, if_full.ast.cond_expr); const tag: Zir.Inst.Tag = if (payload_is_ref) .is_err_ptr else .is_err; @@ -4854,7 +4866,7 @@ fn ifExpr( .inst = err_union, .bool_bit = try block_scope.addUnNode(tag, err_union, node), }; - } else if (if_full.payload_token) |payload_token| { + } else if (if_full.payload_token) |_| { const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const optional = try expr(&block_scope, &block_scope.base, cond_rl, if_full.ast.cond_expr); const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_null_ptr else .is_non_null; @@ -4883,27 +4895,38 @@ fn ifExpr( var payload_val_scope: Scope.LocalVal = undefined; const then_sub_scope = s: { - if (if_full.error_token) |error_token| { - const tag: Zir.Inst.Tag = if (payload_is_ref) - .err_union_payload_unsafe_ptr - else - .err_union_payload_unsafe; - const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); - const ident_name = try astgen.identAsString(error_token); - payload_val_scope = .{ - .parent = &then_scope.base, - .gen_zir = &then_scope, - .name = ident_name, - .inst = payload_inst, - .token_src = error_token, - }; - break :s &payload_val_scope.base; + if (if_full.error_token != null) { + if (if_full.payload_token) |payload_token| { + const tag: Zir.Inst.Tag = if (payload_is_ref) + .err_union_payload_unsafe_ptr + else + .err_union_payload_unsafe; + const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); + const token_name_index = payload_token + @boolToInt(payload_is_ref); + const ident_name = try astgen.identAsString(token_name_index); + const token_name_str = tree.tokenSlice(token_name_index); + if (mem.eql(u8, "_", token_name_str)) + break :s &then_scope.base; + payload_val_scope = .{ + .parent = &then_scope.base, + .gen_zir = &then_scope, + .name = ident_name, + .inst = payload_inst, + .token_src = payload_token, + .used = .capture, + }; + break :s &payload_val_scope.base; + } else { + break :s &then_scope.base; + } } else if (if_full.payload_token) |payload_token| { const ident_token = if (payload_is_ref) payload_token + 1 else payload_token; const tag: Zir.Inst.Tag = if (payload_is_ref) .optional_payload_unsafe_ptr else .optional_payload_unsafe; + if (mem.eql(u8, "_", tree.tokenSlice(ident_token))) + break :s &then_scope.base; const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); const ident_name = try astgen.identAsString(ident_token); payload_val_scope = .{ @@ -4912,6 +4935,7 @@ fn ifExpr( .name = ident_name, .inst = payload_inst, .token_src = ident_token, + .used = .capture, }; break :s &payload_val_scope.base; } else { @@ -4921,6 +4945,7 @@ fn ifExpr( block_scope.break_count += 1; const then_result = try expr(&then_scope, then_sub_scope, block_scope.break_result_loc, if_full.ast.then_expr); + try checkUsed(parent_gz, &then_scope.base, then_sub_scope); // We hold off on the break instructions as well as copying the then/else // instructions into place until we know whether to keep store_to_block_ptr // instructions or not. @@ -4942,21 +4967,27 @@ fn ifExpr( .err_union_code; const payload_inst = try else_scope.addUnNode(tag, cond.inst, node); const ident_name = try astgen.identAsString(error_token); + const error_token_str = tree.tokenSlice(error_token); + if (mem.eql(u8, "_", error_token_str)) + break :s &else_scope.base; payload_val_scope = .{ .parent = &else_scope.base, .gen_zir = &else_scope, .name = ident_name, .inst = payload_inst, .token_src = error_token, + .used = .capture, }; break :s &payload_val_scope.base; } else { break :s &else_scope.base; } }; + const e = try expr(&else_scope, sub_scope, block_scope.break_result_loc, else_node); + try checkUsed(parent_gz, &else_scope.base, sub_scope); break :blk .{ .src = else_node, - .result = try expr(&else_scope, sub_scope, block_scope.break_result_loc, else_node), + .result = e, }; } else .{ .src = if_full.ast.then_expr, @@ -4965,7 +4996,6 @@ fn ifExpr( return finishThenElseBlock( parent_gz, - scope, rl, node, &block_scope, @@ -4973,8 +5003,6 @@ fn ifExpr( &else_scope, condbr, cond.bool_bit, - if_full.ast.then_expr, - else_info.src, then_result, else_info.result, block, @@ -5087,7 +5115,7 @@ fn whileExpr( inst: Zir.Inst.Ref, bool_bit: Zir.Inst.Ref, } = c: { - if (while_full.error_token) |error_token| { + if (while_full.error_token) |_| { const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const err_union = try expr(&continue_scope, &continue_scope.base, cond_rl, while_full.ast.cond_expr); const tag: Zir.Inst.Tag = if (payload_is_ref) .is_err_ptr else .is_err; @@ -5095,7 +5123,7 @@ fn whileExpr( .inst = err_union, .bool_bit = try continue_scope.addUnNode(tag, err_union, node), }; - } else if (while_full.payload_token) |payload_token| { + } else if (while_full.payload_token) |_| { const cond_rl: ResultLoc = if (payload_is_ref) .ref else .none; const optional = try expr(&continue_scope, &continue_scope.base, cond_rl, while_full.ast.cond_expr); const tag: Zir.Inst.Tag = if (payload_is_ref) .is_non_null_ptr else .is_non_null; @@ -5119,11 +5147,65 @@ fn whileExpr( try loop_scope.instructions.append(astgen.gpa, cond_block); try continue_scope.setBlockBody(cond_block); - // TODO avoid emitting the continue expr when there + var then_scope = parent_gz.makeSubBlock(&continue_scope.base); + defer then_scope.instructions.deinit(astgen.gpa); + + var payload_val_scope: Scope.LocalVal = undefined; + + const then_sub_scope = s: { + if (while_full.error_token != null) { + if (while_full.payload_token) |payload_token| { + const tag: Zir.Inst.Tag = if (payload_is_ref) + .err_union_payload_unsafe_ptr + else + .err_union_payload_unsafe; + const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); + const ident_token = if (payload_is_ref) payload_token + 1 else payload_token; + if (mem.eql(u8, "_", tree.tokenSlice(ident_token))) + break :s &then_scope.base; + const ident_name = try astgen.identAsString(payload_token + @boolToInt(payload_is_ref)); + payload_val_scope = .{ + .parent = &then_scope.base, + .gen_zir = &then_scope, + .name = ident_name, + .inst = payload_inst, + .token_src = payload_token, + .used = .capture, + }; + break :s &payload_val_scope.base; + } else { + break :s &then_scope.base; + } + } else if (while_full.payload_token) |payload_token| { + const ident_token = if (payload_is_ref) payload_token + 1 else payload_token; + const tag: Zir.Inst.Tag = if (payload_is_ref) + .optional_payload_unsafe_ptr + else + .optional_payload_unsafe; + const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); + const ident_name = try astgen.identAsString(ident_token); + if (mem.eql(u8, "_", tree.tokenSlice(ident_token))) + break :s &then_scope.base; + payload_val_scope = .{ + .parent = &then_scope.base, + .gen_zir = &then_scope, + .name = ident_name, + .inst = payload_inst, + .token_src = ident_token, + .used = .capture, + }; + break :s &payload_val_scope.base; + } else { + break :s &then_scope.base; + } + }; + + // This code could be improved to avoid emitting the continue expr when there // are no jumps to it. This happens when the last statement of a while body is noreturn // and there are no `continue` statements. + // Tracking issue: https://github.com/ziglang/zig/issues/9185 if (while_full.ast.cont_expr != 0) { - _ = try expr(&loop_scope, &loop_scope.base, .{ .ty = .void_type }, while_full.ast.cont_expr); + _ = try expr(&loop_scope, then_sub_scope, .{ .ty = .void_type }, while_full.ast.cont_expr); } const repeat_tag: Zir.Inst.Tag = if (is_inline) .repeat_inline else .repeat; _ = try loop_scope.addNode(repeat_tag, node); @@ -5138,50 +5220,9 @@ fn whileExpr( }); } - var then_scope = parent_gz.makeSubBlock(&continue_scope.base); - defer then_scope.instructions.deinit(astgen.gpa); - - var payload_val_scope: Scope.LocalVal = undefined; - - const then_sub_scope = s: { - if (while_full.error_token) |error_token| { - const tag: Zir.Inst.Tag = if (payload_is_ref) - .err_union_payload_unsafe_ptr - else - .err_union_payload_unsafe; - const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); - const ident_name = try astgen.identAsString(error_token); - payload_val_scope = .{ - .parent = &then_scope.base, - .gen_zir = &then_scope, - .name = ident_name, - .inst = payload_inst, - .token_src = error_token, - }; - break :s &payload_val_scope.base; - } else if (while_full.payload_token) |payload_token| { - const ident_token = if (payload_is_ref) payload_token + 1 else payload_token; - const tag: Zir.Inst.Tag = if (payload_is_ref) - .optional_payload_unsafe_ptr - else - .optional_payload_unsafe; - const payload_inst = try then_scope.addUnNode(tag, cond.inst, node); - const ident_name = try astgen.identAsString(ident_token); - payload_val_scope = .{ - .parent = &then_scope.base, - .gen_zir = &then_scope, - .name = ident_name, - .inst = payload_inst, - .token_src = ident_token, - }; - break :s &payload_val_scope.base; - } else { - break :s &then_scope.base; - } - }; - loop_scope.break_count += 1; const then_result = try expr(&then_scope, then_sub_scope, loop_scope.break_result_loc, while_full.ast.then_expr); + try checkUsed(parent_gz, &then_scope.base, then_sub_scope); var else_scope = parent_gz.makeSubBlock(&continue_scope.base); defer else_scope.instructions.deinit(astgen.gpa); @@ -5200,21 +5241,26 @@ fn whileExpr( .err_union_code; const payload_inst = try else_scope.addUnNode(tag, cond.inst, node); const ident_name = try astgen.identAsString(error_token); + if (mem.eql(u8, tree.tokenSlice(error_token), "_")) + break :s &else_scope.base; payload_val_scope = .{ .parent = &else_scope.base, .gen_zir = &else_scope, .name = ident_name, .inst = payload_inst, .token_src = error_token, + .used = .capture, }; break :s &payload_val_scope.base; } else { break :s &else_scope.base; } }; + const e = try expr(&else_scope, sub_scope, loop_scope.break_result_loc, else_node); + try checkUsed(parent_gz, &else_scope.base, sub_scope); break :blk .{ .src = else_node, - .result = try expr(&else_scope, sub_scope, loop_scope.break_result_loc, else_node), + .result = e, }; } else .{ .src = while_full.ast.then_expr, @@ -5229,7 +5275,6 @@ fn whileExpr( const break_tag: Zir.Inst.Tag = if (is_inline) .break_inline else .@"break"; return finishThenElseBlock( parent_gz, - scope, rl, node, &loop_scope, @@ -5237,8 +5282,6 @@ fn whileExpr( &else_scope, condbr, cond.bool_bit, - while_full.ast.then_expr, - else_info.src, then_result, else_info.result, loop_block, @@ -5345,6 +5388,7 @@ fn forExpr( .name = name_str_index, .inst = payload_inst, .token_src = ident, + .used = .capture, }; payload_sub_scope = &payload_val_scope.base; } else if (is_ptr) { @@ -5367,13 +5411,15 @@ fn forExpr( .name = index_name, .ptr = index_ptr, .token_src = index_token, - .is_comptime = parent_gz.force_comptime, + .maybe_comptime = is_inline, + .used = .loop_index, }; break :blk &index_scope.base; }; loop_scope.break_count += 1; const then_result = try expr(&then_scope, then_sub_scope, loop_scope.break_result_loc, for_full.ast.then_expr); + try checkUsed(parent_gz, &then_scope.base, then_sub_scope); var else_scope = parent_gz.makeSubBlock(&cond_scope.base); defer else_scope.instructions.deinit(astgen.gpa); @@ -5402,7 +5448,6 @@ fn forExpr( const break_tag: Zir.Inst.Tag = if (is_inline) .break_inline else .@"break"; return finishThenElseBlock( parent_gz, - scope, rl, node, &loop_scope, @@ -5410,8 +5455,6 @@ fn forExpr( &else_scope, condbr, cond, - for_full.ast.then_expr, - else_info.src, then_result, else_info.result, loop_block, @@ -5614,10 +5657,12 @@ fn switchExpr( .name = capture_name, .inst = capture, .token_src = payload_token, + .used = .capture, }; break :blk &capture_val_scope.base; }; const case_result = try expr(&case_scope, sub_scope, block_scope.break_result_loc, case.ast.target_expr); + try checkUsed(parent_gz, &case_scope.base, sub_scope); if (!parent_gz.refIsNoReturn(case_result)) { block_scope.break_count += 1; _ = try case_scope.addBreak(.@"break", switch_block, case_result); @@ -5706,6 +5751,7 @@ fn switchExpr( .name = capture_name, .inst = capture, .token_src = payload_token, + .used = .capture, }; break :blk &capture_val_scope.base; }; @@ -5739,6 +5785,7 @@ fn switchExpr( } const case_result = try expr(&case_scope, sub_scope, block_scope.break_result_loc, case.ast.target_expr); + try checkUsed(parent_gz, &case_scope.base, sub_scope); if (!parent_gz.refIsNoReturn(case_result)) { block_scope.break_count += 1; _ = try case_scope.addBreak(.@"break", switch_block, case_result); @@ -5752,6 +5799,7 @@ fn switchExpr( const item_node = case.ast.values[0]; const item_inst = try comptimeExpr(parent_gz, scope, item_rl, item_node); const case_result = try expr(&case_scope, sub_scope, block_scope.break_result_loc, case.ast.target_expr); + try checkUsed(parent_gz, &case_scope.base, sub_scope); if (!parent_gz.refIsNoReturn(case_result)) { block_scope.break_count += 1; _ = try case_scope.addBreak(.@"break", switch_block, case_result); @@ -5950,7 +5998,7 @@ fn switchExpr( const block_ref = parent_gz.indexToRef(switch_block); switch (rl) { .ref => return block_ref, - else => return rvalue(parent_gz, scope, rl, block_ref, switch_node), + else => return rvalue(parent_gz, rl, block_ref, switch_node), } }, .break_void => { @@ -6016,7 +6064,6 @@ fn ret(gz: *GenZir, scope: *Scope, node: ast.Node.Index) InnerError!Zir.Inst.Ref const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); - const main_tokens = tree.nodes.items(.main_token); if (gz.in_defer) return astgen.failNode(node, "cannot return from defer expression", .{}); @@ -6092,7 +6139,7 @@ fn identifier( } if (simple_types.get(ident_name)) |zir_const_ref| { - return rvalue(gz, scope, rl, zir_const_ref, ident); + return rvalue(gz, rl, zir_const_ref, ident); } if (ident_name.len >= 2) integer: { @@ -6118,7 +6165,7 @@ fn identifier( .bit_count = bit_count, } }, }); - return rvalue(gz, scope, rl, result, ident); + return rvalue(gz, rl, result, ident); } } @@ -6131,33 +6178,37 @@ fn identifier( while (true) switch (s.tag) { .local_val => { const local_val = s.cast(Scope.LocalVal).?; - if (hit_namespace) { - // captures of non-locals need to be emitted as decl_val or decl_ref - // This *might* be capturable depending on if it is comptime known - break; - } + if (local_val.name == name_str_index) { - return rvalue(gz, scope, rl, local_val.inst, ident); + local_val.used = .used; + // Captures of non-locals need to be emitted as decl_val or decl_ref. + // This *might* be capturable depending on if it is comptime known. + if (!hit_namespace) { + return rvalue(gz, rl, local_val.inst, ident); + } } s = local_val.parent; }, .local_ptr => { const local_ptr = s.cast(Scope.LocalPtr).?; if (local_ptr.name == name_str_index) { + local_ptr.used = .used; if (hit_namespace) { - if (local_ptr.is_comptime) + if (local_ptr.maybe_comptime) break else return astgen.failNodeNotes(ident, "'{s}' not accessible from inner function", .{ident_name}, &.{ try astgen.errNoteTok(local_ptr.token_src, "declared here", .{}), // TODO add crossed function definition here note. + // Maybe add a note to the error about it being because of the var, + // maybe recommend copying it into a const variable. -SpexGuy }); } switch (rl) { .ref, .none_or_ref => return local_ptr.ptr, else => { const loaded = try gz.addUnNode(.load, local_ptr.ptr, ident); - return rvalue(gz, scope, rl, loaded, ident); + return rvalue(gz, rl, loaded, ident); }, } } @@ -6191,14 +6242,13 @@ fn identifier( .ref, .none_or_ref => return gz.addStrTok(.decl_ref, name_str_index, ident_token), else => { const result = try gz.addStrTok(.decl_val, name_str_index, ident_token); - return rvalue(gz, scope, rl, result, ident); + return rvalue(gz, rl, result, ident); }, } } fn stringLiteral( gz: *GenZir, - scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { @@ -6214,19 +6264,17 @@ fn stringLiteral( .len = str.len, } }, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn multilineStringLiteral( gz: *GenZir, - scope: *Scope, rl: ResultLoc, node: ast.Node.Index, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const node_datas = tree.nodes.items(.data); - const main_tokens = tree.nodes.items(.main_token); const start = node_datas[node].lhs; const end = node_datas[node].rhs; @@ -6258,10 +6306,10 @@ fn multilineStringLiteral( .len = @intCast(u32, string_bytes.items.len - str_index), } }, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } -fn charLiteral(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) !Zir.Inst.Ref { +fn charLiteral(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) !Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); @@ -6281,15 +6329,10 @@ fn charLiteral(gz: *GenZir, scope: *Scope, rl: ResultLoc, node: ast.Node.Index) }, }; const result = try gz.addInt(value); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } -fn integerLiteral( - gz: *GenZir, - scope: *Scope, - rl: ResultLoc, - node: ast.Node.Index, -) InnerError!Zir.Inst.Ref { +fn integerLiteral(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); @@ -6301,7 +6344,7 @@ fn integerLiteral( 1 => .one, else => try gz.addInt(small_int), }; - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } else |err| switch (err) { error.InvalidCharacter => unreachable, // Caught by the parser. error.Overflow => {}, @@ -6332,17 +6375,11 @@ fn integerLiteral( const limbs = big_int.limbs[0..big_int.len()]; assert(big_int.isPositive()); const result = try gz.addIntBig(limbs); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } -fn floatLiteral( - gz: *GenZir, - scope: *Scope, - rl: ResultLoc, - node: ast.Node.Index, -) InnerError!Zir.Inst.Ref { +fn floatLiteral(gz: *GenZir, rl: ResultLoc, node: ast.Node.Index) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; - const arena = astgen.arena; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); @@ -6363,7 +6400,7 @@ fn floatLiteral( const bigger_again: f128 = smaller_float; if (bigger_again == float_number) { const result = try gz.addFloat(smaller_float, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } // We need to use 128 bits. Break the float into 4 u32 values so we can // put it into the `extra` array. @@ -6374,7 +6411,7 @@ fn floatLiteral( .piece2 = @truncate(u32, int_bits >> 64), .piece3 = @truncate(u32, int_bits >> 96), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn asmExpr( @@ -6385,7 +6422,6 @@ fn asmExpr( full: ast.full.Asm, ) InnerError!Zir.Inst.Ref { const astgen = gz.astgen; - const arena = astgen.arena; const tree = astgen.tree; const main_tokens = tree.nodes.items(.main_token); const node_datas = tree.nodes.items(.data); @@ -6427,6 +6463,33 @@ fn asmExpr( // issues and decide how to handle outputs. Do we want this to be identifiers? // Or maybe we want to force this to be expressions with a pointer type. // Until that is figured out this is only hooked up for referencing Decls. + // TODO we have put this as an identifier lookup just so that we don't get + // unused vars for outputs. We need to check if this is correct in the future ^^ + // so we just put in this simple lookup. This is a workaround. + { + var s = scope; + while (true) switch (s.tag) { + .local_val => { + const local_val = s.cast(Scope.LocalVal).?; + if (local_val.name == str_index) { + local_val.used = .used; + break; + } + s = local_val.parent; + }, + .local_ptr => { + const local_ptr = s.cast(Scope.LocalPtr).?; + if (local_ptr.name == str_index) { + local_ptr.used = .used; + break; + } + s = local_ptr.parent; + }, + .gen_zir => s = s.cast(GenZir).?.parent, + .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent, + .namespace, .top => break, + }; + } const operand = try gz.addStrTok(.decl_ref, str_index, ident_token); outputs[i] = .{ .name = name, @@ -6447,7 +6510,6 @@ fn asmExpr( const name = try astgen.identAsString(symbolic_name); const constraint_token = symbolic_name + 2; const constraint = (try astgen.strLitAsString(constraint_token)).index; - const has_arrow = token_tags[symbolic_name + 4] == .arrow; const operand = try expr(gz, scope, .{ .ty = .usize_type }, node_datas[input_node].lhs); inputs[i] = .{ .name = name, @@ -6492,7 +6554,7 @@ fn asmExpr( .inputs = inputs, .clobbers = clobbers_buffer[0..clobber_i], }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn as( @@ -6507,7 +6569,7 @@ fn as( switch (rl) { .none, .none_or_ref, .discard, .ref, .ty => { const result = try expr(gz, scope, .{ .ty = dest_type }, rhs); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .ptr, .inferred_ptr => |result_ptr| { return asRlPtr(gz, scope, rl, result_ptr, rhs, dest_type); @@ -6529,18 +6591,18 @@ fn unionInit( const field_name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, params[1]); switch (rl) { .none, .none_or_ref, .discard, .ref, .ty, .inferred_ptr => { - const field_type = try gz.addPlNode(.field_type_ref, params[1], Zir.Inst.FieldTypeRef{ + _ = try gz.addPlNode(.field_type_ref, params[1], Zir.Inst.FieldTypeRef{ .container_type = union_type, .field_name = field_name, }); const result = try expr(gz, scope, .{ .ty = union_type }, params[2]); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .ptr => |result_ptr| { - return unionInitRlPtr(gz, scope, rl, node, result_ptr, params[2], union_type, field_name); + return unionInitRlPtr(gz, scope, node, result_ptr, params[2], union_type, field_name); }, .block_ptr => |block_scope| { - return unionInitRlPtr(gz, scope, rl, node, block_scope.rl_ptr, params[2], union_type, field_name); + return unionInitRlPtr(gz, scope, node, block_scope.rl_ptr, params[2], union_type, field_name); }, } } @@ -6548,7 +6610,6 @@ fn unionInit( fn unionInitRlPtr( parent_gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, result_ptr: Zir.Inst.Ref, expr_node: ast.Node.Index, @@ -6596,7 +6657,7 @@ fn asRlPtr( parent_zir.appendAssumeCapacity(src_inst); } const casted_result = try parent_gz.addBin(.as, dest_type, result); - return rvalue(parent_gz, scope, rl, casted_result, operand_node); + return rvalue(parent_gz, rl, casted_result, operand_node); } else { try parent_zir.appendSlice(astgen.gpa, as_scope.instructions.items); return result; @@ -6620,16 +6681,16 @@ fn bitCast( .lhs = dest_type, .rhs = operand, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .ref => { return astgen.failNode(node, "cannot take address of `@bitCast` result", .{}); }, .ptr, .inferred_ptr => |result_ptr| { - return bitCastRlPtr(gz, scope, rl, node, dest_type, result_ptr, rhs); + return bitCastRlPtr(gz, scope, node, dest_type, result_ptr, rhs); }, .block_ptr => |block| { - return bitCastRlPtr(gz, scope, rl, node, dest_type, block.rl_ptr, rhs); + return bitCastRlPtr(gz, scope, node, dest_type, block.rl_ptr, rhs); }, } } @@ -6637,7 +6698,6 @@ fn bitCast( fn bitCastRlPtr( gz: *GenZir, scope: *Scope, - rl: ResultLoc, node: ast.Node.Index, dest_type: Zir.Inst.Ref, result_ptr: Zir.Inst.Ref, @@ -6662,7 +6722,7 @@ fn typeOf( } if (params.len == 1) { const result = try gz.addUnNode(.typeof, try expr(gz, scope, .none, params[0]), node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } const arena = gz.astgen.arena; var items = try arena.alloc(Zir.Inst.Ref, params.len); @@ -6671,7 +6731,7 @@ fn typeOf( } const result = try gz.addExtendedMultiOp(.typeof_peer, node, items); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn builtinCall( @@ -6711,7 +6771,6 @@ fn builtinCall( switch (info.tag) { .import => { const node_tags = tree.nodes.items(.tag); - const node_datas = tree.nodes.items(.data); const operand_node = params[0]; if (node_tags[operand_node] != .string_literal) { @@ -6722,7 +6781,7 @@ fn builtinCall( const str = try astgen.strLitAsString(str_lit_token); try astgen.imports.put(astgen.gpa, str.index, {}); const result = try gz.addStrTok(.import, str.index, str_lit_token); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .compile_log => { const arg_refs = try astgen.gpa.alloc(Zir.Inst.Ref, params.len); @@ -6731,7 +6790,7 @@ fn builtinCall( for (params) |param, i| arg_refs[i] = try expr(gz, scope, .none, param); const result = try gz.addExtendedMultiOp(.compile_log, node, arg_refs); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .field => { const field_name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, params[1]); @@ -6745,7 +6804,7 @@ fn builtinCall( .lhs = try expr(gz, scope, .none, params[0]), .field_name = field_name, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .as => return as( gz, scope, rl, node, params[0], params[1]), .bit_cast => return bitCast( gz, scope, rl, node, params[0], params[1]), @@ -6764,9 +6823,32 @@ fn builtinCall( .identifier => { const ident_token = main_tokens[params[0]]; decl_name = try astgen.identAsString(ident_token); - // TODO look for local variables in scope matching `decl_name` and emit a compile - // error. Only top-level declarations can be exported. Until this is done, the - // compile error will end up being "use of undeclared identifier" in Sema. + { + var s = scope; + while (true) switch (s.tag) { + .local_val => { + const local_val = s.cast(Scope.LocalVal).?; + if (local_val.name == decl_name) { + local_val.used = .used; + break; + } + s = local_val.parent; + }, + .local_ptr => { + const local_ptr = s.cast(Scope.LocalPtr).?; + if (local_ptr.name == decl_name) { + if (!local_ptr.maybe_comptime) + return astgen.failNode(params[0], "unable to export runtime-known value", .{}); + local_ptr.used = .used; + break; + } + s = local_ptr.parent; + }, + .gen_zir => s = s.cast(GenZir).?.parent, + .defer_normal, .defer_error => s = s.cast(Scope.Defer).?.parent, + .namespace, .top => break, + }; + } }, .field_access => { const namespace_node = node_datas[params[0]].lhs; @@ -6776,7 +6858,7 @@ fn builtinCall( decl_name = try astgen.identAsString(field_ident); }, else => return astgen.failNode( - params[0], "the first @export parameter must be an identifier", .{}, + params[0], "symbol to export must identify a declaration", .{}, ), } const options = try comptimeExpr(gz, scope, .{ .ty = .export_options_type }, params[1]); @@ -6785,7 +6867,7 @@ fn builtinCall( .decl_name = decl_name, .options = options, }); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); }, .@"extern" => { const type_inst = try typeExpr(gz, scope, params[0]); @@ -6795,18 +6877,18 @@ fn builtinCall( .lhs = type_inst, .rhs = options, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, - .breakpoint => return simpleNoOpVoid(gz, scope, rl, node, .breakpoint), - .fence => return simpleNoOpVoid(gz, scope, rl, node, .fence), + .breakpoint => return simpleNoOpVoid(gz, rl, node, .breakpoint), + .fence => return simpleNoOpVoid(gz, rl, node, .fence), - .This => return rvalue(gz, scope, rl, try gz.addNodeExtended(.this, node), node), - .return_address => return rvalue(gz, scope, rl, try gz.addNodeExtended(.ret_addr, node), node), - .src => return rvalue(gz, scope, rl, try gz.addNodeExtended(.builtin_src, node), node), - .error_return_trace => return rvalue(gz, scope, rl, try gz.addNodeExtended(.error_return_trace, node), node), - .frame => return rvalue(gz, scope, rl, try gz.addNodeExtended(.frame, node), node), - .frame_address => return rvalue(gz, scope, rl, try gz.addNodeExtended(.frame_address, node), node), + .This => return rvalue(gz, rl, try gz.addNodeExtended(.this, node), node), + .return_address => return rvalue(gz, rl, try gz.addNodeExtended(.ret_addr, node), node), + .src => return rvalue(gz, rl, try gz.addNodeExtended(.builtin_src, node), node), + .error_return_trace => return rvalue(gz, rl, try gz.addNodeExtended(.error_return_trace, node), node), + .frame => return rvalue(gz, rl, try gz.addNodeExtended(.frame, node), node), + .frame_address => return rvalue(gz, rl, try gz.addNodeExtended(.frame_address, node), node), .type_info => return simpleUnOpType(gz, scope, rl, node, params[0], .type_info), .size_of => return simpleUnOpType(gz, scope, rl, node, params[0], .size_of), @@ -6862,7 +6944,7 @@ fn builtinCall( .lhs = dest_align, .rhs = rhs, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .has_decl => return hasDeclOrField(gz, scope, rl, node, params[0], params[1], .has_decl), @@ -6898,7 +6980,7 @@ fn builtinCall( .node = gz.nodeIndexToRelative(node), .operand = operand, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .wasm_memory_grow => { const index_arg = try expr(gz, scope, .{ .ty = .u32_type }, params[0]); @@ -6908,7 +6990,7 @@ fn builtinCall( .lhs = index_arg, .rhs = delta_arg, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .c_define => { const name = try comptimeExpr(gz, scope, .{ .ty = .const_slice_u8_type }, params[0]); @@ -6918,7 +7000,7 @@ fn builtinCall( .lhs = name, .rhs = value, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .splat => { @@ -6928,7 +7010,7 @@ fn builtinCall( .lhs = len, .rhs = scalar, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .reduce => { const op = try expr(gz, scope, .{ .ty = .reduce_op_type }, params[0]); @@ -6937,7 +7019,7 @@ fn builtinCall( .lhs = op, .rhs = scalar, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .add_with_overflow => return overflowArithmetic(gz, scope, rl, node, params, .add_with_overflow), @@ -6964,7 +7046,7 @@ fn builtinCall( .rhs = rhs, .ptr = ptr, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .atomic_load => { @@ -6984,7 +7066,7 @@ fn builtinCall( .lhs = ptr, .rhs = ordering, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .atomic_rmw => { const int_type = try typeExpr(gz, scope, params[0]); @@ -7007,7 +7089,7 @@ fn builtinCall( .operand = operand, .ordering = ordering, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .atomic_store => { const int_type = try typeExpr(gz, scope, params[0]); @@ -7028,7 +7110,7 @@ fn builtinCall( .operand = operand, .ordering = ordering, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .mul_add => { const float_type = try typeExpr(gz, scope, params[0]); @@ -7040,7 +7122,7 @@ fn builtinCall( .mulend2 = mulend2, .addend = addend, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .call => { const options = try comptimeExpr(gz, scope, .{ .ty = .call_options_type }, params[0]); @@ -7051,7 +7133,7 @@ fn builtinCall( .callee = callee, .args = args, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .field_parent_ptr => { const parent_type = try typeExpr(gz, scope, params[0]); @@ -7062,7 +7144,7 @@ fn builtinCall( .field_name = field_name, .field_ptr = try expr(gz, scope, .{ .ty = field_ptr_type }, params[2]), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .memcpy => { const result = try gz.addPlNode(.memcpy, node, Zir.Inst.Memcpy{ @@ -7070,7 +7152,7 @@ fn builtinCall( .source = try expr(gz, scope, .{ .ty = .manyptr_const_u8_type }, params[1]), .byte_count = try expr(gz, scope, .{ .ty = .usize_type }, params[2]), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .memset => { const result = try gz.addPlNode(.memset, node, Zir.Inst.Memset{ @@ -7078,7 +7160,7 @@ fn builtinCall( .byte = try expr(gz, scope, .{ .ty = .u8_type }, params[1]), .byte_count = try expr(gz, scope, .{ .ty = .usize_type }, params[2]), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .shuffle => { const result = try gz.addPlNode(.shuffle, node, Zir.Inst.Shuffle{ @@ -7087,7 +7169,7 @@ fn builtinCall( .b = try expr(gz, scope, .none, params[2]), .mask = try comptimeExpr(gz, scope, .none, params[3]), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .async_call => { const result = try gz.addPlNode(.builtin_async_call, node, Zir.Inst.AsyncCall{ @@ -7096,14 +7178,14 @@ fn builtinCall( .fn_ptr = try expr(gz, scope, .none, params[2]), .args = try expr(gz, scope, .none, params[3]), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, .Vector => { const result = try gz.addPlNode(.vector_type, node, Zir.Inst.Bin{ .lhs = try comptimeExpr(gz, scope, .{.ty = .u32_type}, params[0]), .rhs = try typeExpr(gz, scope, params[1]), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); }, } @@ -7112,13 +7194,12 @@ fn builtinCall( fn simpleNoOpVoid( gz: *GenZir, - scope: *Scope, rl: ResultLoc, node: ast.Node.Index, tag: Zir.Inst.Tag, ) InnerError!Zir.Inst.Ref { _ = try gz.addNode(tag, node); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); } fn hasDeclOrField( @@ -7136,7 +7217,7 @@ fn hasDeclOrField( .lhs = container_type, .rhs = name, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn typeCast( @@ -7152,7 +7233,7 @@ fn typeCast( .lhs = try typeExpr(gz, scope, lhs_node), .rhs = try expr(gz, scope, .none, rhs_node), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn simpleUnOpType( @@ -7165,7 +7246,7 @@ fn simpleUnOpType( ) InnerError!Zir.Inst.Ref { const operand = try typeExpr(gz, scope, operand_node); const result = try gz.addUnNode(tag, operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn simpleUnOp( @@ -7179,7 +7260,7 @@ fn simpleUnOp( ) InnerError!Zir.Inst.Ref { const operand = try expr(gz, scope, operand_rl, operand_node); const result = try gz.addUnNode(tag, operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn cmpxchg( @@ -7209,7 +7290,7 @@ fn cmpxchg( .fail_order = try expr(gz, scope, .{ .ty = .atomic_ordering_type }, params[5]), // zig fmt: on }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn bitBuiltin( @@ -7224,7 +7305,7 @@ fn bitBuiltin( const int_type = try typeExpr(gz, scope, int_type_node); const operand = try expr(gz, scope, .{ .ty = int_type }, operand_node); const result = try gz.addUnNode(tag, operand, node); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn divBuiltin( @@ -7240,7 +7321,7 @@ fn divBuiltin( .lhs = try expr(gz, scope, .none, lhs_node), .rhs = try expr(gz, scope, .none, rhs_node), }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn simpleCBuiltin( @@ -7256,7 +7337,7 @@ fn simpleCBuiltin( .node = gz.nodeIndexToRelative(node), .operand = operand, }); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); } fn offsetOf( @@ -7274,7 +7355,7 @@ fn offsetOf( .lhs = type_inst, .rhs = field_name, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn shiftOp( @@ -7293,7 +7374,7 @@ fn shiftOp( .lhs = lhs, .rhs = rhs, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn cImport( @@ -7318,7 +7399,7 @@ fn cImport( try block_scope.setBlockBody(block_inst); try gz.instructions.append(gpa, block_inst); - return rvalue(gz, scope, rl, .void_value, node); + return rvalue(gz, rl, .void_value, node); } fn overflowArithmetic( @@ -7348,7 +7429,7 @@ fn overflowArithmetic( .rhs = rhs, .ptr = ptr, }); - return rvalue(gz, scope, rl, result, node); + return rvalue(gz, rl, result, node); } fn callExpr( @@ -7400,7 +7481,7 @@ fn callExpr( }; break :res try gz.addCall(tag, lhs, args, node); }; - return rvalue(gz, scope, rl, result, node); // TODO function call with result location + return rvalue(gz, rl, result, node); // TODO function call with result location } pub const simple_types = std.ComptimeStringMap(Zir.Inst.Ref, .{ @@ -7876,7 +7957,6 @@ fn nodeMayEvalToError(tree: *const ast.Tree, start_node: ast.Node.Index) enum { /// If the `ResultLoc` is `ty`, it will coerce the result to the type. fn rvalue( gz: *GenZir, - scope: *Scope, rl: ResultLoc, result: Zir.Inst.Ref, src_node: ast.Node.Index, @@ -8024,7 +8104,6 @@ fn parseStrLit( bytes: []const u8, offset: u32, ) InnerError!void { - const tree = astgen.tree; const raw_string = bytes[offset..]; var buf_managed = buf.toManaged(astgen.gpa); const result = std.zig.string_literal.parseAppend(&buf_managed, raw_string); @@ -8327,6 +8406,15 @@ const Scope = struct { top, }; + // either .used or the type of the var/constant + const Used = enum { + fn_param, + constant, + variable, + loop_index, + capture, + used, + }; /// This is always a `const` local and importantly the `inst` is a value type, not a pointer. /// This structure lives as long as the AST generation of the Block /// node that contains the variable. @@ -8341,6 +8429,8 @@ const Scope = struct { token_src: ast.TokenIndex, /// String table index. name: u32, + /// has this variable been referenced? + used: Used, }; /// This could be a `const` or `var` local. It has a pointer instead of a value. @@ -8357,7 +8447,10 @@ const Scope = struct { token_src: ast.TokenIndex, /// String table index. name: u32, - is_comptime: bool, + /// true means we find out during Sema whether the value is comptime. false means it is already known at AstGen the value is runtime-known. + maybe_comptime: bool, + /// has this variable been referenced? + used: Used, }; const Defer = struct { @@ -8467,7 +8560,6 @@ const GenZir = struct { fn calcLine(gz: GenZir, node: ast.Node.Index) u32 { const astgen = gz.astgen; const tree = astgen.tree; - const node_tags = tree.nodes.items(.tag); const token_starts = tree.tokens.items(.start); const decl_start = token_starts[tree.firstToken(gz.decl_node_index)]; const node_start = token_starts[tree.firstToken(node)]; diff --git a/src/Compilation.zig b/src/Compilation.zig index 867b945213..7dbfb5068a 100644 --- a/src/Compilation.zig +++ b/src/Compilation.zig @@ -325,7 +325,6 @@ pub const AllErrors = struct { }, pub fn renderToStdErr(msg: Message, ttyconf: std.debug.TTY.Config) void { - const stderr_mutex = std.debug.getStderrMutex(); const held = std.debug.getStderrMutex().acquire(); defer held.release(); const stderr = std.io.getStdErr(); @@ -524,6 +523,7 @@ pub const AllErrors = struct { errors: *std.ArrayList(Message), msg: []const u8, ) !void { + _ = arena; try errors.append(.{ .plain = .{ .msg = msg } }); } @@ -1639,7 +1639,7 @@ pub fn update(self: *Compilation) !void { // Make sure std.zig is inside the import_table. We unconditionally need // it for start.zig. const std_pkg = module.root_pkg.table.get("std").?; - _ = try module.importPkg(module.root_pkg, std_pkg); + _ = try module.importPkg(std_pkg); // Put a work item in for every known source file to detect if // it changed, and, if so, re-compute ZIR and then queue the job @@ -2283,8 +2283,12 @@ fn workerAstGenFile( ) void { defer wg.finish(); + var child_prog_node = prog_node.start(file.sub_file_path, 0); + child_prog_node.activate(); + defer child_prog_node.end(); + const mod = comp.bin_file.options.module.?; - mod.astGenFile(file, prog_node) catch |err| switch (err) { + mod.astGenFile(file) catch |err| switch (err) { error.AnalysisFail => return, else => { file.status = .retryable_failure; @@ -2373,7 +2377,7 @@ pub fn cImport(comp: *Compilation, c_src: []const u8) !CImportResult { // We need to "unhit" in this case, to keep the digests matching. const prev_hash_state = man.hash.peekBin(); const actual_hit = hit: { - const is_hit = try man.hit(); + _ = try man.hit(); if (man.files.items.len == 0) { man.unhit(prev_hash_state, 0); break :hit false; diff --git a/src/DepTokenizer.zig b/src/DepTokenizer.zig index b21c893850..0fd26532f0 100644 --- a/src/DepTokenizer.zig +++ b/src/DepTokenizer.zig @@ -944,7 +944,7 @@ fn printLabel(out: anytype, label: []const u8, bytes: []const u8) !void { try out.writeAll(text); var i: usize = text.len; const end = 79; - while (i < 79) : (i += 1) { + while (i < end) : (i += 1) { try out.writeAll(&[_]u8{label[0]}); } try out.writeAll("\n"); @@ -953,7 +953,7 @@ fn printLabel(out: anytype, label: []const u8, bytes: []const u8) !void { fn printRuler(out: anytype) !void { var i: usize = 0; const end = 79; - while (i < 79) : (i += 1) { + while (i < end) : (i += 1) { try out.writeAll("-"); } try out.writeAll("\n"); @@ -1057,4 +1057,3 @@ const printable_char_tab: [256]u8 = ( "................................................................" ++ "................................................................" ).*; - diff --git a/src/Module.zig b/src/Module.zig index 8e868c4ed8..5e94382648 100644 --- a/src/Module.zig +++ b/src/Module.zig @@ -774,7 +774,10 @@ pub const Fn = struct { ir.dumpFn(mod, func); } - pub fn deinit(func: *Fn, gpa: *Allocator) void {} + pub fn deinit(func: *Fn, gpa: *Allocator) void { + _ = func; + _ = gpa; + } }; pub const Var = struct { @@ -1561,7 +1564,6 @@ pub const SrcLoc = struct { .node_offset_array_access_index => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); const node_datas = tree.nodes.items(.data); - const node_tags = tree.nodes.items(.tag); const node = src_loc.declRelativeToNodeIndex(node_off); const main_tokens = tree.nodes.items(.main_token); const tok_index = main_tokens[node_datas[node].rhs]; @@ -1570,7 +1572,6 @@ pub const SrcLoc = struct { }, .node_offset_slice_sentinel => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); - const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const node = src_loc.declRelativeToNodeIndex(node_off); const full = switch (node_tags[node]) { @@ -1586,7 +1587,6 @@ pub const SrcLoc = struct { }, .node_offset_call_func => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); - const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const node = src_loc.declRelativeToNodeIndex(node_off); var params: [1]ast.Node.Index = undefined; @@ -1625,7 +1625,6 @@ pub const SrcLoc = struct { .node_offset_deref_ptr => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); const node_datas = tree.nodes.items(.data); - const node_tags = tree.nodes.items(.tag); const node = src_loc.declRelativeToNodeIndex(node_off); const tok_index = node_datas[node].lhs; const token_starts = tree.tokens.items(.start); @@ -1633,7 +1632,6 @@ pub const SrcLoc = struct { }, .node_offset_asm_source => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); - const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const node = src_loc.declRelativeToNodeIndex(node_off); const full = switch (node_tags[node]) { @@ -1648,7 +1646,6 @@ pub const SrcLoc = struct { }, .node_offset_asm_ret_ty => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); - const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const node = src_loc.declRelativeToNodeIndex(node_off); const full = switch (node_tags[node]) { @@ -1771,7 +1768,6 @@ pub const SrcLoc = struct { .node_offset_fn_type_cc => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); - const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const node = src_loc.declRelativeToNodeIndex(node_off); var params: [1]ast.Node.Index = undefined; @@ -1790,7 +1786,6 @@ pub const SrcLoc = struct { .node_offset_fn_type_ret_ty => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); - const node_datas = tree.nodes.items(.data); const node_tags = tree.nodes.items(.tag); const node = src_loc.declRelativeToNodeIndex(node_off); var params: [1]ast.Node.Index = undefined; @@ -1810,7 +1805,6 @@ pub const SrcLoc = struct { .node_offset_anyframe_type => |node_off| { const tree = try src_loc.file_scope.getTree(gpa); const node_datas = tree.nodes.items(.data); - const node_tags = tree.nodes.items(.tag); const parent_node = src_loc.declRelativeToNodeIndex(node_off); const node = node_datas[parent_node].rhs; const main_tokens = tree.nodes.items(.main_token); @@ -2217,7 +2211,7 @@ comptime { } } -pub fn astGenFile(mod: *Module, file: *Scope.File, prog_node: *std.Progress.Node) !void { +pub fn astGenFile(mod: *Module, file: *Scope.File) !void { const tracy = trace(@src()); defer tracy.end(); @@ -2502,7 +2496,6 @@ pub fn astGenFile(mod: *Module, file: *Scope.File, prog_node: *std.Progress.Node @ptrCast([*]const u8, file.zir.instructions.items(.data).ptr); if (data_has_safety_tag) { // The `Data` union has a safety tag but in the file format we store it without. - const tags = file.zir.instructions.items(.tag); for (file.zir.instructions.items(.data)) |*data, i| { const as_struct = @ptrCast(*const Stage1DataLayout, data); safety_buffer[i] = as_struct.data; @@ -2838,7 +2831,7 @@ pub fn ensureDeclAnalyzed(mod: *Module, decl: *Decl) InnerError!void { } pub fn semaPkg(mod: *Module, pkg: *Package) !void { - const file = (try mod.importPkg(mod.root_pkg, pkg)).file; + const file = (try mod.importPkg(pkg)).file; return mod.semaFile(file); } @@ -3137,7 +3130,7 @@ pub const ImportFileResult = struct { is_new: bool, }; -pub fn importPkg(mod: *Module, cur_pkg: *Package, pkg: *Package) !ImportFileResult { +pub fn importPkg(mod: *Module, pkg: *Package) !ImportFileResult { const gpa = mod.gpa; // The resolved path is used as the key in the import table, to detect if @@ -3190,7 +3183,7 @@ pub fn importFile( import_string: []const u8, ) !ImportFileResult { if (cur_file.pkg.table.get(import_string)) |pkg| { - return mod.importPkg(cur_file.pkg, pkg); + return mod.importPkg(pkg); } const gpa = mod.gpa; @@ -3386,7 +3379,6 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) InnerError!vo log.debug("scan existing {*} ({s}) of {*}", .{ decl, decl.name, namespace }); // Update the AST node of the decl; even if its contents are unchanged, it may // have been re-ordered. - const prev_src_node = decl.src_node; decl.src_node = decl_node; decl.src_line = line; @@ -3395,7 +3387,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) InnerError!vo decl.has_align = has_align; decl.has_linksection = has_linksection; decl.zir_decl_index = @intCast(u32, decl_sub_index); - if (decl.getFunction()) |func| { + if (decl.getFunction()) |_| { switch (mod.comp.bin_file.tag) { .coff => { // TODO Implement for COFF @@ -3764,6 +3756,7 @@ pub fn analyzeExport( errdefer de_gop.value_ptr.* = mod.gpa.shrink(de_gop.value_ptr.*, de_gop.value_ptr.len - 1); } pub fn constInst(mod: *Module, arena: *Allocator, src: LazySrcLoc, typed_value: TypedValue) !*ir.Inst { + _ = mod; const const_inst = try arena.create(ir.Inst.Constant); const_inst.* = .{ .base = .{ @@ -4132,6 +4125,7 @@ pub fn floatAdd( lhs: Value, rhs: Value, ) !Value { + _ = src; switch (float_type.tag()) { .f16 => { @panic("TODO add __trunctfhf2 to compiler-rt"); @@ -4165,6 +4159,7 @@ pub fn floatSub( lhs: Value, rhs: Value, ) !Value { + _ = src; switch (float_type.tag()) { .f16 => { @panic("TODO add __trunctfhf2 to compiler-rt"); @@ -4198,6 +4193,7 @@ pub fn floatDiv( lhs: Value, rhs: Value, ) !Value { + _ = src; switch (float_type.tag()) { .f16 => { @panic("TODO add __trunctfhf2 to compiler-rt"); @@ -4231,6 +4227,7 @@ pub fn floatMul( lhs: Value, rhs: Value, ) !Value { + _ = src; switch (float_type.tag()) { .f16 => { @panic("TODO add __trunctfhf2 to compiler-rt"); @@ -4264,6 +4261,7 @@ pub fn simplePtrType( mutable: bool, size: std.builtin.TypeInfo.Pointer.Size, ) Allocator.Error!Type { + _ = mod; if (!mutable and size == .Slice and elem_ty.eql(Type.initTag(.u8))) { return Type.initTag(.const_slice_u8); } @@ -4298,6 +4296,7 @@ pub fn ptrType( @"volatile": bool, size: std.builtin.TypeInfo.Pointer.Size, ) Allocator.Error!Type { + _ = mod; assert(host_size == 0 or bit_offset < host_size * 8); // TODO check if type can be represented by simplePtrType @@ -4315,6 +4314,7 @@ pub fn ptrType( } pub fn optionalType(mod: *Module, arena: *Allocator, child_type: Type) Allocator.Error!Type { + _ = mod; switch (child_type.tag()) { .single_const_pointer => return Type.Tag.optional_single_const_pointer.create( arena, @@ -4335,6 +4335,7 @@ pub fn arrayType( sentinel: ?Value, elem_type: Type, ) Allocator.Error!Type { + _ = mod; if (elem_type.eql(Type.initTag(.u8))) { if (sentinel) |some| { if (some.eql(Value.initTag(.zero))) { @@ -4365,6 +4366,7 @@ pub fn errorUnionType( error_set: Type, payload: Type, ) Allocator.Error!Type { + _ = mod; assert(error_set.zigTypeTag() == .ErrorSet); if (error_set.eql(Type.initTag(.anyerror)) and payload.eql(Type.initTag(.void))) { return Type.initTag(.anyerror_void_error_union); @@ -4692,11 +4694,9 @@ pub fn analyzeUnionFields(mod: *Module, union_obj: *Union) InnerError!void { const src: LazySrcLoc = .{ .node_offset = union_obj.node_offset }; extra_index += @boolToInt(small.has_src_node); - const tag_type_ref = if (small.has_tag_type) blk: { - const tag_type_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]); + if (small.has_tag_type) { extra_index += 1; - break :blk tag_type_ref; - } else .none; + } const body_len = if (small.has_body_len) blk: { const body_len = zir.extra[extra_index]; @@ -4784,6 +4784,7 @@ pub fn analyzeUnionFields(mod: *Module, union_obj: *Union) InnerError!void { cur_bit_bag >>= 1; const unused = @truncate(u1, cur_bit_bag) != 0; cur_bit_bag >>= 1; + _ = unused; const field_name_zir = zir.nullTerminatedString(zir.extra[extra_index]); extra_index += 1; @@ -4800,11 +4801,9 @@ pub fn analyzeUnionFields(mod: *Module, union_obj: *Union) InnerError!void { break :blk align_ref; } else .none; - const tag_ref: Zir.Inst.Ref = if (has_tag) blk: { - const tag_ref = @intToEnum(Zir.Inst.Ref, zir.extra[extra_index]); + if (has_tag) { extra_index += 1; - break :blk tag_ref; - } else .none; + } // This string needs to outlive the ZIR code. const field_name = try decl_arena.allocator.dupe(u8, field_name_zir); diff --git a/src/Sema.zig b/src/Sema.zig index 62b9fcb7db..1e1aadcc76 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -702,6 +702,7 @@ fn zirBitcastResultPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) I } fn zirCoerceResultPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = inst; const tracy = trace(@src()); defer tracy.end(); return sema.mod.fail(&block.base, sema.src, "TODO implement zirCoerceResultPtr", .{}); @@ -776,6 +777,7 @@ fn zirStructDecl( } fn createTypeName(sema: *Sema, block: *Scope.Block, name_strategy: Zir.Inst.NameStrategy) ![:0]u8 { + _ = block; switch (name_strategy) { .anon => { // It would be neat to have "struct:line:column" but this name has @@ -1074,6 +1076,10 @@ fn zirOpaqueDecl( const src = inst_data.src(); const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index); + _ = name_strategy; + _ = inst_data; + _ = src; + _ = extra; return sema.mod.fail(&block.base, sema.src, "TODO implement zirOpaqueDecl", .{}); } @@ -1230,14 +1236,13 @@ fn zirIndexablePtrLen(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) In fn zirArg(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { const inst_data = sema.code.instructions.items(.data)[inst].str_tok; - const src = inst_data.src(); const arg_name = inst_data.get(sema.code); const arg_index = sema.next_arg_index; sema.next_arg_index += 1; // TODO check if arg_name shadows a Decl - if (block.inlining) |inlining| { + if (block.inlining) |_| { return sema.param_inst_list[arg_index]; } @@ -1636,6 +1641,7 @@ fn zirStr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*In } fn zirInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const tracy = trace(@src()); defer tracy.end(); @@ -1644,6 +1650,7 @@ fn zirInt(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*In } fn zirIntBig(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const tracy = trace(@src()); defer tracy.end(); @@ -1661,6 +1668,7 @@ fn zirIntBig(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError! } fn zirFloat(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const arena = sema.arena; const inst_data = sema.code.instructions.items(.data)[inst].float; const src = inst_data.src(); @@ -1673,6 +1681,7 @@ fn zirFloat(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!* } fn zirFloat128(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const arena = sema.arena; const inst_data = sema.code.instructions.items(.data)[inst].pl_node; const extra = sema.code.extraData(Zir.Inst.Float128, inst_data.payload_index).data; @@ -2354,6 +2363,7 @@ fn analyzeCall( } fn zirIntType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const tracy = trace(@src()); defer tracy.end(); @@ -2462,6 +2472,7 @@ fn zirErrorUnionType(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) Inn } fn zirErrorValue(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const tracy = trace(@src()); defer tracy.end(); @@ -2622,6 +2633,7 @@ fn zirMergeErrorSets(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) Inn } fn zirEnumLiteral(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const tracy = trace(@src()); defer tracy.end(); @@ -3005,7 +3017,6 @@ fn zirFunc( defer tracy.end(); const inst_data = sema.code.instructions.items(.data)[inst].pl_node; - const src = inst_data.src(); const extra = sema.code.extraData(Zir.Inst.Func, inst_data.payload_index); const param_types = sema.code.refSlice(extra.end, extra.data.param_types_len); @@ -3061,7 +3072,9 @@ fn funcCommon( const fn_ty: Type = fn_ty: { // Hot path for some common function types. - if (zir_param_types.len == 0 and !var_args and align_val.tag() == .null_value) { + if (zir_param_types.len == 0 and !var_args and align_val.tag() == .null_value and + !inferred_error_set) + { if (return_type.zigTypeTag() == .NoReturn and cc == .Unspecified) { break :fn_ty Type.initTag(.fn_noreturn_no_args); } @@ -3092,6 +3105,10 @@ fn funcCommon( return mod.fail(&block.base, src, "TODO implement support for function prototypes to have alignment specified", .{}); } + if (inferred_error_set) { + return mod.fail(&block.base, src, "TODO implement functions with inferred error sets", .{}); + } + break :fn_ty try Type.Tag.function.create(sema.arena, .{ .param_types = param_types, .return_type = return_type, @@ -3332,9 +3349,7 @@ fn zirBitcast(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError defer tracy.end(); const inst_data = sema.code.instructions.items(.data)[inst].pl_node; - const src = inst_data.src(); const dest_ty_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node }; - const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg1 = inst_data.src_node }; const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data; const dest_type = try sema.resolveType(block, dest_ty_src, extra.lhs); @@ -3499,6 +3514,8 @@ fn zirSwitchCapture( const switch_info = zir_datas[capture_info.switch_inst].pl_node; const src = switch_info.src(); + _ = is_ref; + _ = is_multi; return sema.mod.fail(&block.base, src, "TODO implement Sema for zirSwitchCapture", .{}); } @@ -3516,6 +3533,7 @@ fn zirSwitchCaptureElse( const switch_info = zir_datas[capture_info.switch_inst].pl_node; const src = switch_info.src(); + _ = is_ref; return sema.mod.fail(&block.base, src, "TODO implement Sema for zirSwitchCaptureElse", .{}); } @@ -3653,7 +3671,6 @@ fn analyzeSwitch( extra_index += 1; const body_len = sema.code.extra[extra_index]; extra_index += 1; - const body = sema.code.extra[extra_index..][0..body_len]; extra_index += body_len; try sema.validateSwitchItemEnum( @@ -3763,7 +3780,6 @@ fn analyzeSwitch( extra_index += 1; const body_len = sema.code.extra[extra_index]; extra_index += 1; - const body = sema.code.extra[extra_index..][0..body_len]; extra_index += body_len; try sema.validateSwitchItem( @@ -3859,7 +3875,6 @@ fn analyzeSwitch( extra_index += 1; const body_len = sema.code.extra[extra_index]; extra_index += 1; - const body = sema.code.extra[extra_index..][0..body_len]; extra_index += body_len; try sema.validateSwitchItemBool( @@ -3942,7 +3957,6 @@ fn analyzeSwitch( extra_index += 1; const body_len = sema.code.extra[extra_index]; extra_index += 1; - const body = sema.code.extra[extra_index..][0..body_len]; extra_index += body_len; try sema.validateSwitchItemSparse( @@ -4457,6 +4471,7 @@ fn validateSwitchNoRange( fn zirHasField(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { const inst_data = sema.code.instructions.items(.data)[inst].pl_node; const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data; + _ = extra; const src = inst_data.src(); return sema.mod.fail(&block.base, src, "TODO implement zirHasField", .{}); @@ -4515,12 +4530,17 @@ fn zirImport(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError! fn zirShl(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { const tracy = trace(@src()); defer tracy.end(); + + _ = block; + _ = inst; return sema.mod.fail(&block.base, sema.src, "TODO implement zirShl", .{}); } fn zirShr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { const tracy = trace(@src()); defer tracy.end(); + + _ = inst; return sema.mod.fail(&block.base, sema.src, "TODO implement zirShr", .{}); } @@ -4590,18 +4610,24 @@ fn zirBitwise( fn zirBitNot(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { const tracy = trace(@src()); defer tracy.end(); + + _ = inst; return sema.mod.fail(&block.base, sema.src, "TODO implement zirBitNot", .{}); } fn zirArrayCat(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { const tracy = trace(@src()); defer tracy.end(); + + _ = inst; return sema.mod.fail(&block.base, sema.src, "TODO implement zirArrayCat", .{}); } fn zirArrayMul(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { const tracy = trace(@src()); defer tracy.end(); + + _ = inst; return sema.mod.fail(&block.base, sema.src, "TODO implement zirArrayMul", .{}); } @@ -5061,6 +5087,7 @@ fn zirTypeInfo(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerErro } fn zirTypeof(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const zir_datas = sema.code.instructions.items(.data); const inst_data = zir_datas[inst].un_node; const src = inst_data.src(); @@ -5069,6 +5096,7 @@ fn zirTypeof(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError! } fn zirTypeofElem(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!*Inst { + _ = block; const inst_data = sema.code.instructions.items(.data)[inst].un_node; const src = inst_data.src(); const operand_ptr = try sema.resolveInst(inst_data.operand); @@ -5594,6 +5622,10 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: return mod.failWithOwnedErrorMsg(&block.base, msg); } + if (is_ref) { + return mod.fail(&block.base, src, "TODO: Sema.zirStructInit is_ref=true", .{}); + } + const is_comptime = for (field_inits) |field_init| { if (field_init.value() == null) { break false; @@ -5617,18 +5649,24 @@ fn zirStructInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: fn zirStructInitAnon(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) InnerError!*Inst { const inst_data = sema.code.instructions.items(.data)[inst].pl_node; const src = inst_data.src(); + + _ = is_ref; return sema.mod.fail(&block.base, src, "TODO: Sema.zirStructInitAnon", .{}); } fn zirArrayInit(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) InnerError!*Inst { const inst_data = sema.code.instructions.items(.data)[inst].pl_node; const src = inst_data.src(); + + _ = is_ref; return sema.mod.fail(&block.base, src, "TODO: Sema.zirArrayInit", .{}); } fn zirArrayInitAnon(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index, is_ref: bool) InnerError!*Inst { const inst_data = sema.code.instructions.items(.data)[inst].pl_node; const src = inst_data.src(); + + _ = is_ref; return sema.mod.fail(&block.base, src, "TODO: Sema.zirArrayInitAnon", .{}); } @@ -5771,7 +5809,6 @@ fn zirIntToPtr(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerErro return sema.mod.fail(&block.base, type_src, "expected pointer, found '{}'", .{type_res}); const ptr_align = type_res.ptrAlignment(sema.mod.getTarget()); - const uncasted_operand = try sema.resolveInst(extra.rhs); if (try sema.resolveDefinedValue(block, operand_src, operand_coerced)) |val| { const addr = val.toUnsignedInt(); if (!type_res.isAllowzeroPtr() and addr == 0) @@ -6025,6 +6062,8 @@ fn zirAwait( ) InnerError!*Inst { const inst_data = sema.code.instructions.items(.data)[inst].un_node; const src = inst_data.src(); + + _ = is_nosuspend; return sema.mod.fail(&block.base, src, "TODO: Sema.zirAwait", .{}); } @@ -6035,7 +6074,6 @@ fn zirVarExtended( ) InnerError!*Inst { const extra = sema.code.extraData(Zir.Inst.ExtendedVar, extended.operand); const src = sema.src; - const align_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at align const ty_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at type const mut_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at mut token const init_src: LazySrcLoc = src; // TODO add a LazySrcLoc that points at init expr @@ -6305,6 +6343,8 @@ fn addSafetyCheck(sema: *Sema, parent_block: *Scope.Block, ok: *Inst, panic_id: } fn safetyPanic(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, panic_id: PanicId) !Zir.Inst.Index { + _ = sema; + _ = panic_id; // TODO Once we have a panic function to call, call it here instead of breakpoint. _ = try block.addNoOp(src, Type.initTag(.void), .breakpoint); _ = try block.addNoOp(src, Type.initTag(.noreturn), .unreach); @@ -6618,6 +6658,8 @@ fn elemPtrArray( }); } } + _ = elem_index; + _ = elem_index_src; return sema.mod.fail(&block.base, src, "TODO implement more analyze elemptr for arrays", .{}); } @@ -7131,6 +7173,7 @@ fn analyzeSlice( ptr_child.isVolatilePtr(), return_ptr_size, ); + _ = return_type; return sema.mod.fail(&block.base, src, "TODO implement analysis of slice", .{}); } @@ -7476,14 +7519,14 @@ fn resolveTypeFields(sema: *Sema, block: *Scope.Block, src: LazySrcLoc, ty: Type struct_obj.status = .have_field_types; return ty; }, - .extern_options => return sema.resolveBuiltinTypeFields(block, src, ty, "ExternOptions"), - .export_options => return sema.resolveBuiltinTypeFields(block, src, ty, "ExportOptions"), - .atomic_ordering => return sema.resolveBuiltinTypeFields(block, src, ty, "AtomicOrdering"), - .atomic_rmw_op => return sema.resolveBuiltinTypeFields(block, src, ty, "AtomicRmwOp"), - .calling_convention => return sema.resolveBuiltinTypeFields(block, src, ty, "CallingConvention"), - .float_mode => return sema.resolveBuiltinTypeFields(block, src, ty, "FloatMode"), - .reduce_op => return sema.resolveBuiltinTypeFields(block, src, ty, "ReduceOp"), - .call_options => return sema.resolveBuiltinTypeFields(block, src, ty, "CallOptions"), + .extern_options => return sema.resolveBuiltinTypeFields(block, src, "ExternOptions"), + .export_options => return sema.resolveBuiltinTypeFields(block, src, "ExportOptions"), + .atomic_ordering => return sema.resolveBuiltinTypeFields(block, src, "AtomicOrdering"), + .atomic_rmw_op => return sema.resolveBuiltinTypeFields(block, src, "AtomicRmwOp"), + .calling_convention => return sema.resolveBuiltinTypeFields(block, src, "CallingConvention"), + .float_mode => return sema.resolveBuiltinTypeFields(block, src, "FloatMode"), + .reduce_op => return sema.resolveBuiltinTypeFields(block, src, "ReduceOp"), + .call_options => return sema.resolveBuiltinTypeFields(block, src, "CallOptions"), .@"union", .union_tagged => { const union_obj = ty.cast(Type.Payload.Union).?.data; @@ -7509,7 +7552,6 @@ fn resolveBuiltinTypeFields( sema: *Sema, block: *Scope.Block, src: LazySrcLoc, - ty: Type, name: []const u8, ) InnerError!Type { const resolved_ty = try sema.getBuiltinType(block, src, name); @@ -7524,7 +7566,7 @@ fn getBuiltinType( ) InnerError!Type { const mod = sema.mod; const std_pkg = mod.root_pkg.table.get("std").?; - const std_file = (mod.importPkg(mod.root_pkg, std_pkg) catch unreachable).file; + const std_file = (mod.importPkg(std_pkg) catch unreachable).file; const opt_builtin_inst = try sema.analyzeNamespaceLookup( block, src, diff --git a/src/ThreadPool.zig b/src/ThreadPool.zig index e66742b49e..4a7fa8cb9b 100644 --- a/src/ThreadPool.zig +++ b/src/ThreadPool.zig @@ -101,7 +101,7 @@ pub fn deinit(self: *ThreadPool) void { pub fn spawn(self: *ThreadPool, comptime func: anytype, args: anytype) !void { if (std.builtin.single_threaded) { - const result = @call(.{}, func, args); + @call(.{}, func, args); return; } @@ -114,7 +114,7 @@ pub fn spawn(self: *ThreadPool, comptime func: anytype, args: anytype) !void { fn runFn(runnable: *Runnable) void { const run_node = @fieldParentPtr(RunQueue.Node, "data", runnable); const closure = @fieldParentPtr(@This(), "run_node", run_node); - const result = @call(.{}, func, closure.arguments); + @call(.{}, func, closure.arguments); const held = closure.pool.lock.acquire(); defer held.release(); diff --git a/src/Zir.zig b/src/Zir.zig index 0c8855bbc9..5d75030711 100644 --- a/src/Zir.zig +++ b/src/Zir.zig @@ -3176,6 +3176,7 @@ const Writer = struct { inst: Inst.Index, ) (@TypeOf(stream).Error || error{OutOfMemory})!void { const inst_data = self.code.instructions.items(.data)[inst].array_type_sentinel; + _ = inst_data; try stream.writeAll("TODO)"); } @@ -3213,6 +3214,7 @@ const Writer = struct { inst: Inst.Index, ) (@TypeOf(stream).Error || error{OutOfMemory})!void { const inst_data = self.code.instructions.items(.data)[inst].ptr_type; + _ = inst_data; try stream.writeAll("TODO)"); } @@ -3559,6 +3561,8 @@ const Writer = struct { assert(body.len == 0); try stream.writeAll("{}, {})"); } else { + const prev_parent_decl_node = self.parent_decl_node; + if (src_node) |off| self.parent_decl_node = self.relativeToNodeIndex(off); self.indent += 2; if (body.len == 0) { try stream.writeAll("{}, {\n"); @@ -3621,6 +3625,7 @@ const Writer = struct { try stream.writeAll(",\n"); } + self.parent_decl_node = prev_parent_decl_node; self.indent -= 2; try stream.writeByteNTimes(' ', self.indent); try stream.writeAll("})"); @@ -3689,6 +3694,8 @@ const Writer = struct { const body = self.code.extra[extra_index..][0..body_len]; extra_index += body.len; + const prev_parent_decl_node = self.parent_decl_node; + if (src_node) |off| self.parent_decl_node = self.relativeToNodeIndex(off); self.indent += 2; if (body.len == 0) { try stream.writeAll("{}, {\n"); @@ -3754,6 +3761,7 @@ const Writer = struct { try stream.writeAll(",\n"); } + self.parent_decl_node = prev_parent_decl_node; self.indent -= 2; try stream.writeByteNTimes(' ', self.indent); try stream.writeAll("})"); @@ -3909,6 +3917,8 @@ const Writer = struct { assert(body.len == 0); try stream.writeAll("{}, {})"); } else { + const prev_parent_decl_node = self.parent_decl_node; + if (src_node) |off| self.parent_decl_node = self.relativeToNodeIndex(off); self.indent += 2; if (body.len == 0) { try stream.writeAll("{}, {\n"); @@ -3949,6 +3959,7 @@ const Writer = struct { } try stream.writeAll(",\n"); } + self.parent_decl_node = prev_parent_decl_node; self.indent -= 2; try stream.writeByteNTimes(' ', self.indent); try stream.writeAll("})"); @@ -4431,6 +4442,7 @@ const Writer = struct { } fn writeInstIndex(self: *Writer, stream: anytype, inst: Inst.Index) !void { + _ = self; return stream.print("%{d}", .{inst}); } @@ -4451,6 +4463,7 @@ const Writer = struct { name: []const u8, flag: bool, ) !void { + _ = self; if (!flag) return; try stream.writeAll(name); } @@ -4739,7 +4752,6 @@ fn findDeclsSwitch( var extra_index: usize = special.end; var scalar_i: usize = 0; while (scalar_i < extra.data.cases_len) : (scalar_i += 1) { - const item_ref = @intToEnum(Inst.Ref, zir.extra[extra_index]); extra_index += 1; const body_len = zir.extra[extra_index]; extra_index += 1; @@ -4779,7 +4791,6 @@ fn findDeclsSwitchMulti( { var scalar_i: usize = 0; while (scalar_i < extra.data.scalar_cases_len) : (scalar_i += 1) { - const item_ref = @intToEnum(Inst.Ref, zir.extra[extra_index]); extra_index += 1; const body_len = zir.extra[extra_index]; extra_index += 1; @@ -4800,12 +4811,11 @@ fn findDeclsSwitchMulti( extra_index += 1; const items = zir.refSlice(extra_index, items_len); extra_index += items_len; + _ = items; var range_i: usize = 0; while (range_i < ranges_len) : (range_i += 1) { - const item_first = @intToEnum(Inst.Ref, zir.extra[extra_index]); extra_index += 1; - const item_last = @intToEnum(Inst.Ref, zir.extra[extra_index]); extra_index += 1; } diff --git a/src/air.zig b/src/air.zig index 4731b847e6..37126f8153 100644 --- a/src/air.zig +++ b/src/air.zig @@ -304,9 +304,12 @@ pub const Inst = struct { base: Inst, pub fn operandCount(self: *const NoOp) usize { + _ = self; return 0; } pub fn getOperand(self: *const NoOp, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; @@ -316,6 +319,7 @@ pub const Inst = struct { operand: *Inst, pub fn operandCount(self: *const UnOp) usize { + _ = self; return 1; } pub fn getOperand(self: *const UnOp, index: usize) ?*Inst { @@ -331,6 +335,7 @@ pub const Inst = struct { rhs: *Inst, pub fn operandCount(self: *const BinOp) usize { + _ = self; return 2; } pub fn getOperand(self: *const BinOp, index: usize) ?*Inst { @@ -356,9 +361,12 @@ pub const Inst = struct { name: [*:0]const u8, pub fn operandCount(self: *const Arg) usize { + _ = self; return 0; } pub fn getOperand(self: *const Arg, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; @@ -391,9 +399,12 @@ pub const Inst = struct { body: Body, pub fn operandCount(self: *const Block) usize { + _ = self; return 0; } pub fn getOperand(self: *const Block, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; @@ -412,9 +423,12 @@ pub const Inst = struct { body: Body, pub fn operandCount(self: *const BrBlockFlat) usize { + _ = self; return 0; } pub fn getOperand(self: *const BrBlockFlat, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; @@ -427,9 +441,11 @@ pub const Inst = struct { operand: *Inst, pub fn operandCount(self: *const Br) usize { + _ = self; return 1; } pub fn getOperand(self: *const Br, index: usize) ?*Inst { + _ = self; if (index == 0) return self.operand; return null; @@ -443,9 +459,12 @@ pub const Inst = struct { block: *Block, pub fn operandCount(self: *const BrVoid) usize { + _ = self; return 0; } pub fn getOperand(self: *const BrVoid, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; @@ -490,6 +509,7 @@ pub const Inst = struct { else_death_count: u32 = 0, pub fn operandCount(self: *const CondBr) usize { + _ = self; return 1; } pub fn getOperand(self: *const CondBr, index: usize) ?*Inst { @@ -516,9 +536,12 @@ pub const Inst = struct { val: Value, pub fn operandCount(self: *const Constant) usize { + _ = self; return 0; } pub fn getOperand(self: *const Constant, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; @@ -530,9 +553,12 @@ pub const Inst = struct { body: Body, pub fn operandCount(self: *const Loop) usize { + _ = self; return 0; } pub fn getOperand(self: *const Loop, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; @@ -544,9 +570,12 @@ pub const Inst = struct { variable: *Module.Var, pub fn operandCount(self: *const VarPtr) usize { + _ = self; return 0; } pub fn getOperand(self: *const VarPtr, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; @@ -559,9 +588,12 @@ pub const Inst = struct { field_index: usize, pub fn operandCount(self: *const StructFieldPtr) usize { + _ = self; return 1; } pub fn getOperand(self: *const StructFieldPtr, index: usize) ?*Inst { + _ = self; + _ = index; var i = index; if (i < 1) @@ -593,6 +625,7 @@ pub const Inst = struct { }; pub fn operandCount(self: *const SwitchBr) usize { + _ = self; return 1; } pub fn getOperand(self: *const SwitchBr, index: usize) ?*Inst { @@ -621,9 +654,12 @@ pub const Inst = struct { column: u32, pub fn operandCount(self: *const DbgStmt) usize { + _ = self; return 0; } pub fn getOperand(self: *const DbgStmt, index: usize) ?*Inst { + _ = self; + _ = index; return null; } }; diff --git a/src/codegen.zig b/src/codegen.zig index 2b3c10b762..0b63222242 100644 --- a/src/codegen.zig +++ b/src/codegen.zig @@ -118,7 +118,6 @@ pub fn generateSymbol( if (typed_value.ty.sentinel()) |sentinel| { try code.ensureCapacity(code.items.len + payload.data.len + 1); code.appendSliceAssumeCapacity(payload.data); - const prev_len = code.items.len; switch (try generateSymbol(bin_file, src_loc, .{ .ty = typed_value.ty.elemType(), .val = sentinel, @@ -565,7 +564,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { .r11 = true, // fp .r14 = true, // lr }; - inline for (callee_preserved_regs) |reg, i| { + inline for (callee_preserved_regs) |reg| { if (self.register_manager.isRegAllocated(reg)) { @field(saved_regs, @tagName(reg)) = true; } @@ -603,7 +602,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { } else { if (math.cast(i26, amt)) |offset| { writeInt(u32, self.code.items[jmp_reloc..][0..4], Instruction.b(.al, offset).toU32()); - } else |err| { + } else |_| { return self.failSymbol("exitlude jump is too large", .{}); } } @@ -676,7 +675,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { } else { if (math.cast(i28, amt)) |offset| { writeInt(u32, self.code.items[jmp_reloc..][0..4], Instruction.b(offset).toU32()); - } else |err| { + } else |_| { return self.failSymbol("exitlude jump is too large", .{}); } } @@ -1498,6 +1497,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { swap_lhs_and_rhs: bool, op: ir.Inst.Tag, ) !void { + _ = src; assert(lhs_mcv == .register or rhs_mcv == .register); const op1 = if (swap_lhs_and_rhs) rhs_mcv.register else lhs_mcv.register; @@ -1906,6 +1906,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { try self.genX8664ModRMRegToStack(src, dst_ty, off, src_reg, mr + 0x1); }, .immediate => |imm| { + _ = imm; return self.fail(src, "TODO implement x86 ADD/SUB/CMP source immediate", .{}); }, .embedded_in_code, .memory, .stack_offset => { @@ -2055,6 +2056,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { return self.genSetStack(src, dst_ty, off, MCValue{ .register = dst_reg }); }, .immediate => |imm| { + _ = imm; return self.fail(src, "TODO implement x86 multiply source immediate", .{}); }, .embedded_in_code, .memory, .stack_offset => { @@ -2983,14 +2985,14 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { .arm, .armeb => { if (math.cast(i26, @intCast(i32, index) - @intCast(i32, self.code.items.len + 8))) |delta| { writeInt(u32, try self.code.addManyAsArray(4), Instruction.b(.al, delta).toU32()); - } else |err| { + } else |_| { return self.fail(src, "TODO: enable larger branch offset", .{}); } }, .aarch64, .aarch64_be, .aarch64_32 => { if (math.cast(i28, @intCast(i32, index) - @intCast(i32, self.code.items.len + 8))) |delta| { writeInt(u32, try self.code.addManyAsArray(4), Instruction.b(delta).toU32()); - } else |err| { + } else |_| { return self.fail(src, "TODO: enable larger branch offset", .{}); } }, @@ -3308,9 +3310,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { } }, .compare_flags_unsigned => |op| { + _ = op; return self.fail(src, "TODO implement set stack variable with compare flags value (unsigned)", .{}); }, .compare_flags_signed => |op| { + _ = op; return self.fail(src, "TODO implement set stack variable with compare flags value (signed)", .{}); }, .immediate => { @@ -3318,6 +3322,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { return self.genSetStack(src, ty, stack_offset, MCValue{ .register = reg }); }, .embedded_in_code => |code_offset| { + _ = code_offset; return self.fail(src, "TODO implement set stack variable from embedded_in_code", .{}); }, .register => |reg| { @@ -3354,6 +3359,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { } }, .memory => |vaddr| { + _ = vaddr; return self.fail(src, "TODO implement set stack variable from memory vaddr", .{}); }, .stack_offset => |off| { @@ -3382,9 +3388,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { } }, .compare_flags_unsigned => |op| { + _ = op; return self.fail(src, "TODO implement set stack variable with compare flags value (unsigned)", .{}); }, .compare_flags_signed => |op| { + _ = op; return self.fail(src, "TODO implement set stack variable with compare flags value (signed)", .{}); }, .immediate => |x_big| { @@ -3437,12 +3445,14 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { } }, .embedded_in_code => |code_offset| { + _ = code_offset; return self.fail(src, "TODO implement set stack variable from embedded_in_code", .{}); }, .register => |reg| { try self.genX8664ModRMRegToStack(src, ty, stack_offset, reg, 0x89); }, .memory => |vaddr| { + _ = vaddr; return self.fail(src, "TODO implement set stack variable from memory vaddr", .{}); }, .stack_offset => |off| { @@ -3471,9 +3481,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { } }, .compare_flags_unsigned => |op| { + _ = op; return self.fail(src, "TODO implement set stack variable with compare flags value (unsigned)", .{}); }, .compare_flags_signed => |op| { + _ = op; return self.fail(src, "TODO implement set stack variable with compare flags value (signed)", .{}); }, .immediate => { @@ -3481,6 +3493,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { return self.genSetStack(src, ty, stack_offset, MCValue{ .register = reg }); }, .embedded_in_code => |code_offset| { + _ = code_offset; return self.fail(src, "TODO implement set stack variable from embedded_in_code", .{}); }, .register => |reg| { @@ -3513,6 +3526,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { } }, .memory => |vaddr| { + _ = vaddr; return self.fail(src, "TODO implement set stack variable from memory vaddr", .{}); }, .stack_offset => |off| { @@ -3843,6 +3857,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { ); }, .compare_flags_signed => |op| { + _ = op; return self.fail(src, "TODO set register with compare flags value (signed)", .{}); }, .immediate => |x| { @@ -4461,6 +4476,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { dummy, pub fn allocIndex(self: Register) ?u4 { + _ = self; return null; } }; diff --git a/src/codegen/arm.zig b/src/codegen/arm.zig index cc6abe2e52..891a9e100b 100644 --- a/src/codegen/arm.zig +++ b/src/codegen/arm.zig @@ -674,7 +674,7 @@ pub const Instruction = union(enum) { }; const imm4h: u4 = switch (offset) { .immediate => |imm| @truncate(u4, imm >> 4), - .register => |reg| 0b0000, + .register => 0b0000, }; return Instruction{ diff --git a/src/codegen/c.zig b/src/codegen/c.zig index 7ebecb45c9..ae439693b8 100644 --- a/src/codegen/c.zig +++ b/src/codegen/c.zig @@ -47,6 +47,8 @@ fn formatTypeAsCIdentifier( options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = fmt; + _ = options; var buffer = [1]u8{0} ** 128; // We don't care if it gets cut off, it's still more unique than a number var buf = std.fmt.bufPrint(&buffer, "{}", .{data}) catch &buffer; @@ -63,6 +65,8 @@ fn formatIdent( options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = fmt; + _ = options; for (ident) |c, i| { switch (c) { 'a'...'z', 'A'...'Z', '_' => try writer.writeByte(c), @@ -747,6 +751,7 @@ pub fn genBody(o: *Object, body: ir.Body) error{ AnalysisFail, OutOfMemory }!voi } fn genVarPtr(o: *Object, inst: *Inst.VarPtr) !CValue { + _ = o; return CValue{ .decl_ref = inst.variable.owner_decl }; } @@ -937,6 +942,8 @@ fn genCall(o: *Object, inst: *Inst.Call) !CValue { } fn genDbgStmt(o: *Object, inst: *Inst.DbgStmt) !CValue { + _ = o; + _ = inst; // TODO emit #line directive here with line number and filename return CValue.none; } @@ -1016,11 +1023,13 @@ fn genBitcast(o: *Object, inst: *Inst.UnOp) !CValue { } fn genBreakpoint(o: *Object, inst: *Inst.NoOp) !CValue { + _ = inst; try o.writer().writeAll("zig_breakpoint();\n"); return CValue.none; } fn genUnreach(o: *Object, inst: *Inst.NoOp) !CValue { + _ = inst; try o.writer().writeAll("zig_unreachable();\n"); return CValue.none; } @@ -1107,7 +1116,6 @@ fn genAsm(o: *Object, as: *Inst.Assembly) !CValue { for (as.inputs) |i, index| { if (i[0] == '{' and i[i.len - 1] == '}') { const reg = i[1 .. i.len - 1]; - const arg = as.args[index]; if (index > 0) { try writer.writeAll(", "); } diff --git a/src/codegen/llvm.zig b/src/codegen/llvm.zig index 4e4621ca29..2baedf8c9d 100644 --- a/src/codegen/llvm.zig +++ b/src/codegen/llvm.zig @@ -154,6 +154,7 @@ pub const Object = struct { object_pathZ: [:0]const u8, pub fn create(allocator: *Allocator, sub_path: []const u8, options: link.Options) !*Object { + _ = sub_path; const self = try allocator.create(Object); errdefer allocator.destroy(self); @@ -742,6 +743,7 @@ pub const FuncGen = struct { } fn genRetVoid(self: *FuncGen, inst: *Inst.NoOp) ?*const llvm.Value { + _ = inst; _ = self.builder.buildRetVoid(); return null; } @@ -873,6 +875,7 @@ pub const FuncGen = struct { } fn genUnreach(self: *FuncGen, inst: *Inst.NoOp) ?*const llvm.Value { + _ = inst; _ = self.builder.buildUnreachable(); return null; } @@ -1013,6 +1016,7 @@ pub const FuncGen = struct { } fn genBreakpoint(self: *FuncGen, inst: *Inst.NoOp) !?*const llvm.Value { + _ = inst; const llvn_fn = self.getIntrinsic("llvm.debugtrap"); _ = self.builder.buildCall(llvn_fn, null, 0, ""); return null; diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 3bff09bd8d..9e0cd19f6f 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -714,7 +714,6 @@ pub const DeclGen = struct { return self.fail(inst.base.src, "TODO: SPIR-V backend: binary operations for strange integers", .{}); } - const is_bool = info.class == .bool; const is_float = info.class == .float; const is_signed = info.signedness == .signed; // **Note**: All these operations must be valid for vectors as well! @@ -802,8 +801,6 @@ pub const DeclGen = struct { const result_id = self.spv.allocResultId(); const result_type_id = try self.genType(inst.base.src, inst.base.ty); - const info = try self.arithmeticTypeInfo(inst.operand.ty); - const opcode = switch (inst.base.tag) { // Bool -> bool .not => Opcode.OpLogicalNot, @@ -867,6 +864,7 @@ pub const DeclGen = struct { // are not allowed to be created from a phi node, and throw an error for those. For now, genType already throws // an error for pointers. const result_type_id = try self.genType(inst.base.src, inst.base.ty); + _ = result_type_id; try writeOpcode(&self.code, .OpPhi, 2 + @intCast(u16, incoming_blocks.items.len * 2)); // result type + result + variable/parent... diff --git a/src/codegen/wasm.zig b/src/codegen/wasm.zig index d7fe239d3b..ec4ec66b1e 100644 --- a/src/codegen/wasm.zig +++ b/src/codegen/wasm.zig @@ -702,7 +702,7 @@ pub const Context = struct { try writer.writeByte(wasm.valtype(.i32)); // error code is always an i32 integer. try writer.writeByte(val_type); }, - else => |ret_type| { + else => { try leb.writeULEB128(writer, @as(u32, 1)); // Can we maybe get the source index of the return type? const val_type = try self.genValtype(.{ .node_offset = 0 }, return_type); @@ -721,7 +721,7 @@ pub const Context = struct { // TODO: check for and handle death of instructions const mod_fn = blk: { if (typed_value.val.castTag(.function)) |func| break :blk func.data; - if (typed_value.val.castTag(.extern_fn)) |ext_fn| return Result.appended; // don't need code body for extern functions + if (typed_value.val.castTag(.extern_fn)) |_| return Result.appended; // don't need code body for extern functions unreachable; }; @@ -849,7 +849,6 @@ pub const Context = struct { } fn genCall(self: *Context, inst: *Inst.Call) InnerError!WValue { - const func_inst = inst.func.castTag(.constant).?; const func_val = inst.func.value().?; const target: *Decl = blk: { @@ -914,7 +913,7 @@ pub const Context = struct { .local => |local| { try self.emitWValue(rhs); try writer.writeByte(wasm.opcode(.local_set)); - try leb.writeULEB128(writer, lhs.local); + try leb.writeULEB128(writer, local); }, else => unreachable, } @@ -926,6 +925,7 @@ pub const Context = struct { } fn genArg(self: *Context, inst: *Inst.Arg) InnerError!WValue { + _ = inst; // arguments share the index with locals defer self.local_index += 1; return WValue{ .local = self.local_index }; @@ -1146,8 +1146,6 @@ pub const Context = struct { } fn genCmp(self: *Context, inst: *Inst.BinOp, op: std.math.CompareOperator) InnerError!WValue { - const ty = inst.lhs.ty.tag(); - // save offset, so potential conditions can insert blocks in front of // the comparison that we can later jump back to const offset = self.code.items.len; @@ -1216,12 +1214,15 @@ pub const Context = struct { } fn genBreakpoint(self: *Context, breakpoint: *Inst.NoOp) InnerError!WValue { + _ = self; + _ = breakpoint; // unsupported by wasm itself. Can be implemented once we support DWARF // for wasm return .none; } fn genUnreachable(self: *Context, unreach: *Inst.NoOp) InnerError!WValue { + _ = unreach; try self.code.append(wasm.opcode(.@"unreachable")); return .none; } diff --git a/src/glibc.zig b/src/glibc.zig index 30bc021ced..c0afc321c9 100644 --- a/src/glibc.zig +++ b/src/glibc.zig @@ -497,7 +497,6 @@ fn add_include_dirs(comp: *Compilation, arena: *Allocator, args: *std.ArrayList( const target = comp.getTarget(); const arch = target.cpu.arch; const opt_nptl: ?[]const u8 = if (target.os.tag == .linux) "nptl" else "htl"; - const glibc = try lib_path(comp, arena, lib_libc ++ "glibc"); const s = path.sep_str; diff --git a/src/link.zig b/src/link.zig index d1508c29cd..bae468d075 100644 --- a/src/link.zig +++ b/src/link.zig @@ -517,7 +517,7 @@ pub const File = struct { .target = base.options.target, .output_mode = .Obj, }); - const o_directory = base.options.module.?.zig_cache_artifact_directory; + const o_directory = module.zig_cache_artifact_directory; const full_obj_path = try o_directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } diff --git a/src/link/C.zig b/src/link/C.zig index 6cb219db41..1793b95210 100644 --- a/src/link/C.zig +++ b/src/link/C.zig @@ -76,7 +76,10 @@ pub fn deinit(self: *C) void { self.decl_table.deinit(self.base.allocator); } -pub fn allocateDeclIndexes(self: *C, decl: *Module.Decl) !void {} +pub fn allocateDeclIndexes(self: *C, decl: *Module.Decl) !void { + _ = self; + _ = decl; +} pub fn freeDecl(self: *C, decl: *Module.Decl) void { _ = self.decl_table.swapRemove(decl); @@ -307,4 +310,9 @@ pub fn updateDeclExports( module: *Module, decl: *Module.Decl, exports: []const *Module.Export, -) !void {} +) !void { + _ = exports; + _ = decl; + _ = module; + _ = self; +} diff --git a/src/link/Coff.zig b/src/link/Coff.zig index 9ab1c6d78a..b466cf9136 100644 --- a/src/link/Coff.zig +++ b/src/link/Coff.zig @@ -831,7 +831,7 @@ fn linkWithLLD(self: *Coff, comp: *Compilation) !void { .target = self.base.options.target, .output_mode = .Obj, }); - const o_directory = self.base.options.module.?.zig_cache_artifact_directory; + const o_directory = module.zig_cache_artifact_directory; const full_obj_path = try o_directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } @@ -1340,6 +1340,9 @@ pub fn getDeclVAddr(self: *Coff, decl: *const Module.Decl) u64 { } pub fn updateDeclLineNumber(self: *Coff, module: *Module, decl: *Module.Decl) !void { + _ = self; + _ = module; + _ = decl; // TODO Implement this } diff --git a/src/link/Elf.zig b/src/link/Elf.zig index 84068ffeca..e2e48b9871 100644 --- a/src/link/Elf.zig +++ b/src/link/Elf.zig @@ -1262,7 +1262,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation) !void { .target = self.base.options.target, .output_mode = .Obj, }); - const o_directory = self.base.options.module.?.zig_cache_artifact_directory; + const o_directory = module.zig_cache_artifact_directory; const full_obj_path = try o_directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } @@ -1938,6 +1938,9 @@ fn freeTextBlock(self: *Elf, text_block: *TextBlock) void { } fn shrinkTextBlock(self: *Elf, text_block: *TextBlock, new_block_size: u64) void { + _ = self; + _ = text_block; + _ = new_block_size; // TODO check the new capacity, and if it crosses the size threshold into a big enough // capacity, insert a free list node for it. } @@ -2706,6 +2709,7 @@ pub fn updateDeclExports( /// Must be called only after a successful call to `updateDecl`. pub fn updateDeclLineNumber(self: *Elf, module: *Module, decl: *const Module.Decl) !void { + _ = module; const tracy = trace(@src()); defer tracy.end(); @@ -2979,6 +2983,7 @@ fn dbgLineNeededHeaderBytes(self: Elf) u32 { } fn dbgInfoNeededHeaderBytes(self: Elf) u32 { + _ = self; return 120; } @@ -3372,7 +3377,7 @@ const CsuObjects = struct { if (result.crtend) |*obj| obj.* = try fs.path.join(arena, &[_][]const u8{ gcc_dir_path, obj.* }); }, else => { - inline for (std.meta.fields(@TypeOf(result))) |f, i| { + inline for (std.meta.fields(@TypeOf(result))) |f| { if (@field(result, f.name)) |*obj| { obj.* = try fs.path.join(arena, &[_][]const u8{ crt_dir_path, obj.* }); } @@ -3380,7 +3385,7 @@ const CsuObjects = struct { }, } } else { - inline for (std.meta.fields(@TypeOf(result))) |f, i| { + inline for (std.meta.fields(@TypeOf(result))) |f| { if (@field(result, f.name)) |*obj| { if (comp.crt_files.get(obj.*)) |crtf| { obj.* = crtf.full_object_path; diff --git a/src/link/MachO.zig b/src/link/MachO.zig index 8c1d092f12..6e1996f9ff 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -441,6 +441,7 @@ pub fn flush(self: *MachO, comp: *Compilation) !void { } pub fn flushModule(self: *MachO, comp: *Compilation) !void { + _ = comp; const tracy = trace(@src()); defer tracy.end(); @@ -533,7 +534,7 @@ fn linkWithLLD(self: *MachO, comp: *Compilation) !void { .target = self.base.options.target, .output_mode = .Obj, }); - const o_directory = self.base.options.module.?.zig_cache_artifact_directory; + const o_directory = module.zig_cache_artifact_directory; const full_obj_path = try o_directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } @@ -1254,6 +1255,9 @@ fn freeTextBlock(self: *MachO, text_block: *TextBlock) void { } fn shrinkTextBlock(self: *MachO, text_block: *TextBlock, new_block_size: u64) void { + _ = self; + _ = text_block; + _ = new_block_size; // TODO check the new capacity, and if it crosses the size threshold into a big enough // capacity, insert a free list node for it. } @@ -2918,7 +2922,6 @@ fn relocateSymbolTable(self: *MachO) !void { const nsyms = nlocals + nglobals + nundefs; if (symtab.nsyms < nsyms) { - const linkedit_segment = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment; const needed_size = nsyms * @sizeOf(macho.nlist_64); if (needed_size > self.allocatedSizeLinkedit(symtab.symoff)) { // Move the entire symbol table to a new location @@ -3150,7 +3153,6 @@ fn writeExportTrie(self: *MachO) !void { const nwritten = try trie.write(stream.writer()); assert(nwritten == trie.size); - const linkedit_segment = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment; const dyld_info = &self.load_commands.items[self.dyld_info_cmd_index.?].DyldInfoOnly; const allocated_size = self.allocatedSizeLinkedit(dyld_info.export_off); const needed_size = mem.alignForwardGeneric(u64, buffer.len, @alignOf(u64)); @@ -3357,7 +3359,6 @@ fn populateLazyBindOffsetsInStubHelper(self: *MachO, buffer: []const u8) !void { error.EndOfStream => break, else => return err, }; - const imm: u8 = inst & macho.BIND_IMMEDIATE_MASK; const opcode: u8 = inst & macho.BIND_OPCODE_MASK; switch (opcode) { diff --git a/src/link/MachO/DebugSymbols.zig b/src/link/MachO/DebugSymbols.zig index ca6e5157b3..2b10f3307b 100644 --- a/src/link/MachO/DebugSymbols.zig +++ b/src/link/MachO/DebugSymbols.zig @@ -500,7 +500,6 @@ pub fn flushModule(self: *DebugSymbols, allocator: *Allocator, options: link.Opt if (self.debug_aranges_section_dirty) { const dwarf_segment = &self.load_commands.items[self.dwarf_segment_cmd_index.?].Segment; const debug_aranges_sect = &dwarf_segment.sections.items[self.debug_aranges_section_index.?]; - const debug_info_sect = dwarf_segment.sections.items[self.debug_info_section_index.?]; var di_buf = std.ArrayList(u8).init(allocator); defer di_buf.deinit(); @@ -844,7 +843,6 @@ fn relocateSymbolTable(self: *DebugSymbols) !void { const nsyms = nlocals + nglobals; if (symtab.nsyms < nsyms) { - const linkedit_segment = self.load_commands.items[self.linkedit_segment_cmd_index.?].Segment; const needed_size = nsyms * @sizeOf(macho.nlist_64); if (needed_size > self.allocatedSizeLinkedit(symtab.symoff)) { // Move the entire symbol table to a new location @@ -901,14 +899,10 @@ fn writeStringTable(self: *DebugSymbols) !void { } pub fn updateDeclLineNumber(self: *DebugSymbols, module: *Module, decl: *const Module.Decl) !void { + _ = module; const tracy = trace(@src()); defer tracy.end(); - const tree = decl.namespace.file_scope.tree; - const node_tags = tree.nodes.items(.tag); - const node_datas = tree.nodes.items(.data); - const token_starts = tree.tokens.items(.start); - const func = decl.val.castTag(.function).?.data; const line_off = @intCast(u28, decl.src_line + func.lbrace_line); @@ -933,6 +927,8 @@ pub fn initDeclDebugBuffers( module: *Module, decl: *Module.Decl, ) !DeclDebugBuffers { + _ = self; + _ = module; const tracy = trace(@src()); defer tracy.end(); @@ -1195,6 +1191,7 @@ fn addDbgInfoType( dbg_info_buffer: *std.ArrayList(u8), target: std.Target, ) !void { + _ = self; switch (ty.zigTypeTag()) { .Void => unreachable, .NoReturn => unreachable, @@ -1371,6 +1368,7 @@ fn getRelocDbgInfoSubprogramHighPC() u32 { } fn dbgLineNeededHeaderBytes(self: DebugSymbols, module: *Module) u32 { + _ = self; const directory_entry_format_count = 1; const file_name_entry_format_count = 1; const directory_count = 1; @@ -1385,6 +1383,7 @@ fn dbgLineNeededHeaderBytes(self: DebugSymbols, module: *Module) u32 { } fn dbgInfoNeededHeaderBytes(self: DebugSymbols) u32 { + _ = self; return 120; } diff --git a/src/link/MachO/Object.zig b/src/link/MachO/Object.zig index c4a044b446..f9c33bfa5c 100644 --- a/src/link/MachO/Object.zig +++ b/src/link/MachO/Object.zig @@ -478,7 +478,6 @@ pub fn parseDebugInfo(self: *Object) !void { self.tu_path = try std.fs.path.join(self.allocator, &[_][]const u8{ comp_dir, name }); self.tu_mtime = mtime: { - var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined; const stat = try self.file.?.stat(); break :mtime @intCast(u64, @divFloor(stat.mtime, 1_000_000_000)); }; diff --git a/src/link/MachO/Zld.zig b/src/link/MachO/Zld.zig index 2c8b77d983..9d9a1315bb 100644 --- a/src/link/MachO/Zld.zig +++ b/src/link/MachO/Zld.zig @@ -108,6 +108,7 @@ const TlvOffset = struct { offset: u64, fn cmp(context: void, a: TlvOffset, b: TlvOffset) bool { + _ = context; return a.source_addr < b.source_addr; } }; @@ -432,13 +433,12 @@ fn mapAndUpdateSections( fn updateMetadata(self: *Zld) !void { for (self.objects.items) |object| { - const object_seg = object.load_commands.items[object.segment_cmd_index.?].Segment; const text_seg = &self.load_commands.items[self.text_segment_cmd_index.?].Segment; const data_const_seg = &self.load_commands.items[self.data_const_segment_cmd_index.?].Segment; const data_seg = &self.load_commands.items[self.data_segment_cmd_index.?].Segment; // Create missing metadata - for (object.sections.items) |sect, sect_id| { + for (object.sections.items) |sect| { const segname = sect.segname(); const sectname = sect.sectname(); @@ -1294,7 +1294,6 @@ fn allocateLinkeditSegment(self: *Zld) void { } fn allocateSegment(self: *Zld, index: u16, offset: u64) !void { - const base_vmaddr = self.load_commands.items[self.pagezero_segment_cmd_index.?].Segment.inner.vmsize; const seg = &self.load_commands.items[index].Segment; // Allocate the sections according to their alignment at the beginning of the segment. @@ -1375,7 +1374,7 @@ fn allocateTentativeSymbols(self: *Zld) !void { } // Convert tentative definitions into regular symbols. - for (self.tentatives.values()) |sym, i| { + for (self.tentatives.values()) |sym| { const tent = sym.cast(Symbol.Tentative) orelse unreachable; const reg = try self.allocator.create(Symbol.Regular); errdefer self.allocator.destroy(reg); @@ -1427,7 +1426,6 @@ fn writeStubHelperCommon(self: *Zld) !void { const got = &data_const_segment.sections.items[self.got_section_index.?]; const data_segment = &self.load_commands.items[self.data_segment_cmd_index.?].Segment; const data = &data_segment.sections.items[self.data_section_index.?]; - const la_symbol_ptr = data_segment.sections.items[self.la_symbol_ptr_section_index.?]; self.stub_helper_stubs_start_off = blk: { switch (self.arch.?) { @@ -1761,7 +1759,7 @@ fn resolveSymbolsInObject(self: *Zld, object: *Object) !void { t_sym.alias = sym; sym_ptr.* = sym; - } else if (sym.cast(Symbol.Unresolved)) |und| { + } else if (sym.cast(Symbol.Unresolved)) |_| { if (self.globals.get(sym.name)) |g_sym| { sym.alias = g_sym; continue; @@ -2654,7 +2652,6 @@ fn setEntryPoint(self: *Zld) !void { // TODO we should respect the -entry flag passed in by the user to set a custom // entrypoint. For now, assume default of `_main`. const seg = self.load_commands.items[self.text_segment_cmd_index.?].Segment; - const text = seg.sections.items[self.text_section_index.?]; const sym = self.globals.get("_main") orelse return error.MissingMainEntrypoint; const entry_sym = sym.cast(Symbol.Regular) orelse unreachable; const ec = &self.load_commands.items[self.main_cmd_index.?].Main; @@ -2862,7 +2859,6 @@ fn populateLazyBindOffsetsInStubHelper(self: *Zld, buffer: []const u8) !void { error.EndOfStream => break, else => return err, }; - const imm: u8 = inst & macho.BIND_IMMEDIATE_MASK; const opcode: u8 = inst & macho.BIND_OPCODE_MASK; switch (opcode) { @@ -2959,6 +2955,7 @@ fn writeDebugInfo(self: *Zld) !void { for (self.objects.items) |object| { const tu_path = object.tu_path orelse continue; const tu_mtime = object.tu_mtime orelse continue; + _ = tu_mtime; const dirname = std.fs.path.dirname(tu_path) orelse "./"; // Current dir try stabs.append(.{ diff --git a/src/link/MachO/bind.zig b/src/link/MachO/bind.zig index d234fa8242..402e74d776 100644 --- a/src/link/MachO/bind.zig +++ b/src/link/MachO/bind.zig @@ -10,6 +10,7 @@ pub const Pointer = struct { }; pub fn pointerCmp(context: void, a: Pointer, b: Pointer) bool { + _ = context; if (a.segment_id < b.segment_id) return true; if (a.segment_id == b.segment_id) { return a.offset < b.offset; diff --git a/src/link/MachO/reloc/x86_64.zig b/src/link/MachO/reloc/x86_64.zig index 2a457fdea2..6df68b6b3e 100644 --- a/src/link/MachO/reloc/x86_64.zig +++ b/src/link/MachO/reloc/x86_64.zig @@ -175,7 +175,6 @@ pub const Parser = struct { const rel_type = @intToEnum(macho.reloc_type_x86_64, rel.r_type); const target = Relocation.Target.from_reloc(rel, parser.symbols); - const is_extern = rel.r_extern == 1; const offset = @intCast(u32, rel.r_address); const inst = parser.code[offset..][0..4]; diff --git a/src/link/SpirV.zig b/src/link/SpirV.zig index 9d64245bbb..bfae799462 100644 --- a/src/link/SpirV.zig +++ b/src/link/SpirV.zig @@ -102,6 +102,7 @@ pub fn deinit(self: *SpirV) void { } pub fn updateDecl(self: *SpirV, module: *Module, decl: *Module.Decl) !void { + _ = module; // Keep track of all decls so we can iterate over them on flush(). _ = try self.decl_table.getOrPut(self.base.allocator, decl); } @@ -111,7 +112,12 @@ pub fn updateDeclExports( module: *Module, decl: *const Module.Decl, exports: []const *Module.Export, -) !void {} +) !void { + _ = self; + _ = module; + _ = decl; + _ = exports; +} pub fn freeDecl(self: *SpirV, decl: *Module.Decl) void { assert(self.decl_table.swapRemove(decl)); diff --git a/src/link/Wasm.zig b/src/link/Wasm.zig index 3fcdc04e71..6d38939a88 100644 --- a/src/link/Wasm.zig +++ b/src/link/Wasm.zig @@ -216,7 +216,7 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void { try module.failed_decls.put(module.gpa, decl, context.err_msg); return; }, - else => |e| return err, + else => |e| return e, }; const code: []const u8 = switch (result) { @@ -258,7 +258,12 @@ pub fn updateDeclExports( module: *Module, decl: *const Module.Decl, exports: []const *Module.Export, -) !void {} +) !void { + _ = self; + _ = module; + _ = decl; + _ = exports; +} pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void { if (self.getFuncidx(decl)) |func_idx| { @@ -300,6 +305,7 @@ pub fn flush(self: *Wasm, comp: *Compilation) !void { } pub fn flushModule(self: *Wasm, comp: *Compilation) !void { + _ = comp; const tracy = trace(@src()); defer tracy.end(); @@ -496,7 +502,6 @@ pub fn flushModule(self: *Wasm, comp: *Compilation) !void { if (data_size != 0) { const header_offset = try reserveVecSectionHeader(file); const writer = file.writer(); - var len: u32 = 0; // index to memory section (currently, there can only be 1 memory section in wasm) try leb.writeULEB128(writer, @as(u32, 0)); @@ -558,7 +563,7 @@ fn linkWithLLD(self: *Wasm, comp: *Compilation) !void { .target = self.base.options.target, .output_mode = .Obj, }); - const o_directory = self.base.options.module.?.zig_cache_artifact_directory; + const o_directory = module.zig_cache_artifact_directory; const full_obj_path = try o_directory.join(arena, &[_][]const u8{obj_basename}); break :blk full_obj_path; } diff --git a/src/main.zig b/src/main.zig index 83548dc327..f2d00c47bb 100644 --- a/src/main.zig +++ b/src/main.zig @@ -500,7 +500,7 @@ const Emit = union(enum) { }; fn optionalBoolEnvVar(arena: *Allocator, name: []const u8) !bool { - if (std.process.getEnvVarOwned(arena, name)) |value| { + if (std.process.getEnvVarOwned(arena, name)) |_| { return true; } else |err| switch (err) { error.EnvironmentVariableNotFound => return false, @@ -2565,6 +2565,7 @@ pub fn cmdInit( args: []const []const u8, output_mode: std.builtin.OutputMode, ) !void { + _ = gpa; { var i: usize = 0; while (i < args.len) : (i += 1) { @@ -3749,7 +3750,6 @@ pub fn cmdAstCheck( var color: Color = .auto; var want_output_text = false; - var have_zig_source_file = false; var zig_source_file: ?[]const u8 = null; var i: usize = 0; diff --git a/src/mingw.zig b/src/mingw.zig index ca887dd940..42d1ac47db 100644 --- a/src/mingw.zig +++ b/src/mingw.zig @@ -372,11 +372,9 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void { try child.spawn(); - const stdout_reader = child.stdout.?.reader(); const stderr_reader = child.stderr.?.reader(); // TODO https://github.com/ziglang/zig/issues/6343 - const stdout = try stdout_reader.readAllAlloc(arena, std.math.maxInt(u32)); const stderr = try stderr_reader.readAllAlloc(arena, 10 * 1024 * 1024); const term = child.wait() catch |err| { diff --git a/src/musl.zig b/src/musl.zig index 4f641a4c7c..fcdc503ccc 100644 --- a/src/musl.zig +++ b/src/musl.zig @@ -143,7 +143,6 @@ pub fn buildCRTFile(comp: *Compilation, crt_file: CRTFile) !void { const dirname = path.dirname(src_file).?; const basename = path.basename(src_file); const noextbasename = basename[0 .. basename.len - std.fs.path.extension(basename).len]; - const before_arch_dir = path.dirname(dirname).?; const dirbasename = path.basename(dirname); var is_arch_specific = false; diff --git a/src/print_env.zig b/src/print_env.zig index d62e1f62fd..8c44e85e65 100644 --- a/src/print_env.zig +++ b/src/print_env.zig @@ -5,6 +5,7 @@ const Allocator = std.mem.Allocator; const fatal = @import("main.zig").fatal; pub fn cmdEnv(gpa: *Allocator, args: []const []const u8, stdout: std.fs.File.Writer) !void { + _ = args; const self_exe_path = try std.fs.selfExePathAlloc(gpa); defer gpa.free(self_exe_path); diff --git a/src/print_targets.zig b/src/print_targets.zig index e24a2294a1..d0a1d5167a 100644 --- a/src/print_targets.zig +++ b/src/print_targets.zig @@ -17,6 +17,7 @@ pub fn cmdTargets( stdout: anytype, native_target: Target, ) !void { + _ = args; var zig_lib_directory = introspect.findZigLibDir(allocator) catch |err| { fatal("unable to find zig installation directory: {s}\n", .{@errorName(err)}); }; diff --git a/src/register_manager.zig b/src/register_manager.zig index 9f47526f13..96cf4f17b7 100644 --- a/src/register_manager.zig +++ b/src/register_manager.zig @@ -265,6 +265,8 @@ fn MockFunction(comptime Register: type) type { } pub fn spillInstruction(self: *Self, src: LazySrcLoc, reg: Register, inst: *ir.Inst) !void { + _ = src; + _ = inst; try self.spilled.append(self.allocator, reg); } }; @@ -281,12 +283,6 @@ test "default state" { }; defer function.deinit(); - var mock_instruction = ir.Inst{ - .tag = .breakpoint, - .ty = Type.initTag(.void), - .src = .unneeded, - }; - try expect(!function.register_manager.isRegAllocated(.r2)); try expect(!function.register_manager.isRegAllocated(.r3)); try expect(function.register_manager.isRegFree(.r2)); @@ -365,12 +361,6 @@ test "tryAllocRegs" { }; defer function.deinit(); - var mock_instruction = ir.Inst{ - .tag = .breakpoint, - .ty = Type.initTag(.void), - .src = .unneeded, - }; - try expectEqual([_]MockRegister2{ .r0, .r1, .r2 }, function.register_manager.tryAllocRegs(3, .{ null, null, null }, &.{}).?); // Exceptions diff --git a/src/stage1.zig b/src/stage1.zig index 91e7cd8bed..46d70ea335 100644 --- a/src/stage1.zig +++ b/src/stage1.zig @@ -407,6 +407,8 @@ export fn stage2_add_link_lib( symbol_name_ptr: [*c]const u8, symbol_name_len: usize, ) ?[*:0]const u8 { + _ = symbol_name_len; + _ = symbol_name_ptr; const comp = @intToPtr(*Compilation, stage1.userdata); const lib_name = std.ascii.allocLowerString(comp.gpa, lib_name_ptr[0..lib_name_len]) catch return "out of memory"; const target = comp.getTarget(); diff --git a/src/test.zig b/src/test.zig index a7f11d93df..1d2a552662 100644 --- a/src/test.zig +++ b/src/test.zig @@ -70,6 +70,8 @@ const ErrorMsg = union(enum) { options: std.fmt.FormatOptions, writer: anytype, ) !void { + _ = fmt; + _ = options; switch (self) { .src => |src| { return writer.print("{s}:{d}:{d}: {s}: {s}", .{ @@ -592,6 +594,7 @@ pub const TestContext = struct { thread_pool: *ThreadPool, global_cache_directory: Compilation.Directory, ) !void { + _ = self; const target_info = try std.zig.system.NativeTargetInfo.detect(allocator, case.target); const target = target_info.target; diff --git a/src/tracy.zig b/src/tracy.zig index 6f56a87ce6..9ea15d721b 100644 --- a/src/tracy.zig +++ b/src/tracy.zig @@ -28,7 +28,9 @@ pub const ___tracy_c_zone_context = extern struct { }; pub const Ctx = if (enable) ___tracy_c_zone_context else struct { - pub fn end(self: Ctx) void {} + pub fn end(self: Ctx) void { + _ = self; + } }; pub inline fn trace(comptime src: std.builtin.SourceLocation) Ctx { diff --git a/src/translate_c.zig b/src/translate_c.zig index 4b07618391..a575c0d13f 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -206,6 +206,7 @@ const Scope = struct { } fn findBlockReturnType(inner: *Scope, c: *Context) clang.QualType { + _ = c; var scope = inner; while (true) { switch (scope.id) { @@ -601,7 +602,7 @@ fn visitFnDecl(c: *Context, fn_decl: *const clang.FunctionDecl) Error!void { var scope = &block_scope.base; var param_id: c_uint = 0; - for (proto_node.data.params) |*param, i| { + for (proto_node.data.params) |*param| { const param_name = param.name orelse { proto_node.data.is_extern = true; proto_node.data.is_export = false; @@ -785,7 +786,7 @@ const builtin_typedef_map = std.ComptimeStringMap([]const u8, .{ }); fn transTypeDef(c: *Context, scope: *Scope, typedef_decl: *const clang.TypedefNameDecl) Error!void { - if (c.decl_table.get(@ptrToInt(typedef_decl.getCanonicalDecl()))) |name| + if (c.decl_table.get(@ptrToInt(typedef_decl.getCanonicalDecl()))) |_| return; // Avoid processing this decl twice const toplevel = scope.id == .root; const bs: *Scope.Block = if (!toplevel) try scope.findBlockScope(c) else undefined; @@ -935,7 +936,7 @@ fn hasFlexibleArrayField(c: *Context, record_def: *const clang.RecordDecl) bool } fn transRecordDecl(c: *Context, scope: *Scope, record_decl: *const clang.RecordDecl) Error!void { - if (c.decl_table.get(@ptrToInt(record_decl.getCanonicalDecl()))) |name| + if (c.decl_table.get(@ptrToInt(record_decl.getCanonicalDecl()))) |_| return; // Avoid processing this decl twice const record_loc = record_decl.getLocation(); const toplevel = scope.id == .root; @@ -1080,7 +1081,7 @@ fn transRecordDecl(c: *Context, scope: *Scope, record_decl: *const clang.RecordD } fn transEnumDecl(c: *Context, scope: *Scope, enum_decl: *const clang.EnumDecl) Error!void { - if (c.decl_table.get(@ptrToInt(enum_decl.getCanonicalDecl()))) |name| + if (c.decl_table.get(@ptrToInt(enum_decl.getCanonicalDecl()))) |_| return; // Avoid processing this decl twice const enum_loc = enum_decl.getLocation(); const toplevel = scope.id == .root; @@ -1312,6 +1313,7 @@ fn transConvertVectorExpr( source_loc: clang.SourceLocation, expr: *const clang.ConvertVectorExpr, ) TransError!Node { + _ = source_loc; const base_stmt = @ptrCast(*const clang.Stmt, expr); var block_scope = try Scope.Block.init(c, scope, true); @@ -1321,7 +1323,6 @@ fn transConvertVectorExpr( const src_type = qualTypeCanon(src_expr.getType()); const src_vector_ty = @ptrCast(*const clang.VectorType, src_type); const src_element_qt = src_vector_ty.getElementType(); - const src_element_type_node = try transQualType(c, &block_scope.base, src_element_qt, base_stmt.getBeginLoc()); const src_expr_node = try transExpr(c, &block_scope.base, src_expr, .used); @@ -1434,6 +1435,7 @@ fn transSimpleOffsetOfExpr( scope: *Scope, expr: *const clang.OffsetOfExpr, ) TransError!Node { + _ = scope; assert(expr.getNumComponents() == 1); const component = expr.getComponent(0); if (component.getKind() == .Field) { @@ -2270,6 +2272,7 @@ fn transStringLiteralInitializer( /// both operands resolve to addresses. The C standard requires that both operands /// point to elements of the same array object, but we do not verify that here. fn cIsPointerDiffExpr(c: *Context, stmt: *const clang.BinaryOperator) bool { + _ = c; const lhs = @ptrCast(*const clang.Stmt, stmt.getLHS()); const rhs = @ptrCast(*const clang.Stmt, stmt.getRHS()); return stmt.getOpcode() == .Sub and @@ -2573,6 +2576,7 @@ fn transInitListExprVector( expr: *const clang.InitListExpr, ty: *const clang.Type, ) TransError!Node { + _ = ty; const qt = getExprQualType(c, @ptrCast(*const clang.Expr, expr)); const vector_type = try transQualType(c, scope, qt, loc); const init_count = expr.getNumInits(); @@ -2722,6 +2726,7 @@ fn transImplicitValueInitExpr( expr: *const clang.Expr, used: ResultUsed, ) TransError!Node { + _ = used; const source_loc = expr.getBeginLoc(); const qt = getExprQualType(c, expr); const ty = qt.getTypePtr(); @@ -3408,6 +3413,7 @@ fn transUnaryExprOrTypeTraitExpr( stmt: *const clang.UnaryExprOrTypeTraitExpr, result_used: ResultUsed, ) TransError!Node { + _ = result_used; const loc = stmt.getBeginLoc(); const type_node = try transQualType(c, scope, stmt.getTypeOfArgument(), loc); @@ -3802,7 +3808,6 @@ fn transBinaryConditionalOperator(c: *Context, scope: *Scope, stmt: *const clang const res_is_bool = qualTypeIsBoolean(qt); const casted_stmt = @ptrCast(*const clang.AbstractConditionalOperator, stmt); const cond_expr = casted_stmt.getCond(); - const true_expr = casted_stmt.getTrueExpr(); const false_expr = casted_stmt.getFalseExpr(); // c: (cond_expr)?:(false_expr) @@ -3895,6 +3900,7 @@ fn maybeSuppressResult( used: ResultUsed, result: Node, ) TransError!Node { + _ = scope; if (used == .used) return result; return Tag.discard.create(c.arena, result); } @@ -4336,12 +4342,10 @@ fn transCreateNodeNumber(c: *Context, num: anytype, num_kind: enum { int, float } fn transCreateNodeMacroFn(c: *Context, name: []const u8, ref: Node, proto_alias: *ast.Payload.Func) !Node { - const scope = &c.global_scope.base; - var fn_params = std.ArrayList(ast.Payload.Param).init(c.gpa); defer fn_params.deinit(); - for (proto_alias.data.params) |param, i| { + for (proto_alias.data.params) |param| { const param_name = param.name orelse try std.fmt.allocPrint(c.arena, "arg_{d}", .{c.getMangle()}); @@ -5657,6 +5661,7 @@ fn parseCSpecifierQualifierList(c: *Context, m: *MacroCtx, scope: *Scope, allow_ } fn parseCNumericType(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node { + _ = scope; const KwCounter = struct { double: u8 = 0, long: u8 = 0, @@ -5758,6 +5763,7 @@ fn parseCNumericType(c: *Context, m: *MacroCtx, scope: *Scope) ParseError!Node { } fn parseCAbstractDeclarator(c: *Context, m: *MacroCtx, scope: *Scope, node: Node) ParseError!Node { + _ = scope; switch (m.next().?) { .Asterisk => { // last token of `node` diff --git a/src/type.zig b/src/type.zig index 549b15f366..853a4b7914 100644 --- a/src/type.zig +++ b/src/type.zig @@ -600,9 +600,11 @@ pub const Type = extern union { pub const HashContext = struct { pub fn hash(self: @This(), t: Type) u64 { + _ = self; return t.hash(); } pub fn eql(self: @This(), a: Type, b: Type) bool { + _ = self; return a.eql(b); } }; @@ -777,6 +779,7 @@ pub const Type = extern union { options: std.fmt.FormatOptions, writer: anytype, ) @TypeOf(writer).Error!void { + _ = options; comptime assert(fmt.len == 0); var ty = start_type; while (true) { @@ -3013,7 +3016,7 @@ pub const Type = extern union { .base = .{ .tag = t }, .data = data, }; - return Type{ .ptr_otherwise = &ptr.base }; + return file_struct.Type{ .ptr_otherwise = &ptr.base }; } pub fn Data(comptime t: Tag) type { @@ -3163,7 +3166,6 @@ pub const CType = enum { longdouble, pub fn sizeInBits(self: CType, target: Target) u16 { - const arch = target.cpu.arch; switch (target.os.tag) { .freestanding, .other => switch (target.cpu.arch) { .msp430 => switch (self) { diff --git a/src/value.zig b/src/value.zig index 696f3d3d88..008cc3c2fe 100644 --- a/src/value.zig +++ b/src/value.zig @@ -626,6 +626,7 @@ pub const Value = extern union { return std.mem.dupe(allocator, u8, payload.data); } if (self.castTag(.repeated)) |payload| { + _ = payload; @panic("TODO implement toAllocatedBytes for this Value tag"); } if (self.castTag(.decl_ref)) |payload| { @@ -747,6 +748,7 @@ pub const Value = extern union { /// Asserts the type is an enum type. pub fn toEnum(val: Value, enum_ty: Type, comptime E: type) E { + _ = enum_ty; // TODO this needs to resolve other kinds of Value tags rather than // assuming the tag will be .enum_field_index. const field_index = val.castTag(.enum_field_index).?.data; @@ -935,6 +937,7 @@ pub const Value = extern union { /// Converts an integer or a float to a float. /// Returns `error.Overflow` if the value does not fit in the new type. pub fn floatCast(self: Value, allocator: *Allocator, ty: Type, target: Target) !Value { + _ = target; switch (ty.tag()) { .f16 => { @panic("TODO add __trunctfhf2 to compiler-rt"); @@ -1292,17 +1295,21 @@ pub const Value = extern union { pub const ArrayHashContext = struct { pub fn hash(self: @This(), v: Value) u32 { + _ = self; return v.hash_u32(); } pub fn eql(self: @This(), a: Value, b: Value) bool { + _ = self; return a.eql(b); } }; pub const HashContext = struct { pub fn hash(self: @This(), v: Value) u64 { + _ = self; return v.hash(); } pub fn eql(self: @This(), a: Value, b: Value) bool { + _ = self; return a.eql(b); } }; @@ -1345,6 +1352,7 @@ pub const Value = extern union { } pub fn fieldValue(val: Value, allocator: *Allocator, index: usize) error{OutOfMemory}!Value { + _ = allocator; switch (val.tag()) { .@"struct" => { const field_values = val.castTag(.@"struct").?.data; diff --git a/test/behavior/align.zig b/test/behavior/align.zig index 06173ef40f..e99cf1e0e2 100644 --- a/test/behavior/align.zig +++ b/test/behavior/align.zig @@ -167,6 +167,7 @@ test "generic function with align param" { } fn whyWouldYouEverDoThis(comptime align_bytes: u8) align(align_bytes) u8 { + _ = align_bytes; return 0x1; } diff --git a/test/behavior/async_fn.zig b/test/behavior/async_fn.zig index b0e6c548ed..6d734669fc 100644 --- a/test/behavior/async_fn.zig +++ b/test/behavior/async_fn.zig @@ -13,6 +13,7 @@ test "simple coroutine suspend and resume" { resume frame; try expect(global_x == 3); const af: anyframe->void = &frame; + _ = af; resume frame; try expect(global_x == 4); } @@ -45,6 +46,7 @@ test "suspend at end of function" { fn doTheTest() !void { try expect(x == 1); const p = async suspendAtEnd(); + _ = p; try expect(x == 2); } @@ -131,7 +133,9 @@ test "@frameSize" { other(1); } fn other(param: i32) void { + _ = param; var local: i32 = undefined; + _ = local; suspend {} } }; @@ -181,6 +185,7 @@ test "coroutine suspend, resume" { test "coroutine suspend with block" { const p = async testSuspendBlock(); + _ = p; try expect(!global_result); resume a_promise; try expect(global_result); @@ -207,6 +212,7 @@ var await_final_result: i32 = 0; test "coroutine await" { await_seq('a'); var p = async await_amain(); + _ = p; await_seq('f'); resume await_a_promise; await_seq('i'); @@ -243,6 +249,7 @@ var early_final_result: i32 = 0; test "coroutine await early return" { early_seq('a'); var p = async early_amain(); + _ = p; early_seq('f'); try expect(early_final_result == 1234); try expect(std.mem.eql(u8, &early_points, "abcdef")); @@ -276,6 +283,7 @@ test "async function with dot syntax" { } }; const p = async S.foo(); + _ = p; try expect(S.y == 2); } @@ -362,11 +370,13 @@ test "error return trace across suspend points - early return" { const p = nonFailing(); resume p; const p2 = async printTrace(p); + _ = p2; } test "error return trace across suspend points - async return" { const p = nonFailing(); const p2 = async printTrace(p); + _ = p2; resume p; } @@ -396,6 +406,7 @@ fn printTrace(p: anyframe->(anyerror!void)) callconv(.Async) void { test "break from suspend" { var my_result: i32 = 1; const p = async testBreakFromSuspend(&my_result); + _ = p; try std.testing.expect(my_result == 2); } fn testBreakFromSuspend(my_result: *i32) callconv(.Async) void { @@ -619,11 +630,14 @@ test "returning a const error from async function" { fn amain() !void { var download_frame = async fetchUrl(10, "a string"); const download_text = try await download_frame; + _ = download_text; @panic("should not get here"); } fn fetchUrl(unused: i32, url: []const u8) ![]u8 { + _ = unused; + _ = url; frame = @frame(); suspend {} ok = true; @@ -700,6 +714,7 @@ fn testAsyncAwaitTypicalUsage( var global_download_frame: anyframe = undefined; fn fetchUrl(allocator: *std.mem.Allocator, url: []const u8) anyerror![]u8 { + _ = url; const result = try std.mem.dupe(allocator, u8, "expected download text"); errdefer allocator.free(result); if (suspend_download) { @@ -713,6 +728,7 @@ fn testAsyncAwaitTypicalUsage( var global_file_frame: anyframe = undefined; fn readFile(allocator: *std.mem.Allocator, filename: []const u8) anyerror![]u8 { + _ = filename; const result = try std.mem.dupe(allocator, u8, "expected file text"); errdefer allocator.free(result); if (suspend_file) { @@ -730,6 +746,7 @@ test "alignment of local variables in async functions" { const S = struct { fn doTheTest() !void { var y: u8 = 123; + _ = y; var x: u8 align(128) = 1; try expect(@ptrToInt(&x) % 128 == 0); } @@ -742,6 +759,7 @@ test "no reason to resolve frame still works" { } fn simpleNothing() void { var x: i32 = 1234; + _ = x; } test "async call a generic function" { @@ -802,6 +820,7 @@ test "struct parameter to async function is copied to the frame" { if (x == 0) return; clobberStack(x - 1); var y: i32 = x; + _ = y; } fn bar(f: *@Frame(foo)) void { @@ -1212,6 +1231,7 @@ test "suspend in while loop" { suspend {} return val; } else |err| { + err catch {}; return 0; } } @@ -1341,6 +1361,7 @@ test "async function passed 0-bit arg after non-0-bit arg" { } fn bar(x: i32, args: anytype) anyerror!void { + _ = args; global_frame = @frame(); suspend {} global_int = x; @@ -1636,6 +1657,8 @@ test "@asyncCall with pass-by-value arguments" { pub const AT = [5]u8; pub fn f(_fill0: u64, s: ST, _fill1: u64, a: AT, _fill2: u64) callconv(.Async) void { + _ = s; + _ = a; // Check that the array and struct arguments passed by value don't // end up overflowing the adjacent fields in the frame structure. expectEqual(F0, _fill0) catch @panic("test failure"); @@ -1654,6 +1677,7 @@ test "@asyncCall with pass-by-value arguments" { [_]u8{ 1, 2, 3, 4, 5 }, F2, }); + _ = frame_ptr; } test "@asyncCall with arguments having non-standard alignment" { @@ -1662,6 +1686,7 @@ test "@asyncCall with arguments having non-standard alignment" { const S = struct { pub fn f(_fill0: u32, s: struct { x: u64 align(16) }, _fill1: u64) callconv(.Async) void { + _ = s; // The compiler inserts extra alignment for s, check that the // generated code picks the right slot for fill1. expectEqual(F0, _fill0) catch @panic("test failure"); @@ -1673,4 +1698,5 @@ test "@asyncCall with arguments having non-standard alignment" { // The function pointer must not be comptime-known. var t = S.f; var frame_ptr = @asyncCall(&buffer, {}, t, .{ F0, undefined, F1 }); + _ = frame_ptr; } diff --git a/test/behavior/atomics.zig b/test/behavior/atomics.zig index 3d808b3fb6..7ac30b57c7 100644 --- a/test/behavior/atomics.zig +++ b/test/behavior/atomics.zig @@ -97,7 +97,6 @@ test "cmpxchg with ptr" { test "cmpxchg with ignored result" { var x: i32 = 1234; - var ptr = &x; _ = @cmpxchgStrong(i32, &x, 1234, 5678, .Monotonic, .Monotonic); @@ -195,7 +194,6 @@ fn testAtomicRmwInt() !void { test "atomics with different types" { try testAtomicsWithType(bool, true, false); inline for (.{ u1, i4, u5, i15, u24 }) |T| { - var x: T = 0; try testAtomicsWithType(T, 0, 1); } try testAtomicsWithType(u0, 0, 0); diff --git a/test/behavior/await_struct.zig b/test/behavior/await_struct.zig index 9e01aecc8c..229a72b9ff 100644 --- a/test/behavior/await_struct.zig +++ b/test/behavior/await_struct.zig @@ -12,6 +12,7 @@ var await_final_result = Foo{ .x = 0 }; test "coroutine await struct" { await_seq('a'); var p = async await_amain(); + _ = p; await_seq('f'); resume await_a_promise; await_seq('i'); diff --git a/test/behavior/bit_shifting.zig b/test/behavior/bit_shifting.zig index a58026e88d..c1f84a99d4 100644 --- a/test/behavior/bit_shifting.zig +++ b/test/behavior/bit_shifting.zig @@ -100,5 +100,5 @@ test "comptime shr of BigInt" { } test "comptime shift safety check" { - const x = @as(usize, 42) << @sizeOf(usize); + _ = @as(usize, 42) << @sizeOf(usize); } diff --git a/test/behavior/bugs/1310.zig b/test/behavior/bugs/1310.zig index a291b217ec..31911d5014 100644 --- a/test/behavior/bugs/1310.zig +++ b/test/behavior/bugs/1310.zig @@ -16,6 +16,8 @@ pub const InvocationTable_ = struct_InvocationTable_; pub const VM_ = struct_VM_; fn agent_callback(_vm: [*]VM, options: [*]u8) callconv(.C) i32 { + _ = _vm; + _ = options; return 11; } diff --git a/test/behavior/bugs/1467.zig b/test/behavior/bugs/1467.zig index 71c55dc59c..e062e66c8d 100644 --- a/test/behavior/bugs/1467.zig +++ b/test/behavior/bugs/1467.zig @@ -4,4 +4,5 @@ pub const S = extern struct { }; test "bug 1467" { const s: S = undefined; + _ = s; } diff --git a/test/behavior/bugs/1500.zig b/test/behavior/bugs/1500.zig index e24cfe5a9c..5683d53721 100644 --- a/test/behavior/bugs/1500.zig +++ b/test/behavior/bugs/1500.zig @@ -7,4 +7,8 @@ const B = fn (A) void; test "allow these dependencies" { var a: A = undefined; var b: B = undefined; + if (false) { + a; + b; + } } diff --git a/test/behavior/bugs/2346.zig b/test/behavior/bugs/2346.zig index c8cea34813..52c1e3ac6b 100644 --- a/test/behavior/bugs/2346.zig +++ b/test/behavior/bugs/2346.zig @@ -1,6 +1,8 @@ test "fixed" { const a: *void = undefined; const b: *[1]void = a; + _ = b; const c: *[0]u8 = undefined; const d: []u8 = c; + _ = d; } diff --git a/test/behavior/bugs/2578.zig b/test/behavior/bugs/2578.zig index cf7d941562..547aee9b22 100644 --- a/test/behavior/bugs/2578.zig +++ b/test/behavior/bugs/2578.zig @@ -5,7 +5,9 @@ const Foo = struct { var foo: Foo = undefined; const t = &foo; -fn bar(pointer: ?*c_void) void {} +fn bar(pointer: ?*c_void) void { + _ = pointer; +} test "fixed" { bar(t); diff --git a/test/behavior/bugs/2692.zig b/test/behavior/bugs/2692.zig index 267c3a131a..1bc38a0274 100644 --- a/test/behavior/bugs/2692.zig +++ b/test/behavior/bugs/2692.zig @@ -1,4 +1,6 @@ -fn foo(a: []u8) void {} +fn foo(a: []u8) void { + _ = a; +} test "address of 0 length array" { var pt: [0]u8 = undefined; diff --git a/test/behavior/bugs/3367.zig b/test/behavior/bugs/3367.zig index 3df3adbff7..b77b979b8a 100644 --- a/test/behavior/bugs/3367.zig +++ b/test/behavior/bugs/3367.zig @@ -3,7 +3,9 @@ const Foo = struct { }; const Mixin = struct { - pub fn two(self: Foo) void {} + pub fn two(self: Foo) void { + _ = self; + } }; test "container member access usingnamespace decls" { diff --git a/test/behavior/bugs/3586.zig b/test/behavior/bugs/3586.zig index 7bb1ba5d31..047cb5d205 100644 --- a/test/behavior/bugs/3586.zig +++ b/test/behavior/bugs/3586.zig @@ -8,4 +8,5 @@ test "fixed" { var ctr = Container{ .params = NoteParams{}, }; + _ = ctr; } diff --git a/test/behavior/bugs/4328.zig b/test/behavior/bugs/4328.zig index 76c3e788fd..26b96d8d6f 100644 --- a/test/behavior/bugs/4328.zig +++ b/test/behavior/bugs/4328.zig @@ -53,10 +53,12 @@ test "Peer resolution of extern function calls in @TypeOf" { test "Extern function calls, dereferences and field access in @TypeOf" { const Test = struct { fn test_fn_1(a: c_long) @TypeOf(fopen("test", "r").*) { + _ = a; return .{ .dummy_field = 0 }; } fn test_fn_2(a: anytype) @TypeOf(fopen("test", "r").*.dummy_field) { + _ = a; return 255; } diff --git a/test/behavior/bugs/4560.zig b/test/behavior/bugs/4560.zig index 682d3f2125..3119bd99b9 100644 --- a/test/behavior/bugs/4560.zig +++ b/test/behavior/bugs/4560.zig @@ -25,6 +25,10 @@ pub fn StringHashMap(comptime V: type) type { } pub fn HashMap(comptime K: type, comptime V: type) type { + if (false) { + K; + V; + } return struct { size: usize, max_distance_from_start_index: usize, diff --git a/test/behavior/bugs/4954.zig b/test/behavior/bugs/4954.zig index b5a9bdf851..3dea934895 100644 --- a/test/behavior/bugs/4954.zig +++ b/test/behavior/bugs/4954.zig @@ -1,5 +1,5 @@ fn f(buf: []u8) void { - var ptr = &buf[@sizeOf(u32)]; + _ = &buf[@sizeOf(u32)]; } test "crash" { diff --git a/test/behavior/bugs/529_other_file_2.zig b/test/behavior/bugs/529_other_file_2.zig index b493959e50..9f4636dce8 100644 --- a/test/behavior/bugs/529_other_file_2.zig +++ b/test/behavior/bugs/529_other_file_2.zig @@ -1,4 +1,6 @@ pub const A = extern struct { field: c_int, }; -export fn issue529(a: ?*A) void {} +export fn issue529(a: ?*A) void { + _ = a; +} diff --git a/test/behavior/bugs/5487.zig b/test/behavior/bugs/5487.zig index bf530a8a02..4f67e6e846 100644 --- a/test/behavior/bugs/5487.zig +++ b/test/behavior/bugs/5487.zig @@ -1,6 +1,7 @@ const io = @import("std").io; pub fn write(_: void, bytes: []const u8) !usize { + _ = bytes; return 0; } pub fn writer() io.Writer(void, @typeInfo(@typeInfo(@TypeOf(write)).Fn.return_type.?).ErrorUnion.error_set, write) { diff --git a/test/behavior/bugs/624.zig b/test/behavior/bugs/624.zig index 4d52aad693..b8bf09f22e 100644 --- a/test/behavior/bugs/624.zig +++ b/test/behavior/bugs/624.zig @@ -12,6 +12,7 @@ const ListenerContext = struct { const ContextAllocator = MemoryPool(TestContext); fn MemoryPool(comptime T: type) type { + _ = T; return struct { n: usize, }; diff --git a/test/behavior/bugs/679.zig b/test/behavior/bugs/679.zig index 9b402defca..6420e7f99f 100644 --- a/test/behavior/bugs/679.zig +++ b/test/behavior/bugs/679.zig @@ -2,6 +2,7 @@ const std = @import("std"); const expect = std.testing.expect; pub fn List(comptime T: type) type { + _ = T; return u32; } diff --git a/test/behavior/bugs/7003.zig b/test/behavior/bugs/7003.zig index 75fc9068b1..3568f36d2b 100644 --- a/test/behavior/bugs/7003.zig +++ b/test/behavior/bugs/7003.zig @@ -5,4 +5,5 @@ test "@Type should resolve its children types" { comptime var sparse_info = @typeInfo(anyerror!sparse); sparse_info.ErrorUnion.payload = dense; const B = @Type(sparse_info); + _ = B; } diff --git a/test/behavior/bugs/7027.zig b/test/behavior/bugs/7027.zig index 782eebbfc9..064c511ca8 100644 --- a/test/behavior/bugs/7027.zig +++ b/test/behavior/bugs/7027.zig @@ -9,7 +9,9 @@ const Foobar = struct { } }; -fn foo(arg: anytype) void {} +fn foo(arg: anytype) void { + _ = arg; +} test "" { comptime var foobar = Foobar.foo(); diff --git a/test/behavior/bugs/704.zig b/test/behavior/bugs/704.zig index 765336c95f..15fe9419a6 100644 --- a/test/behavior/bugs/704.zig +++ b/test/behavior/bugs/704.zig @@ -1,5 +1,7 @@ const xxx = struct { - pub fn bar(self: *xxx) void {} + pub fn bar(self: *xxx) void { + _ = self; + } }; test "bug 704" { var x: xxx = undefined; diff --git a/test/behavior/bugs/7250.zig b/test/behavior/bugs/7250.zig index b0f1aa15df..862b75f851 100644 --- a/test/behavior/bugs/7250.zig +++ b/test/behavior/bugs/7250.zig @@ -3,7 +3,9 @@ const nrfx_uart_t = extern struct { drv_inst_idx: u8, }; -pub fn nrfx_uart_rx(p_instance: [*c]const nrfx_uart_t) void {} +pub fn nrfx_uart_rx(p_instance: [*c]const nrfx_uart_t) void { + _ = p_instance; +} threadlocal var g_uart0 = nrfx_uart_t{ .p_reg = 0, diff --git a/test/behavior/bugs/828.zig b/test/behavior/bugs/828.zig index 50ae0fd279..d54664f9c6 100644 --- a/test/behavior/bugs/828.zig +++ b/test/behavior/bugs/828.zig @@ -4,6 +4,7 @@ const CountBy = struct { const One = CountBy{ .a = 1 }; pub fn counter(self: *const CountBy) Counter { + _ = self; return Counter{ .i = 0 }; } }; @@ -18,6 +19,7 @@ const Counter = struct { }; fn constCount(comptime cb: *const CountBy, comptime unused: u32) void { + _ = unused; comptime { var cnt = cb.counter(); if (cnt.i != 0) @compileError("Counter instance reused!"); @@ -30,4 +32,8 @@ test "comptime struct return should not return the same instance" { //a second parameter is required to trigger the bug const ValA = constCount(&CountBy.One, 12); const ValB = constCount(&CountBy.One, 15); + if (false) { + ValA; + ValB; + } } diff --git a/test/behavior/bugs/920.zig b/test/behavior/bugs/920.zig index b148fce578..8d30f01369 100644 --- a/test/behavior/bugs/920.zig +++ b/test/behavior/bugs/920.zig @@ -46,6 +46,8 @@ fn norm_f_inv(y: f64) f64 { return math.sqrt(-2.0 * math.ln(y)); } fn norm_zero_case(random: *Random, u: f64) f64 { + _ = random; + _ = u; return 0.0; } diff --git a/test/behavior/cast.zig b/test/behavior/cast.zig index 864579c8f0..e9e2df991e 100644 --- a/test/behavior/cast.zig +++ b/test/behavior/cast.zig @@ -102,6 +102,7 @@ fn castToOptionalTypeError(z: i32) !void { const f = z; const g: anyerror!?i32 = f; + _ = g catch {}; const a = A{ .a = z }; const b: anyerror!?A = a; @@ -114,7 +115,9 @@ test "implicitly cast from int to anyerror!?T" { } fn implicitIntLitToOptional() void { const f: ?i32 = 1; + _ = f; const g: anyerror!?i32 = 1; + _ = g catch {}; } test "return null from fn() anyerror!?&T" { @@ -821,9 +824,13 @@ test "variable initialization uses result locations properly with regards to the test "cast between [*c]T and ?[*:0]T on fn parameter" { const S = struct { const Handler = ?fn ([*c]const u8) callconv(.C) void; - fn addCallback(handler: Handler) void {} + fn addCallback(handler: Handler) void { + _ = handler; + } - fn myCallback(cstr: ?[*:0]const u8) callconv(.C) void {} + fn myCallback(cstr: ?[*:0]const u8) callconv(.C) void { + _ = cstr; + } fn doTheTest() void { addCallback(myCallback); diff --git a/test/behavior/enum.zig b/test/behavior/enum.zig index a1a4bbdca8..dbda9f3238 100644 --- a/test/behavior/enum.zig +++ b/test/behavior/enum.zig @@ -111,6 +111,8 @@ test "enum type" { .y = 5678, }, }; + try expect(foo1.One == 13); + try expect(foo2.Two.x == 1234 and foo2.Two.y == 5678); const bar = Bar.B; try expect(bar == Bar.B); diff --git a/test/behavior/error.zig b/test/behavior/error.zig index c0b4dc0231..b1ef55af9e 100644 --- a/test/behavior/error.zig +++ b/test/behavior/error.zig @@ -103,6 +103,7 @@ fn testErrorSetType() !void { const a: MyErrSet!i32 = 5678; const b: MyErrSet!i32 = MyErrSet.OutOfMemory; + try expect(b catch error.OutOfMemory == error.OutOfMemory); if (a) |value| try expect(value == 5678) else |err| switch (err) { error.OutOfMemory => unreachable, @@ -138,7 +139,10 @@ test "comptime test error for empty error set" { const EmptyErrorSet = error{}; fn testComptimeTestErrorEmptySet(x: EmptyErrorSet!i32) !void { - if (x) |v| try expect(v == 1234) else |err| @compileError("bad"); + if (x) |v| try expect(v == 1234) else |err| { + _ = err; + @compileError("bad"); + } } test "syntax: optional operator in front of error union operator" { @@ -162,6 +166,7 @@ fn testErrToIntWithOnePossibleValue( test "empty error union" { const x = error{} || error{}; + _ = x; } test "error union peer type resolution" { @@ -204,6 +209,7 @@ fn entry() void { fn foo2(f: fn () anyerror!void) void { const x = f(); + x catch {}; } fn bar2() (error{}!void) {} @@ -338,6 +344,7 @@ test "optional error set is the same size as error set" { test "debug info for optional error set" { const SomeError = error{Hello}; var a_local_variable: ?SomeError = null; + _ = a_local_variable; } test "nested catch" { @@ -349,7 +356,7 @@ test "nested catch" { return error.Wrong; } fn func() anyerror!Foo { - const x = fail() catch + _ = fail() catch fail() catch return error.Bad; unreachable; @@ -390,6 +397,7 @@ test "function pointer with return type that is error union with payload which i const Err = error{UnspecifiedErr}; fn bar(a: i32) anyerror!*Foo { + _ = a; return Err.UnspecifiedErr; } @@ -444,7 +452,9 @@ test "error payload type is correctly resolved" { test "error union comptime caching" { const S = struct { - fn foo(comptime arg: anytype) void {} + fn foo(comptime arg: anytype) void { + arg catch {}; + } }; S.foo(@as(anyerror!void, {})); diff --git a/test/behavior/eval.zig b/test/behavior/eval.zig index f86ee79761..80a3bccb7c 100644 --- a/test/behavior/eval.zig +++ b/test/behavior/eval.zig @@ -184,6 +184,7 @@ fn testTryToTrickEvalWithRuntimeIf(b: bool) usize { comptime var i: usize = 0; inline while (i < 10) : (i += 1) { const result = if (b) false else true; + _ = result; } comptime { return i; @@ -195,6 +196,7 @@ test "inlined loop has array literal with elided runtime scope on first iteratio comptime var i: usize = 0; inline while (i < 2) : (i += 1) { const result = if (i == 0) [1]i32{2} else runtime; + _ = result; } comptime { try expect(i == 2); @@ -420,6 +422,7 @@ test { } pub fn TypeWithCompTimeSlice(comptime field_name: []const u8) type { + _ = field_name; return struct { pub const Node = struct {}; }; @@ -696,7 +699,9 @@ test "refer to the type of a generic function" { f(i32); } -fn doNothingWithType(comptime T: type) void {} +fn doNothingWithType(comptime T: type) void { + _ = T; +} test "zero extend from u0 to u1" { var zero_u0: u0 = 0; @@ -817,7 +822,9 @@ test "two comptime calls with array default initialized to undefined" { result.getCpuArch(); } - pub fn getCpuArch(self: CrossTarget) void {} + pub fn getCpuArch(self: CrossTarget) void { + _ = self; + } }; const DynamicLinker = struct { diff --git a/test/behavior/fn.zig b/test/behavior/fn.zig index 75a1131072..2567582cd3 100644 --- a/test/behavior/fn.zig +++ b/test/behavior/fn.zig @@ -23,6 +23,7 @@ test "void parameters" { try voidFun(1, void{}, 2, {}); } fn voidFun(a: i32, b: void, c: i32, d: void) !void { + _ = d; const v = b; const vv: void = if (a == 1) v else {}; try expect(a + c == 3); @@ -57,7 +58,9 @@ test "call function with empty string" { acceptsString(""); } -fn acceptsString(foo: []u8) void {} +fn acceptsString(foo: []u8) void { + _ = foo; +} fn @"weird function name"() i32 { return 1234; @@ -70,7 +73,9 @@ test "implicit cast function unreachable return" { wantsFnWithVoid(fnWithUnreachable); } -fn wantsFnWithVoid(f: fn () void) void {} +fn wantsFnWithVoid(f: fn () void) void { + _ = f; +} fn fnWithUnreachable() noreturn { unreachable; @@ -162,6 +167,7 @@ const Point3 = struct { y: i32, fn addPointCoords(self: Point3, comptime T: type) i32 { + _ = T; return self.x + self.y; } }; diff --git a/test/behavior/for.zig b/test/behavior/for.zig index 9f08d41246..b022df0958 100644 --- a/test/behavior/for.zig +++ b/test/behavior/for.zig @@ -29,10 +29,14 @@ test "for loop with pointer elem var" { mangleString(target[0..]); try expect(mem.eql(u8, &target, "bcdefgh")); - for (source) |*c, i| + for (source) |*c, i| { + _ = i; try expect(@TypeOf(c) == *const u8); - for (target) |*c, i| + } + for (target) |*c, i| { + _ = i; try expect(@TypeOf(c) == *u8); + } } fn mangleString(s: []u8) void { @@ -53,6 +57,7 @@ test "basic for loop" { buf_index += 1; } for (array) |item, index| { + _ = item; buffer[buf_index] = @intCast(u8, index); buf_index += 1; } @@ -62,6 +67,7 @@ test "basic for loop" { buf_index += 1; } for (array_ptr) |item, index| { + _ = item; buffer[buf_index] = @intCast(u8, index); buf_index += 1; } @@ -70,7 +76,7 @@ test "basic for loop" { buffer[buf_index] = item; buf_index += 1; } - for (unknown_size) |item, index| { + for (unknown_size) |_, index| { buffer[buf_index] = @intCast(u8, index); buf_index += 1; } @@ -118,6 +124,7 @@ test "2 break statements and an else" { var buf: [10]u8 = undefined; var ok = false; ok = for (buf) |item| { + _ = item; if (f) break false; if (t) break true; } else false; @@ -136,6 +143,7 @@ test "for with null and T peer types and inferred result location type" { break item; } } else null) |v| { + _ = v; @panic("fail"); } } diff --git a/test/behavior/if.zig b/test/behavior/if.zig index 1951a9262a..e8c84f4570 100644 --- a/test/behavior/if.zig +++ b/test/behavior/if.zig @@ -45,7 +45,7 @@ var global_with_err: anyerror!u32 = error.SomeError; test "unwrap mutable global var" { if (global_with_val) |v| { try expect(v == 0); - } else |e| { + } else |_| { unreachable; } if (global_with_err) |_| { diff --git a/test/behavior/import.zig b/test/behavior/import.zig index 2b037637da..2018ee0b93 100644 --- a/test/behavior/import.zig +++ b/test/behavior/import.zig @@ -18,5 +18,5 @@ test "import in non-toplevel scope" { } test "import empty file" { - const empty = @import("import/empty.zig"); + _ = @import("import/empty.zig"); } diff --git a/test/behavior/inttoptr.zig b/test/behavior/inttoptr.zig index de6e8e3a1e..7c07a63b7c 100644 --- a/test/behavior/inttoptr.zig +++ b/test/behavior/inttoptr.zig @@ -5,7 +5,7 @@ test "casting random address to function pointer" { fn randomAddressToFunction() void { var addr: usize = 0xdeadbeef; - var ptr = @intToPtr(fn () void, addr); + _ = @intToPtr(fn () void, addr); } test "mutate through ptr initialized with constant intToPtr value" { diff --git a/test/behavior/ir_block_deps.zig b/test/behavior/ir_block_deps.zig index aacb7b7658..09c1532bff 100644 --- a/test/behavior/ir_block_deps.zig +++ b/test/behavior/ir_block_deps.zig @@ -5,6 +5,7 @@ fn foo(id: u64) !i32 { 1 => getErrInt(), 2 => { const size = try getErrInt(); + _ = size; return try getErrInt(); }, else => error.ItBroke, diff --git a/test/behavior/math.zig b/test/behavior/math.zig index e615c36551..5c746816e2 100644 --- a/test/behavior/math.zig +++ b/test/behavior/math.zig @@ -333,6 +333,12 @@ test "quad hex float literal parsing in range" { const b = 0x1.dedafcff354b6ae9758763545432p-9; const c = 0x1.2f34dd5f437e849b4baab754cdefp+4534; const d = 0x1.edcbff8ad76ab5bf46463233214fp-435; + if (false) { + a; + b; + c; + d; + } } test "quad hex float literal parsing accurate" { @@ -457,6 +463,11 @@ test "hex float literal within range" { const a = 0x1.0p16383; const b = 0x0.1p16387; const c = 0x1.0p-16382; + if (false) { + a; + b; + c; + } } test "truncating shift left" { diff --git a/test/behavior/misc.zig b/test/behavior/misc.zig index 35f088eb4d..6fabbf487b 100644 --- a/test/behavior/misc.zig +++ b/test/behavior/misc.zig @@ -234,6 +234,7 @@ test "compile time global reinterpret" { test "explicit cast maybe pointers" { const a: ?*i32 = undefined; const b: ?*f32 = @ptrCast(?*f32, a); + _ = b; } test "generic malloc free" { @@ -244,14 +245,18 @@ var some_mem: [100]u8 = undefined; fn memAlloc(comptime T: type, n: usize) anyerror![]T { return @ptrCast([*]T, &some_mem[0])[0..n]; } -fn memFree(comptime T: type, memory: []T) void {} +fn memFree(comptime T: type, memory: []T) void { + _ = memory; +} test "cast undefined" { const array: [100]u8 = undefined; const slice = @as([]const u8, &array); testCastUndefined(slice); } -fn testCastUndefined(x: []const u8) void {} +fn testCastUndefined(x: []const u8) void { + _ = x; +} test "cast small unsigned to larger signed" { try expect(castSmallUnsignedToLargerSigned1(200) == @as(i16, 200)); @@ -451,6 +456,7 @@ test "@typeName" { } fn TypeFromFn(comptime T: type) type { + _ = T; return struct {}; } @@ -554,7 +560,12 @@ test "packed struct, enum, union parameters in extern function" { }), &(PackedUnion{ .a = 1 })); } -export fn testPackedStuff(a: *const PackedStruct, b: *const PackedUnion) void {} +export fn testPackedStuff(a: *const PackedStruct, b: *const PackedUnion) void { + if (false) { + a; + b; + } +} test "slicing zero length array" { const s1 = ""[0..]; @@ -583,6 +594,7 @@ test "self reference through fn ptr field" { }; fn foo(a: A) u8 { + _ = a; return 12; } }; @@ -752,7 +764,9 @@ test "extern variable with non-pointer opaque type" { test "lazy typeInfo value as generic parameter" { const S = struct { - fn foo(args: anytype) void {} + fn foo(args: anytype) void { + _ = args; + } }; S.foo(@typeInfo(@TypeOf(.{}))); } diff --git a/test/behavior/null.zig b/test/behavior/null.zig index 45401f621a..3bd652772b 100644 --- a/test/behavior/null.zig +++ b/test/behavior/null.zig @@ -39,6 +39,7 @@ test "test maybe object and get a pointer to the inner value" { test "rhs maybe unwrap return" { const x: ?bool = true; const y = x orelse return; + _ = y; } test "maybe return" { @@ -129,6 +130,7 @@ var struct_with_optional: StructWithOptional = undefined; test "unwrap optional which is field of global var" { struct_with_optional.field = null; if (struct_with_optional.field) |payload| { + _ = payload; unreachable; } struct_with_optional.field = 1234; diff --git a/test/behavior/optional.zig b/test/behavior/optional.zig index 75b4311159..2943915869 100644 --- a/test/behavior/optional.zig +++ b/test/behavior/optional.zig @@ -128,6 +128,7 @@ test "nested orelse" { const x = maybe() orelse maybe() orelse return null; + _ = x; unreachable; } const Foo = struct { @@ -160,6 +161,7 @@ test "self-referential struct through a slice of optional" { test "assigning to an unwrapped optional field in an inline loop" { comptime var maybe_pos_arg: ?comptime_int = null; inline for ("ab") |x| { + _ = x; maybe_pos_arg = 0; if (maybe_pos_arg.? != 0) { @compileError("bad"); diff --git a/test/behavior/pointers.zig b/test/behavior/pointers.zig index a078e58ab5..bb95d3c219 100644 --- a/test/behavior/pointers.zig +++ b/test/behavior/pointers.zig @@ -65,6 +65,10 @@ test "assigning integer to C pointer" { var x: i32 = 0; var ptr: [*c]u8 = 0; var ptr2: [*c]u8 = x; + if (false) { + ptr; + ptr2; + } } test "implicit cast single item pointer to C pointer and back" { @@ -78,7 +82,6 @@ test "implicit cast single item pointer to C pointer and back" { test "C pointer comparison and arithmetic" { const S = struct { fn doTheTest() !void { - var one: usize = 1; var ptr1: [*c]u32 = 0; var ptr2 = ptr1 + 10; try expect(ptr1 == 0); @@ -176,6 +179,7 @@ test "assign null directly to C pointer and test null equality" { try expect(!(x != null)); try expect(!(null != x)); if (x) |same_x| { + _ = same_x; @panic("fail"); } var otherx: i32 = undefined; @@ -186,7 +190,10 @@ test "assign null directly to C pointer and test null equality" { comptime try expect(null == y); comptime try expect(!(y != null)); comptime try expect(!(null != y)); - if (y) |same_y| @panic("fail"); + if (y) |same_y| { + _ = same_y; + @panic("fail"); + } const othery: i32 = undefined; comptime try expect((y orelse &othery) == &othery); @@ -325,6 +332,7 @@ test "@ptrToInt on null optional at comptime" { { const pointer = @intToPtr(?*u8, 0x000); const x = @ptrToInt(pointer); + _ = x; comptime try expect(0 == @ptrToInt(pointer)); } { diff --git a/test/behavior/reflection.zig b/test/behavior/reflection.zig index 3e5e4087c4..e8596c2844 100644 --- a/test/behavior/reflection.zig +++ b/test/behavior/reflection.zig @@ -15,6 +15,11 @@ test "reflection: function return type, var args, and param types" { } fn dummy(a: bool, b: i32, c: f32) i32 { + if (false) { + a; + b; + c; + } return 1234; } diff --git a/test/behavior/sizeof_and_typeof.zig b/test/behavior/sizeof_and_typeof.zig index d241448e05..60951a4c5a 100644 --- a/test/behavior/sizeof_and_typeof.zig +++ b/test/behavior/sizeof_and_typeof.zig @@ -195,11 +195,11 @@ test "branching logic inside @TypeOf" { fn fn1(alpha: bool) void { const n: usize = 7; - const v = if (alpha) n else @sizeOf(usize); + _ = if (alpha) n else @sizeOf(usize); } test "lazy @sizeOf result is checked for definedness" { - const f = fn1; + _ = fn1; } test "@bitSizeOf" { diff --git a/test/behavior/slice.zig b/test/behavior/slice.zig index d324c34477..38d0faa25a 100644 --- a/test/behavior/slice.zig +++ b/test/behavior/slice.zig @@ -104,6 +104,7 @@ test "obtaining a null terminated slice" { // now we obtain a null terminated slice: const ptr = buf[0..3 :0]; + _ = ptr; var runtime_len: usize = 3; const ptr2 = buf[0..runtime_len :0]; diff --git a/test/behavior/slice_sentinel_comptime.zig b/test/behavior/slice_sentinel_comptime.zig index 79da5d3c52..368860547e 100644 --- a/test/behavior/slice_sentinel_comptime.zig +++ b/test/behavior/slice_sentinel_comptime.zig @@ -3,6 +3,7 @@ test "comptime slice-sentinel in bounds (unterminated)" { comptime { var target = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; const slice = target[0..3 :'d']; + _ = slice; } // ptr_array @@ -10,6 +11,7 @@ test "comptime slice-sentinel in bounds (unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target = &buf; const slice = target[0..3 :'d']; + _ = slice; } // vector_ConstPtrSpecialBaseArray @@ -17,6 +19,7 @@ test "comptime slice-sentinel in bounds (unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = &buf; const slice = target[0..3 :'d']; + _ = slice; } // vector_ConstPtrSpecialRef @@ -24,6 +27,7 @@ test "comptime slice-sentinel in bounds (unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = @ptrCast([*]u8, &buf); const slice = target[0..3 :'d']; + _ = slice; } // cvector_ConstPtrSpecialBaseArray @@ -31,6 +35,7 @@ test "comptime slice-sentinel in bounds (unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = &buf; const slice = target[0..3 :'d']; + _ = slice; } // cvector_ConstPtrSpecialRef @@ -38,6 +43,7 @@ test "comptime slice-sentinel in bounds (unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = @ptrCast([*c]u8, &buf); const slice = target[0..3 :'d']; + _ = slice; } // slice @@ -45,6 +51,7 @@ test "comptime slice-sentinel in bounds (unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: []u8 = &buf; const slice = target[0..3 :'d']; + _ = slice; } } @@ -53,6 +60,7 @@ test "comptime slice-sentinel in bounds (end,unterminated)" { comptime { var target = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; const slice = target[0..13 :0xff]; + _ = slice; } // ptr_array @@ -60,6 +68,7 @@ test "comptime slice-sentinel in bounds (end,unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target = &buf; const slice = target[0..13 :0xff]; + _ = slice; } // vector_ConstPtrSpecialBaseArray @@ -67,6 +76,7 @@ test "comptime slice-sentinel in bounds (end,unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: [*]u8 = &buf; const slice = target[0..13 :0xff]; + _ = slice; } // vector_ConstPtrSpecialRef @@ -74,6 +84,7 @@ test "comptime slice-sentinel in bounds (end,unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: [*]u8 = @ptrCast([*]u8, &buf); const slice = target[0..13 :0xff]; + _ = slice; } // cvector_ConstPtrSpecialBaseArray @@ -81,6 +92,7 @@ test "comptime slice-sentinel in bounds (end,unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: [*c]u8 = &buf; const slice = target[0..13 :0xff]; + _ = slice; } // cvector_ConstPtrSpecialRef @@ -88,6 +100,7 @@ test "comptime slice-sentinel in bounds (end,unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: [*c]u8 = @ptrCast([*c]u8, &buf); const slice = target[0..13 :0xff]; + _ = slice; } // slice @@ -95,6 +108,7 @@ test "comptime slice-sentinel in bounds (end,unterminated)" { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: []u8 = &buf; const slice = target[0..13 :0xff]; + _ = slice; } } @@ -103,6 +117,7 @@ test "comptime slice-sentinel in bounds (terminated)" { comptime { var target = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; const slice = target[0..3 :'d']; + _ = slice; } // ptr_array @@ -110,6 +125,7 @@ test "comptime slice-sentinel in bounds (terminated)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target = &buf; const slice = target[0..3 :'d']; + _ = slice; } // vector_ConstPtrSpecialBaseArray @@ -117,6 +133,7 @@ test "comptime slice-sentinel in bounds (terminated)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = &buf; const slice = target[0..3 :'d']; + _ = slice; } // vector_ConstPtrSpecialRef @@ -124,6 +141,7 @@ test "comptime slice-sentinel in bounds (terminated)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = @ptrCast([*]u8, &buf); const slice = target[0..3 :'d']; + _ = slice; } // cvector_ConstPtrSpecialBaseArray @@ -131,6 +149,7 @@ test "comptime slice-sentinel in bounds (terminated)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = &buf; const slice = target[0..3 :'d']; + _ = slice; } // cvector_ConstPtrSpecialRef @@ -138,6 +157,7 @@ test "comptime slice-sentinel in bounds (terminated)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = @ptrCast([*c]u8, &buf); const slice = target[0..3 :'d']; + _ = slice; } // slice @@ -145,6 +165,7 @@ test "comptime slice-sentinel in bounds (terminated)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: []u8 = &buf; const slice = target[0..3 :'d']; + _ = slice; } } @@ -153,6 +174,7 @@ test "comptime slice-sentinel in bounds (on target sentinel)" { comptime { var target = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; const slice = target[0..14 :0]; + _ = slice; } // ptr_array @@ -160,6 +182,7 @@ test "comptime slice-sentinel in bounds (on target sentinel)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target = &buf; const slice = target[0..14 :0]; + _ = slice; } // vector_ConstPtrSpecialBaseArray @@ -167,6 +190,7 @@ test "comptime slice-sentinel in bounds (on target sentinel)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = &buf; const slice = target[0..14 :0]; + _ = slice; } // vector_ConstPtrSpecialRef @@ -174,6 +198,7 @@ test "comptime slice-sentinel in bounds (on target sentinel)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = @ptrCast([*]u8, &buf); const slice = target[0..14 :0]; + _ = slice; } // cvector_ConstPtrSpecialBaseArray @@ -181,6 +206,7 @@ test "comptime slice-sentinel in bounds (on target sentinel)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = &buf; const slice = target[0..14 :0]; + _ = slice; } // cvector_ConstPtrSpecialRef @@ -188,6 +214,7 @@ test "comptime slice-sentinel in bounds (on target sentinel)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = @ptrCast([*c]u8, &buf); const slice = target[0..14 :0]; + _ = slice; } // slice @@ -195,5 +222,6 @@ test "comptime slice-sentinel in bounds (on target sentinel)" { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: []u8 = &buf; const slice = target[0..14 :0]; + _ = slice; } } diff --git a/test/behavior/struct.zig b/test/behavior/struct.zig index 9773680922..4f7e0c2d71 100644 --- a/test/behavior/struct.zig +++ b/test/behavior/struct.zig @@ -182,6 +182,7 @@ test "empty struct method call" { } const EmptyStruct = struct { fn method(es: *const EmptyStruct) i32 { + _ = es; return 1234; } }; @@ -452,9 +453,11 @@ fn alloc(comptime T: type) []T { test "call method with mutable reference to struct with no fields" { const S = struct { fn doC(s: *const @This()) bool { + _ = s; return true; } fn do(s: *@This()) bool { + _ = s; return true; } }; @@ -584,13 +587,14 @@ test "default struct initialization fields" { const x = S{ .b = 5, }; - if (x.a + x.b != 1239) { - @compileError("it should be comptime known"); - } var five: i32 = 5; const y = S{ .b = five, }; + if (x.a + x.b != 1239) { + @compileError("it should be comptime known"); + } + try expectEqual(y, x); try expectEqual(1239, x.a + x.b); } @@ -624,11 +628,13 @@ test "for loop over pointers to struct, getting field from struct pointer" { var ok = true; fn eql(a: []const u8) bool { + _ = a; return true; } const ArrayList = struct { fn toSlice(self: *ArrayList) []*Foo { + _ = self; return @as([*]*Foo, undefined)[0..0]; } }; @@ -654,6 +660,7 @@ test "zero-bit field in packed struct" { y: void, }; var x: S = undefined; + _ = x; } test "struct field init with catch" { diff --git a/test/behavior/switch.zig b/test/behavior/switch.zig index 9d05e3edea..e512565b80 100644 --- a/test/behavior/switch.zig +++ b/test/behavior/switch.zig @@ -103,6 +103,7 @@ fn switchProngWithVarFn(a: SwitchProngWithVarEnum) !void { }, SwitchProngWithVarEnum.Meh => |x| { const v: void = x; + _ = v; }, } } @@ -385,6 +386,7 @@ test "switch with null and T peer types and inferred result location type" { 0 => true, else => null, }) |v| { + _ = v; @panic("fail"); } } @@ -410,12 +412,18 @@ test "switch prongs with cases with identical payload types" { try expect(@TypeOf(e) == usize); try expect(e == 8); }, - .B => |e| @panic("fail"), + .B => |e| { + _ = e; + @panic("fail"); + }, } } fn doTheSwitch2(u: Union) !void { switch (u) { - .A, .C => |e| @panic("fail"), + .A, .C => |e| { + _ = e; + @panic("fail"); + }, .B => |e| { try expect(@TypeOf(e) == isize); try expect(e == -8); @@ -454,6 +462,7 @@ test "switch variable for range and multiple prongs" { } } }; + _ = S; } var state: u32 = 0; @@ -506,7 +515,10 @@ test "switch on error set with single else" { fn doTheTest() !void { var some: error{Foo} = error.Foo; try expect(switch (some) { - else => |a| true, + else => |a| blk: { + a catch {}; + break :blk true; + }, }); } }; diff --git a/test/behavior/tuple.zig b/test/behavior/tuple.zig index 29d44d582f..632e5be013 100644 --- a/test/behavior/tuple.zig +++ b/test/behavior/tuple.zig @@ -105,6 +105,7 @@ test "tuple initializer for var" { .id = @as(usize, 2), .name = Bytes{ .id = 20 }, }; + _ = tmp; } }; diff --git a/test/behavior/type.zig b/test/behavior/type.zig index 5d12ea494f..3a56f2171f 100644 --- a/test/behavior/type.zig +++ b/test/behavior/type.zig @@ -431,11 +431,14 @@ test "Type.Fn" { const foo = struct { fn func(a: usize, b: bool) align(4) callconv(.C) usize { + _ = a; + _ = b; return 0; } }.func; const Foo = @Type(@typeInfo(@TypeOf(foo))); const foo_2: Foo = foo; + _ = foo_2; } test "Type.BoundFn" { @@ -443,7 +446,9 @@ test "Type.BoundFn" { if (builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64) return error.SkipZigTest; const TestStruct = packed struct { - pub fn foo(self: *const @This()) align(4) callconv(.Unspecified) void {} + pub fn foo(self: *const @This()) align(4) callconv(.Unspecified) void { + _ = self; + } }; const test_instance: TestStruct = undefined; try testing.expect(std.meta.eql( diff --git a/test/behavior/type_info.zig b/test/behavior/type_info.zig index 6e9fbe676d..8e8039372c 100644 --- a/test/behavior/type_info.zig +++ b/test/behavior/type_info.zig @@ -277,7 +277,9 @@ const TestStruct = packed struct { fieldC: *Self, fieldD: u32 = 4, - pub fn foo(self: *const Self) void {} + pub fn foo(self: *const Self) void { + _ = self; + } const Self = @This(); }; @@ -326,9 +328,12 @@ extern fn fooAligned(a: usize, b: bool, ...) align(4) callconv(.C) usize; test "typeInfo with comptime parameter in struct fn def" { const S = struct { - pub fn func(comptime x: f32) void {} + pub fn func(comptime x: f32) void { + _ = x; + } }; comptime var info = @typeInfo(S); + _ = info; } test "type info: vectors" { @@ -368,6 +373,7 @@ test "type info: pass to function" { } fn passTypeInfo(comptime info: TypeInfo) type { + _ = info; return void; } diff --git a/test/behavior/underscore.zig b/test/behavior/underscore.zig index 516d33a4eb..abe219f3e0 100644 --- a/test/behavior/underscore.zig +++ b/test/behavior/underscore.zig @@ -7,7 +7,9 @@ test "ignore lval with underscore" { test "ignore lval with underscore (for loop)" { for ([_]void{}) |_, i| { + _ = i; for ([_]void{}) |_, j| { + _ = j; break; } break; diff --git a/test/behavior/union.zig b/test/behavior/union.zig index bcdd3fa247..f7c0c93696 100644 --- a/test/behavior/union.zig +++ b/test/behavior/union.zig @@ -374,7 +374,9 @@ const Attribute = union(enum) { B: u8, }; -fn setAttribute(attr: Attribute) void {} +fn setAttribute(attr: Attribute) void { + _ = attr; +} fn Setter(attr: Attribute) type { return struct { @@ -465,7 +467,9 @@ test "union no tag with struct member" { const Struct = struct {}; const Union = union { s: Struct, - pub fn foo(self: *@This()) void {} + pub fn foo(self: *@This()) void { + _ = self; + } }; var u = Union{ .s = Struct{} }; u.foo(); @@ -703,6 +707,7 @@ test "method call on an empty union" { X2: [0]u8, pub fn useIt(self: *@This()) bool { + _ = self; return true; } }; @@ -771,6 +776,7 @@ test "@unionInit on union w/ tag but no fields" { no_op: void, pub fn decode(buf: []const u8) Data { + _ = buf; return @unionInit(Data, "no_op", {}); } }; @@ -781,6 +787,7 @@ test "@unionInit on union w/ tag but no fields" { fn doTheTest() !void { var data: Data = .{ .no_op = .{} }; + _ = data; var o = Data.decode(&[_]u8{}); try expectEqual(Type.no_op, o); } diff --git a/test/behavior/var_args.zig b/test/behavior/var_args.zig index 8935877167..40770e1334 100644 --- a/test/behavior/var_args.zig +++ b/test/behavior/var_args.zig @@ -18,7 +18,7 @@ test "add arbitrary args" { } fn readFirstVarArg(args: anytype) void { - const value = args[0]; + _ = args[0]; } test "send void arg to var args" { @@ -48,6 +48,7 @@ test "runtime parameter before var args" { } fn extraFn(extra: u32, args: anytype) !usize { + _ = extra; if (args.len >= 1) { try expect(args[0] == false); } @@ -63,9 +64,11 @@ const foos = [_]fn (anytype) bool{ }; fn foo1(args: anytype) bool { + _ = args; return true; } fn foo2(args: anytype) bool { + _ = args; return false; } @@ -79,5 +82,5 @@ test "pass zero length array to var args param" { } fn doNothingWithFirstArg(args: anytype) void { - const a = args[0]; + _ = args[0]; } diff --git a/test/behavior/vector.zig b/test/behavior/vector.zig index 77793b67e6..1847640a91 100644 --- a/test/behavior/vector.zig +++ b/test/behavior/vector.zig @@ -113,6 +113,7 @@ test "array to vector" { var foo: f32 = 3.14; var arr = [4]f32{ foo, 1.5, 0.0, 0.0 }; var vec: Vector(4, f32) = arr; + _ = vec; } test "vector casts of sizes not divisable by 8" { @@ -264,6 +265,7 @@ test "initialize vector which is a struct field" { var foo = Vec4Obj{ .data = [_]f32{ 1, 2, 3, 4 }, }; + _ = foo; } }; try S.doTheTest(); diff --git a/test/behavior/void.zig b/test/behavior/void.zig index 4f49d5fca1..17778d42de 100644 --- a/test/behavior/void.zig +++ b/test/behavior/void.zig @@ -36,5 +36,5 @@ test "void optional" { test "void array as a local variable initializer" { var x = [_]void{{}} ** 1004; - var y = x[0]; + _ = x[0]; } diff --git a/test/behavior/while.zig b/test/behavior/while.zig index a237b4b866..e52adfdbcf 100644 --- a/test/behavior/while.zig +++ b/test/behavior/while.zig @@ -151,14 +151,14 @@ test "while on optional with else result follow break prong" { test "while on error union with else result follow else prong" { const result = while (returnError()) |value| { break value; - } else |err| @as(i32, 2); + } else |_| @as(i32, 2); try expect(result == 2); } test "while on error union with else result follow break prong" { const result = while (returnSuccess(10)) |value| { break value; - } else |err| @as(i32, 2); + } else |_| @as(i32, 2); try expect(result == 10); } diff --git a/test/stage2/cbe.zig b/test/stage2/cbe.zig index eec475e3da..fd55015dd5 100644 --- a/test/stage2/cbe.zig +++ b/test/stage2/cbe.zig @@ -93,16 +93,16 @@ pub fn addCases(ctx: *TestContext) !void { , ""); case.addError( \\pub export fn main() c_int { - \\ const c = @intToError(0); + \\ _ = @intToError(0); \\ return 0; \\} - , &.{":2:27: error: integer value 0 represents no error"}); + , &.{":2:21: error: integer value 0 represents no error"}); case.addError( \\pub export fn main() c_int { - \\ const c = @intToError(3); + \\ _ = @intToError(3); \\ return 0; \\} - , &.{":2:27: error: integer value 3 represents no error"}); + , &.{":2:21: error: integer value 3 represents no error"}); } { @@ -383,6 +383,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ true => 2, \\ false => 3, \\ }; + \\ _ = b; \\} , &.{ ":6:9: error: duplicate switch value", @@ -398,6 +399,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ f64, i32 => 3, \\ else => 4, \\ }; + \\ _ = b; \\} , &.{ ":6:14: error: duplicate switch value", @@ -414,6 +416,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ f16...f64 => 3, \\ else => 4, \\ }; + \\ _ = b; \\} , &.{ ":3:30: error: ranges not allowed when switching on type 'type'", @@ -431,6 +434,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ 3 => 40, \\ else => 50, \\ }; + \\ _ = b; \\} , &.{ ":8:14: error: unreachable else prong; all cases already handled", @@ -556,10 +560,10 @@ pub fn addCases(ctx: *TestContext) !void { \\const E1 = packed enum { a, b, c }; \\const E2 = extern enum { a, b, c }; \\export fn foo() void { - \\ const x = E1.a; + \\ _ = E1.a; \\} \\export fn bar() void { - \\ const x = E2.a; + \\ _ = E2.a; \\} , &.{ ":1:12: error: enums do not support 'packed' or 'extern'; instead provide an explicit integer tag type", @@ -579,10 +583,10 @@ pub fn addCases(ctx: *TestContext) !void { \\ c, \\}; \\export fn foo() void { - \\ const x = E1.a; + \\ _ = E1.a; \\} \\export fn bar() void { - \\ const x = E2.a; + \\ _ = E2.a; \\} , &.{ ":3:5: error: enum fields cannot be marked comptime", @@ -621,7 +625,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ c, \\}; \\export fn foo() void { - \\ const x = E1.a; + \\ _ = E1.a; \\} , &.{ ":3:7: error: expected ',', found 'align'", @@ -638,7 +642,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ _, \\}; \\export fn foo() void { - \\ const x = E1.a; + \\ _ = E1.a; \\} , &.{ ":6:5: error: redundant non-exhaustive enum mark", @@ -653,7 +657,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ _ = 10, \\}; \\export fn foo() void { - \\ const x = E1.a; + \\ _ = E1.a; \\} , &.{ ":5:9: error: '_' is used to mark an enum as non-exhaustive and cannot be assigned a value", @@ -662,7 +666,7 @@ pub fn addCases(ctx: *TestContext) !void { case.addError( \\const E1 = enum {}; \\export fn foo() void { - \\ const x = E1.a; + \\ _ = E1.a; \\} , &.{ ":1:12: error: enum declarations must have at least one tag", @@ -671,7 +675,7 @@ pub fn addCases(ctx: *TestContext) !void { case.addError( \\const E1 = enum { a, b, _ }; \\export fn foo() void { - \\ const x = E1.a; + \\ _ = E1.a; \\} , &.{ ":1:12: error: non-exhaustive enum missing integer tag type", @@ -681,7 +685,7 @@ pub fn addCases(ctx: *TestContext) !void { case.addError( \\const E1 = enum { a, b, c, b, d }; \\pub export fn main() c_int { - \\ const x = E1.a; + \\ _ = E1.a; \\} , &.{ ":1:28: error: duplicate enum tag", @@ -691,28 +695,28 @@ pub fn addCases(ctx: *TestContext) !void { case.addError( \\pub export fn main() c_int { \\ const a = true; - \\ const b = @enumToInt(a); + \\ _ = @enumToInt(a); \\} , &.{ - ":3:26: error: expected enum or tagged union, found bool", + ":3:20: error: expected enum or tagged union, found bool", }); case.addError( \\pub export fn main() c_int { \\ const a = 1; - \\ const b = @intToEnum(bool, a); + \\ _ = @intToEnum(bool, a); \\} , &.{ - ":3:26: error: expected enum, found bool", + ":3:20: error: expected enum, found bool", }); case.addError( \\const E = enum { a, b, c }; \\pub export fn main() c_int { - \\ const b = @intToEnum(E, 3); + \\ _ = @intToEnum(E, 3); \\} , &.{ - ":3:15: error: enum 'test_case.E' has no tag with value 3", + ":3:9: error: enum 'test_case.E' has no tag with value 3", ":1:11: note: enum declared here", }); @@ -780,10 +784,10 @@ pub fn addCases(ctx: *TestContext) !void { case.addError( \\const E = enum { a, b, c }; \\pub export fn main() c_int { - \\ var x = E.d; + \\ _ = E.d; \\} , &.{ - ":3:14: error: enum 'test_case.E' has no member named 'd'", + ":3:10: error: enum 'test_case.E' has no member named 'd'", ":1:11: note: enum declared here", }); @@ -791,6 +795,7 @@ pub fn addCases(ctx: *TestContext) !void { \\const E = enum { a, b, c }; \\pub export fn main() c_int { \\ var x: E = .d; + \\ _ = x; \\} , &.{ ":3:17: error: enum 'test_case.E' has no field named 'd'", @@ -818,31 +823,35 @@ pub fn addCases(ctx: *TestContext) !void { \\ ); ctx.h("header with single param function", linux_x64, - \\export fn start(a: u8) void{} + \\export fn start(a: u8) void{ + \\ _ = a; + \\} , \\ZIG_EXTERN_C void start(uint8_t a0); \\ ); ctx.h("header with multiple param function", linux_x64, - \\export fn start(a: u8, b: u8, c: u8) void{} + \\export fn start(a: u8, b: u8, c: u8) void{ + \\ _ = a; _ = b; _ = c; + \\} , \\ZIG_EXTERN_C void start(uint8_t a0, uint8_t a1, uint8_t a2); \\ ); ctx.h("header with u32 param function", linux_x64, - \\export fn start(a: u32) void{} + \\export fn start(a: u32) void{ _ = a; } , \\ZIG_EXTERN_C void start(uint32_t a0); \\ ); ctx.h("header with usize param function", linux_x64, - \\export fn start(a: usize) void{} + \\export fn start(a: usize) void{ _ = a; } , \\ZIG_EXTERN_C void start(uintptr_t a0); \\ ); ctx.h("header with bool param function", linux_x64, - \\export fn start(a: bool) void{} + \\export fn start(a: bool) void{_ = a;} , \\ZIG_EXTERN_C void start(bool a0); \\ @@ -866,7 +875,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ ); ctx.h("header with multiple includes", linux_x64, - \\export fn start(a: u32, b: usize) void{} + \\export fn start(a: u32, b: usize) void{ _ = a; _ = b; } , \\ZIG_EXTERN_C void start(uint32_t a0, uintptr_t a1); \\ diff --git a/test/stage2/test.zig b/test/stage2/test.zig index 977f5f9ebf..8ce46f2064 100644 --- a/test/stage2/test.zig +++ b/test/stage2/test.zig @@ -246,11 +246,20 @@ pub fn addCases(ctx: *TestContext) !void { "", ); } + { + var case = ctx.exe("unused vars", linux_x64); + case.addError( + \\pub fn main() void { + \\ const x = 1; + \\} + , &.{":2:11: error: unused local constant"}); + } { var case = ctx.exe("@TypeOf", linux_x64); case.addCompareOutput( \\pub fn main() void { \\ var x: usize = 0; + \\ _ = x; \\ const z = @TypeOf(x, @as(u128, 5)); \\ assert(z == u128); \\} @@ -275,9 +284,9 @@ pub fn addCases(ctx: *TestContext) !void { ); case.addError( \\pub fn main() void { - \\ const z = @TypeOf(true, 1); + \\ _ = @TypeOf(true, 1); \\} - , &[_][]const u8{":2:15: error: incompatible types: 'bool' and 'comptime_int'"}); + , &[_][]const u8{":2:9: error: incompatible types: 'bool' and 'comptime_int'"}); } { @@ -738,6 +747,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ \\ cool thx \\ \\ \\ ; + \\ _ = ignore; \\ add('ぁ', '\x03'); \\} \\ @@ -889,6 +899,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ try expect(false); \\ } \\ }; + \\ _ = S; \\} , &.{":4:13: error: invalid 'try' outside function scope"}, @@ -979,6 +990,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ return bar; \\ } \\ }; + \\ _ = S; \\} , &.{ ":5:20: error: 'bar' not accessible from inner function", @@ -1064,6 +1076,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ @compileLog(b, 20, f, x); \\ @compileLog(1000); \\ var bruh: usize = true; + \\ _ = bruh; \\ unreachable; \\} \\export fn other() void { @@ -1209,6 +1222,7 @@ pub fn addCases(ctx: *TestContext) !void { case.addError( \\pub fn main() void { \\ var x = null; + \\ _ = x; \\} , &[_][]const u8{ ":2:9: error: variable of type '@Type(.Null)' must be const or comptime", @@ -1378,7 +1392,9 @@ pub fn addCases(ctx: *TestContext) !void { \\pub fn main() void { \\ doNothing(0); \\} - \\fn doNothing(arg: u0) void {} + \\fn doNothing(arg: u0) void { + \\ _ = arg; + \\} , "", ); @@ -1448,14 +1464,14 @@ pub fn addCases(ctx: *TestContext) !void { case.addCompareOutput( \\pub fn main() void { \\ const E = error{ A, B, D } || error { A, B, C }; - \\ const a = E.A; - \\ const b = E.B; - \\ const c = E.C; - \\ const d = E.D; + \\ E.A catch {}; + \\ E.B catch {}; + \\ E.C catch {}; + \\ E.D catch {}; \\ const E2 = error { X, Y } || @TypeOf(error.Z); - \\ const x = E2.X; - \\ const y = E2.Y; - \\ const z = E2.Z; + \\ E2.X catch {}; + \\ E2.Y catch {}; + \\ E2.Z catch {}; \\ assert(anyerror || error { Z } == anyerror); \\} \\fn assert(b: bool) void { @@ -1477,6 +1493,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ [arg1] "{rdi}" (code) \\ : "rcx", "r11", "memory" \\ ); + \\ _ = x; \\} , &[_][]const u8{":4:27: error: expected type, found comptime_int"}); } diff --git a/test/stage2/wasm.zig b/test/stage2/wasm.zig index 947f90ff0f..07386e8212 100644 --- a/test/stage2/wasm.zig +++ b/test/stage2/wasm.zig @@ -64,7 +64,7 @@ pub fn addCases(ctx: *TestContext) !void { \\ foo(10, 20); \\ return 5; \\} - \\fn foo(x: u32, y: u32) void {} + \\fn foo(x: u32, y: u32) void { _ = x; _ = y; } , "5\n"); } @@ -76,6 +76,10 @@ pub fn addCases(ctx: *TestContext) !void { \\ var i: u32 = 5; \\ var y: f32 = 42.0; \\ var x: u32 = 10; + \\ if (false) { + \\ y; + \\ x; + \\ } \\ return i; \\} , "5\n"); @@ -84,12 +88,14 @@ pub fn addCases(ctx: *TestContext) !void { \\pub export fn _start() u32 { \\ var i: u32 = 5; \\ var y: f32 = 42.0; + \\ _ = y; \\ var x: u32 = 10; \\ foo(i, x); \\ i = x; \\ return i; \\} \\fn foo(x: u32, y: u32) void { + \\ _ = y; \\ var i: u32 = 10; \\ i = x; \\} @@ -388,6 +394,10 @@ pub fn addCases(ctx: *TestContext) !void { \\pub export fn _start() i32 { \\ var number1 = Number.One; \\ var number2: Number = .Two; + \\ if (false) { + \\ number1; + \\ number2; + \\ } \\ const number3 = @intToEnum(Number, 2); \\ \\ return @enumToInt(number3); diff --git a/test/standalone/hello_world/hello_libc.zig b/test/standalone/hello_world/hello_libc.zig index 5c0a233f1c..42ba4db4b1 100644 --- a/test/standalone/hello_world/hello_libc.zig +++ b/test/standalone/hello_world/hello_libc.zig @@ -8,6 +8,8 @@ const c = @cImport({ const msg = "Hello, world!\n"; pub export fn main(argc: c_int, argv: **u8) c_int { + _ = argv; + _ = argc; if (c.printf(msg) != @intCast(c_int, c.strlen(msg))) return -1; return 0; } diff --git a/test/standalone/issue_339/test.zig b/test/standalone/issue_339/test.zig index 2d0c14c0f5..5e0aafc182 100644 --- a/test/standalone/issue_339/test.zig +++ b/test/standalone/issue_339/test.zig @@ -1,5 +1,7 @@ const StackTrace = @import("std").builtin.StackTrace; pub fn panic(msg: []const u8, stack_trace: ?*StackTrace) noreturn { + _ = msg; + _ = stack_trace; @breakpoint(); while (true) {} } diff --git a/test/standalone/issue_8550/main.zig b/test/standalone/issue_8550/main.zig index 7dae7f856c..615e9aed6a 100644 --- a/test/standalone/issue_8550/main.zig +++ b/test/standalone/issue_8550/main.zig @@ -1,6 +1,11 @@ export fn main(r0: u32, r1: u32, atags: u32) callconv(.C) noreturn { + _ = r0; + _ = r1; + _ = atags; unreachable; // never gets run so it doesn't matter } pub fn panic(msg: []const u8, error_return_trace: ?*@import("std").builtin.StackTrace) noreturn { + _ = msg; + _ = error_return_trace; while (true) {} } diff --git a/test/tests.zig b/test/tests.zig index 26f38d4e28..8871c18428 100644 --- a/test/tests.zig +++ b/test/tests.zig @@ -417,6 +417,8 @@ pub fn addStandaloneTests(b: *build.Builder, test_filter: ?[]const u8, modes: [] } pub fn addCliTests(b: *build.Builder, test_filter: ?[]const u8, modes: []const Mode) *build.Step { + _ = test_filter; + _ = modes; const step = b.step("test-cli", "Test the command line interface"); const exe = b.addExecutable("test-cli", "test/cli.zig"); @@ -525,7 +527,6 @@ pub fn addPkgTests( if (skip_single_threaded and test_target.single_threaded) continue; - const ArchTag = std.meta.Tag(std.Target.Cpu.Arch); if (test_target.disable_native and test_target.target.getOsTag() == std.Target.current.os.tag and test_target.target.getCpuArch() == std.Target.current.cpu.arch) diff --git a/tools/process_headers.zig b/tools/process_headers.zig index c087688732..51fc69e579 100644 --- a/tools/process_headers.zig +++ b/tools/process_headers.zig @@ -236,12 +236,14 @@ const DestTarget = struct { const HashContext = struct { pub fn hash(self: @This(), a: DestTarget) u32 { + _ = self; return @enumToInt(a.arch) +% (@enumToInt(a.os) *% @as(u32, 4202347608)) +% (@enumToInt(a.abi) *% @as(u32, 4082223418)); } pub fn eql(self: @This(), a: DestTarget, b: DestTarget) bool { + _ = self; return a.arch.eql(b.arch) and a.os == b.os and a.abi == b.abi; @@ -256,6 +258,7 @@ const Contents = struct { is_generic: bool, fn hitCountLessThan(context: void, lhs: *const Contents, rhs: *const Contents) bool { + _ = context; return lhs.hit_count < rhs.hit_count; } }; diff --git a/tools/update_clang_options.zig b/tools/update_clang_options.zig index f5f5cc8e24..04cdbf44de 100644 --- a/tools/update_clang_options.zig +++ b/tools/update_clang_options.zig @@ -585,6 +585,8 @@ const Syntax = union(enum) { options: std.fmt.FormatOptions, out_stream: anytype, ) !void { + _ = fmt; + _ = options; switch (self) { .multi_arg => |n| return out_stream.print(".{{.{s}={}}}", .{ @tagName(self), n }), else => return out_stream.print(".{s}", .{@tagName(self)}), @@ -663,6 +665,7 @@ fn syntaxMatchesWithEql(syntax: Syntax) bool { } fn objectLessThan(context: void, a: *json.ObjectMap, b: *json.ObjectMap) bool { + _ = context; // Priority is determined by exact matches first, followed by prefix matches in descending // length, with key as a final tiebreaker. const a_syntax = objSyntax(a); diff --git a/tools/update_cpu_features.zig b/tools/update_cpu_features.zig index dfaeec2862..68d9b233a7 100644 --- a/tools/update_cpu_features.zig +++ b/tools/update_cpu_features.zig @@ -1227,14 +1227,17 @@ fn usageAndExit(file: fs.File, arg0: []const u8, code: u8) noreturn { } fn featureLessThan(context: void, a: Feature, b: Feature) bool { + _ = context; return std.ascii.lessThanIgnoreCase(a.zig_name, b.zig_name); } fn cpuLessThan(context: void, a: Cpu, b: Cpu) bool { + _ = context; return std.ascii.lessThanIgnoreCase(a.zig_name, b.zig_name); } fn asciiLessThan(context: void, a: []const u8, b: []const u8) bool { + _ = context; return std.ascii.lessThanIgnoreCase(a, b); } diff --git a/tools/update_glibc.zig b/tools/update_glibc.zig index 94e4ab756e..ba12f6e0e6 100644 --- a/tools/update_glibc.zig +++ b/tools/update_glibc.zig @@ -155,7 +155,7 @@ pub fn main() !void { } const fn_set = &target_funcs_gop.value_ptr.list; - for (lib_names) |lib_name, lib_name_index| { + for (lib_names) |lib_name| { const lib_prefix = if (std.mem.eql(u8, lib_name, "ld")) "" else "lib"; const basename = try fmt.allocPrint(allocator, "{s}{s}.abilist", .{ lib_prefix, lib_name }); const abi_list_filename = blk: { @@ -263,7 +263,7 @@ pub fn main() !void { // Now the mapping of version and function to integer index is complete. // Here we create a mapping of function name to list of versions. - for (abi_lists) |*abi_list, abi_index| { + for (abi_lists) |*abi_list| { const value = target_functions.getPtr(@ptrToInt(abi_list)).?; const fn_vers_list = &value.fn_vers_list; for (value.list.items) |*ver_fn| { @@ -286,7 +286,7 @@ pub fn main() !void { const abilist_txt = buffered.writer(); // first iterate over the abi lists - for (abi_lists) |*abi_list, abi_index| { + for (abi_lists) |*abi_list| { const fn_vers_list = &target_functions.getPtr(@ptrToInt(abi_list)).?.fn_vers_list; for (abi_list.targets) |target, it_i| { if (it_i != 0) try abilist_txt.writeByte(' '); @@ -312,10 +312,12 @@ pub fn main() !void { } pub fn strCmpLessThan(context: void, a: []const u8, b: []const u8) bool { + _ = context; return std.mem.order(u8, a, b) == .lt; } pub fn versionLessThan(context: void, a: []const u8, b: []const u8) bool { + _ = context; const sep_chars = "GLIBC_."; var a_tokens = std.mem.tokenize(a, sep_chars); var b_tokens = std.mem.tokenize(b, sep_chars); diff --git a/tools/update_spirv_features.zig b/tools/update_spirv_features.zig index 5f2bab6c28..0de1c56934 100644 --- a/tools/update_spirv_features.zig +++ b/tools/update_spirv_features.zig @@ -37,6 +37,7 @@ const Version = struct { } fn lessThan(ctx: void, a: Version, b: Version) bool { + _ = ctx; return if (a.major == b.major) a.minor < b.minor else