From baabc6013ea4f44082e69375214e76b5d803c5cb Mon Sep 17 00:00:00 2001 From: mlugg Date: Fri, 10 Nov 2023 07:57:54 +0000 Subject: compiler: add error for unnecessary use of 'var' When a local variable is never used as an lvalue, we can determine that `const` would be sufficient for this variable, so emit an error in this case. More sophisticated checking is unfortunately not possible with Zig's current analysis model, since whether an lvalue is actually mutated depends on semantic analysis, in which some code paths may not be analyzed, so attempting to determine this would result in false positive compile errors. It's worth noting that an unfortunate consequence of this is that any field call `a.b()` will allow `a` to be `var`, even if `b` does not take a pointer as its first parameter - this is again a necessary compromise because the parameter type is not known until semantic analysis. Also update `translate-c` to not trigger these errors. This is done by replacing the `_ = @TypeOf(x)` emitted with `_ = &x` - the reference there means that the local is permitted to be `var`. A similar strategy will be used to prevent compile errors in the behavior tests, where we sometimes want to force a value to be runtime-known. Resolves: #224 --- src/AstGen.zig | 28 +++++++++++++++++++++------- src/translate_c/ast.zig | 9 +++++++-- 2 files changed, 28 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/AstGen.zig b/src/AstGen.zig index 5638216ed1..58ba3ee11c 100644 --- a/src/AstGen.zig +++ b/src/AstGen.zig @@ -1226,7 +1226,7 @@ fn awaitExpr( try astgen.errNoteNode(gz.suspend_node, "suspend block here", .{}), }); } - const operand = try expr(gz, scope, .{ .rl = .none }, rhs_node); + const operand = try expr(gz, scope, .{ .rl = .ref }, rhs_node); const result = if (gz.nosuspend_node != 0) try gz.addExtendedPayload(.await_nosuspend, Zir.Inst.UnNode{ .node = gz.nodeIndexToRelative(node), @@ -1248,7 +1248,7 @@ fn resumeExpr( const tree = astgen.tree; const node_datas = tree.nodes.items(.data); const rhs_node = node_datas[node].lhs; - const operand = try expr(gz, scope, .{ .rl = .none }, rhs_node); + const operand = try expr(gz, scope, .{ .rl = .ref }, rhs_node); const result = try gz.addUnNode(.@"resume", operand, node); return rvalue(gz, ri, result, node); } @@ -2941,11 +2941,19 @@ fn checkUsed(gz: *GenZir, outer_scope: *Scope, inner_scope: *Scope) InnerError!v const s = scope.cast(Scope.LocalPtr).?; if (s.used == 0 and s.discarded == 0) { try astgen.appendErrorTok(s.token_src, "unused {s}", .{@tagName(s.id_cat)}); - } else if (s.used != 0 and s.discarded != 0) { - try astgen.appendErrorTokNotes(s.discarded, "pointless discard of {s}", .{@tagName(s.id_cat)}, &[_]u32{ - try gz.astgen.errNoteTok(s.used, "used here", .{}), - }); + } else { + if (s.used != 0 and s.discarded != 0) { + try astgen.appendErrorTokNotes(s.discarded, "pointless discard of {s}", .{@tagName(s.id_cat)}, &[_]u32{ + try astgen.errNoteTok(s.used, "used here", .{}), + }); + } + if (s.id_cat == .@"local variable" and !s.used_as_lvalue) { + try astgen.appendErrorTokNotes(s.token_src, "local variable is never mutated", .{}, &.{ + try astgen.errNoteTok(s.token_src, "consider using 'const'", .{}), + }); + } } + scope = s.parent; }, .defer_normal, .defer_error => scope = scope.cast(Scope.Defer).?.parent, @@ -7579,7 +7587,10 @@ fn localVarRef( ); switch (ri.rl) { - .ref, .ref_coerced_ty => return ptr_inst, + .ref, .ref_coerced_ty => { + local_ptr.used_as_lvalue = true; + return ptr_inst; + }, else => { const loaded = try gz.addUnNode(.load, ptr_inst, ident); return rvalueNoCoercePreRef(gz, ri, loaded, ident); @@ -10948,6 +10959,9 @@ const Scope = struct { /// Track the identifier where it is discarded, like this `_ = foo;`. /// 0 means never discarded. discarded: Ast.TokenIndex = 0, + /// Whether this value is used as an lvalue after inititialization. + /// If not, we know it can be `const`, so will emit a compile error if it is `var`. + used_as_lvalue: bool = false, /// String table index. name: u32, id_cat: IdCat, diff --git a/src/translate_c/ast.zig b/src/translate_c/ast.zig index 0381f58cf9..8330e6785f 100644 --- a/src/translate_c/ast.zig +++ b/src/translate_c/ast.zig @@ -1625,13 +1625,18 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex { }); const main_token = try c.addToken(.equal, "="); if (payload.value.tag() == .identifier) { - // Render as `_ = @TypeOf(foo);` to avoid tripping "pointless discard" error. + // Render as `_ = &foo;` to avoid tripping "pointless discard" and "local variable never mutated" errors. + var addr_of_pl: Payload.UnOp = .{ + .base = .{ .tag = .address_of }, + .data = payload.value, + }; + const addr_of: Node = .{ .ptr_otherwise = &addr_of_pl.base }; return c.addNode(.{ .tag = .assign, .main_token = main_token, .data = .{ .lhs = lhs, - .rhs = try renderBuiltinCall(c, "@TypeOf", &.{payload.value}), + .rhs = try renderNode(c, addr_of), }, }); } else { -- cgit v1.2.3 From 172c2797bdd5f939e53acc26ea6820896e62733a Mon Sep 17 00:00:00 2001 From: mlugg Date: Tue, 14 Nov 2023 18:40:07 +0000 Subject: link: fix MachO boundary symbol resolution --- src/link/MachO.zig | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/link/MachO.zig b/src/link/MachO.zig index ee09137759..f0938a3c19 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -1923,6 +1923,8 @@ fn resolveBoundarySymbols(self: *MachO) !void { _ = self.unresolved.swapRemove(global_index); continue; } + + next_sym += 1; } } -- cgit v1.2.3 From b35589343894791a48b1423aa6d4a59b4858dfdb Mon Sep 17 00:00:00 2001 From: mlugg Date: Tue, 14 Nov 2023 09:10:53 +0000 Subject: compiler: correct unnecessary uses of 'var' --- src/Air.zig | 2 +- src/AstGen.zig | 4 +- src/Autodoc.zig | 100 ++++++++++++++++++------------------- src/Compilation.zig | 12 ++--- src/Package/Fetch/git.zig | 18 +++---- src/Sema.zig | 18 +++---- src/arch/riscv64/CodeGen.zig | 5 ++ src/arch/sparc64/CodeGen.zig | 4 ++ src/arch/wasm/CodeGen.zig | 8 +-- src/arch/x86_64/CodeGen.zig | 2 +- src/arch/x86_64/Disassembler.zig | 3 +- src/arch/x86_64/Lower.zig | 2 +- src/arch/x86_64/encoder.zig | 4 +- src/aro_translate_c.zig | 4 +- src/codegen.zig | 2 +- src/codegen/llvm/BitcodeReader.zig | 2 +- src/codegen/spirv.zig | 8 +-- src/link/C.zig | 2 +- src/link/Coff.zig | 10 ++-- src/link/Dwarf.zig | 6 +-- src/link/Elf.zig | 10 ++-- src/link/Elf/eh_frame.zig | 2 +- src/link/MachO.zig | 14 +++--- src/link/MachO/Archive.zig | 6 +-- src/link/MachO/Dylib.zig | 6 +-- src/link/MachO/Trie.zig | 16 +++--- src/link/MachO/UnwindInfo.zig | 2 +- src/link/MachO/eh_frame.zig | 2 +- src/link/MachO/load_commands.zig | 2 +- src/link/MachO/zld.zig | 2 +- src/link/Plan9.zig | 12 ++--- src/link/Wasm.zig | 10 ++-- src/link/Wasm/Object.zig | 6 +-- src/link/tapi/yaml.zig | 2 +- src/main.zig | 14 +++--- src/resinator/bmp.zig | 2 +- src/resinator/cli.zig | 10 ++-- src/resinator/code_pages.zig | 6 +-- src/resinator/comments.zig | 8 +-- src/resinator/compile.zig | 8 +-- src/resinator/lang.zig | 2 +- src/resinator/parse.zig | 12 ++--- src/resinator/res.zig | 4 +- src/resinator/source_mapping.zig | 4 +- src/translate_c.zig | 10 ++-- src/value.zig | 6 +-- src/windows_sdk.zig | 18 +++---- 47 files changed, 210 insertions(+), 202 deletions(-) (limited to 'src') diff --git a/src/Air.zig b/src/Air.zig index 8bcc4dbf92..9bf0bd5eca 100644 --- a/src/Air.zig +++ b/src/Air.zig @@ -1787,7 +1787,7 @@ pub fn mustLower(air: Air, inst: Air.Inst.Index, ip: *const InternPool) bool { => false, .assembly => { - var extra = air.extraData(Air.Asm, data.ty_pl.payload); + const extra = air.extraData(Air.Asm, data.ty_pl.payload); const is_volatile = @as(u1, @truncate(extra.data.flags >> 31)) != 0; return is_volatile or if (extra.data.outputs_len == 1) @as(Air.Inst.Ref, @enumFromInt(air.extra[extra.end])) != .none diff --git a/src/AstGen.zig b/src/AstGen.zig index 58ba3ee11c..be6e88af0a 100644 --- a/src/AstGen.zig +++ b/src/AstGen.zig @@ -6707,7 +6707,7 @@ fn forExpr( }; } - var then_node = for_full.ast.then_expr; + const then_node = for_full.ast.then_expr; var then_scope = parent_gz.makeSubBlock(&cond_scope.base); defer then_scope.unstack(); @@ -8160,7 +8160,7 @@ fn typeOf( } const payload_size: u32 = std.meta.fields(Zir.Inst.TypeOfPeer).len; const payload_index = try reserveExtra(astgen, payload_size + args.len); - var args_index = payload_index + payload_size; + const args_index = payload_index + payload_size; const typeof_inst = try gz.addExtendedMultiOpPayloadIndex(.typeof_peer, payload_index, args.len); diff --git a/src/Autodoc.zig b/src/Autodoc.zig index cd64b5e2cf..754c29cec3 100644 --- a/src/Autodoc.zig +++ b/src/Autodoc.zig @@ -985,7 +985,7 @@ fn walkInstruction( }, .import => { const str_tok = data[@intFromEnum(inst)].str_tok; - var path = str_tok.get(file.zir); + const path = str_tok.get(file.zir); // importFile cannot error out since all files // are already loaded at this point @@ -1210,7 +1210,7 @@ fn walkInstruction( .compile_error => { const un_node = data[@intFromEnum(inst)].un_node; - var operand: DocData.WalkResult = try self.walkRef( + const operand: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1252,7 +1252,7 @@ fn walkInstruction( const byte_count = str.len * @sizeOf(std.math.big.Limb); const limb_bytes = file.zir.string_bytes[str.start..][0..byte_count]; - var limbs = try self.arena.alloc(std.math.big.Limb, str.len); + const limbs = try self.arena.alloc(std.math.big.Limb, str.len); @memcpy(std.mem.sliceAsBytes(limbs)[0..limb_bytes.len], limb_bytes); const big_int = std.math.big.int.Const{ @@ -1281,7 +1281,7 @@ fn walkInstruction( const slice_index = self.exprs.items.len; try self.exprs.append(self.arena, .{ .slice = .{ .lhs = 0, .start = 0 } }); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1289,7 +1289,7 @@ fn walkInstruction( false, call_ctx, ); - var start: DocData.WalkResult = try self.walkRef( + const start: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1321,7 +1321,7 @@ fn walkInstruction( const slice_index = self.exprs.items.len; try self.exprs.append(self.arena, .{ .slice = .{ .lhs = 0, .start = 0 } }); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1329,7 +1329,7 @@ fn walkInstruction( false, call_ctx, ); - var start: DocData.WalkResult = try self.walkRef( + const start: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1337,7 +1337,7 @@ fn walkInstruction( false, call_ctx, ); - var end: DocData.WalkResult = try self.walkRef( + const end: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1371,7 +1371,7 @@ fn walkInstruction( const slice_index = self.exprs.items.len; try self.exprs.append(self.arena, .{ .slice = .{ .lhs = 0, .start = 0 } }); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1379,7 +1379,7 @@ fn walkInstruction( false, call_ctx, ); - var start: DocData.WalkResult = try self.walkRef( + const start: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1387,7 +1387,7 @@ fn walkInstruction( false, call_ctx, ); - var end: DocData.WalkResult = try self.walkRef( + const end: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1395,7 +1395,7 @@ fn walkInstruction( false, call_ctx, ); - var sentinel: DocData.WalkResult = try self.walkRef( + const sentinel: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1436,7 +1436,7 @@ fn walkInstruction( const slice_index = self.exprs.items.len; try self.exprs.append(self.arena, .{ .slice = .{ .lhs = 0, .start = 0 } }); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1444,7 +1444,7 @@ fn walkInstruction( false, call_ctx, ); - var start: DocData.WalkResult = try self.walkRef( + const start: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1452,7 +1452,7 @@ fn walkInstruction( false, call_ctx, ); - var len: DocData.WalkResult = try self.walkRef( + const len: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1460,7 +1460,7 @@ fn walkInstruction( false, call_ctx, ); - var sentinel_opt: ?DocData.WalkResult = if (extra.data.sentinel != .none) + const sentinel_opt: ?DocData.WalkResult = if (extra.data.sentinel != .none) try self.walkRef( file, parent_scope, @@ -1574,7 +1574,7 @@ fn walkInstruction( const binop_index = self.exprs.items.len; try self.exprs.append(self.arena, .{ .binOp = .{ .lhs = 0, .rhs = 0 } }); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1582,7 +1582,7 @@ fn walkInstruction( false, call_ctx, ); - var rhs: DocData.WalkResult = try self.walkRef( + const rhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1620,7 +1620,7 @@ fn walkInstruction( const binop_index = self.exprs.items.len; try self.exprs.append(self.arena, .{ .binOp = .{ .lhs = 0, .rhs = 0 } }); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1628,7 +1628,7 @@ fn walkInstruction( false, call_ctx, ); - var rhs: DocData.WalkResult = try self.walkRef( + const rhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1786,7 +1786,7 @@ fn walkInstruction( const pl_node = data[@intFromEnum(inst)].pl_node; const extra = file.zir.extraData(Zir.Inst.Bin, pl_node.payload_index); - var rhs: DocData.WalkResult = try self.walkRef( + const rhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1801,7 +1801,7 @@ fn walkInstruction( const rhs_index = self.exprs.items.len; try self.exprs.append(self.arena, rhs.expr); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1850,7 +1850,7 @@ fn walkInstruction( const binop_index = self.exprs.items.len; try self.exprs.append(self.arena, .{ .builtinBin = .{ .lhs = 0, .rhs = 0 } }); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1858,7 +1858,7 @@ fn walkInstruction( false, call_ctx, ); - var rhs: DocData.WalkResult = try self.walkRef( + const rhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1882,7 +1882,7 @@ fn walkInstruction( const pl_node = data[@intFromEnum(inst)].pl_node; const extra = file.zir.extraData(Zir.Inst.MulAdd, pl_node.payload_index); - var mul1: DocData.WalkResult = try self.walkRef( + const mul1: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1890,7 +1890,7 @@ fn walkInstruction( false, call_ctx, ); - var mul2: DocData.WalkResult = try self.walkRef( + const mul2: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1898,7 +1898,7 @@ fn walkInstruction( false, call_ctx, ); - var add: DocData.WalkResult = try self.walkRef( + const add: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1914,7 +1914,7 @@ fn walkInstruction( const add_index = self.exprs.items.len; try self.exprs.append(self.arena, add.expr); - var type_index: usize = self.exprs.items.len; + const type_index: usize = self.exprs.items.len; try self.exprs.append(self.arena, add.typeRef orelse .{ .type = @intFromEnum(Ref.type_type) }); return DocData.WalkResult{ @@ -1933,7 +1933,7 @@ fn walkInstruction( const pl_node = data[@intFromEnum(inst)].pl_node; const extra = file.zir.extraData(Zir.Inst.UnionInit, pl_node.payload_index); - var union_type: DocData.WalkResult = try self.walkRef( + const union_type: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1941,7 +1941,7 @@ fn walkInstruction( false, call_ctx, ); - var field_name: DocData.WalkResult = try self.walkRef( + const field_name: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1949,7 +1949,7 @@ fn walkInstruction( false, call_ctx, ); - var init: DocData.WalkResult = try self.walkRef( + const init: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1980,7 +1980,7 @@ fn walkInstruction( const pl_node = data[@intFromEnum(inst)].pl_node; const extra = file.zir.extraData(Zir.Inst.BuiltinCall, pl_node.payload_index); - var modifier: DocData.WalkResult = try self.walkRef( + const modifier: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1989,7 +1989,7 @@ fn walkInstruction( call_ctx, ); - var callee: DocData.WalkResult = try self.walkRef( + const callee: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -1998,7 +1998,7 @@ fn walkInstruction( call_ctx, ); - var args: DocData.WalkResult = try self.walkRef( + const args: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -2028,7 +2028,7 @@ fn walkInstruction( const pl_node = data[@intFromEnum(inst)].pl_node; const extra = file.zir.extraData(Zir.Inst.Bin, pl_node.payload_index); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -2036,7 +2036,7 @@ fn walkInstruction( false, call_ctx, ); - var rhs: DocData.WalkResult = try self.walkRef( + const rhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -2060,7 +2060,7 @@ fn walkInstruction( const pl_node = data[@intFromEnum(inst)].pl_node; const extra = file.zir.extraData(Zir.Inst.Bin, pl_node.payload_index); - var lhs: DocData.WalkResult = try self.walkRef( + const lhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -2068,7 +2068,7 @@ fn walkInstruction( false, call_ctx, ); - var rhs: DocData.WalkResult = try self.walkRef( + const rhs: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -2090,7 +2090,7 @@ fn walkInstruction( // .elem_type => { // const un_node = data[@intFromEnum(inst)].un_node; - // var operand: DocData.WalkResult = try self.walkRef( + // const operand: DocData.WalkResult = try self.walkRef( // file, // parent_scope, parent_src, // un_node.operand, @@ -2158,7 +2158,7 @@ fn walkInstruction( address_space = ref_result.expr; extra_index += 1; } - var bit_start: ?DocData.Expr = null; + const bit_start: ?DocData.Expr = null; if (ptr.flags.has_bit_range) { const ref = @as(Zir.Inst.Ref, @enumFromInt(file.zir.extra[extra_index])); const ref_result = try self.walkRef( @@ -2292,7 +2292,7 @@ fn walkInstruction( const array_data = try self.arena.alloc(usize, operands.len - 1); std.debug.assert(operands.len > 0); - var array_type = try self.walkRef( + const array_type = try self.walkRef( file, parent_scope, parent_src, @@ -2352,7 +2352,7 @@ fn walkInstruction( const array_data = try self.arena.alloc(usize, operands.len - 1); std.debug.assert(operands.len > 0); - var array_type = try self.walkRef( + const array_type = try self.walkRef( file, parent_scope, parent_src, @@ -2578,7 +2578,7 @@ fn walkInstruction( const pl_node = data[@intFromEnum(inst)].pl_node; const extra = file.zir.extraData(Zir.Inst.Block, pl_node.payload_index); const body = file.zir.extra[extra.end..][extra.data.body_len - 1]; - var operand: DocData.WalkResult = try self.walkRef( + const operand: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -2903,7 +2903,7 @@ fn walkInstruction( => { const un_node = data[@intFromEnum(inst)].un_node; - var operand: DocData.WalkResult = try self.walkRef( + const operand: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -2920,7 +2920,7 @@ fn walkInstruction( .struct_init_empty_ref_result => { const un_node = data[@intFromEnum(inst)].un_node; - var operand: DocData.WalkResult = try self.walkRef( + const operand: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -3937,7 +3937,7 @@ fn walkInstruction( try self.exprs.append(self.arena, last_type); const ptr_index = self.exprs.items.len; - var ptr: DocData.WalkResult = try self.walkRef( + const ptr: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -3948,7 +3948,7 @@ fn walkInstruction( try self.exprs.append(self.arena, ptr.expr); const expected_value_index = self.exprs.items.len; - var expected_value: DocData.WalkResult = try self.walkRef( + const expected_value: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -3959,7 +3959,7 @@ fn walkInstruction( try self.exprs.append(self.arena, expected_value.expr); const new_value_index = self.exprs.items.len; - var new_value: DocData.WalkResult = try self.walkRef( + const new_value: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -3970,7 +3970,7 @@ fn walkInstruction( try self.exprs.append(self.arena, new_value.expr); const success_order_index = self.exprs.items.len; - var success_order: DocData.WalkResult = try self.walkRef( + const success_order: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, @@ -3981,7 +3981,7 @@ fn walkInstruction( try self.exprs.append(self.arena, success_order.expr); const failure_order_index = self.exprs.items.len; - var failure_order: DocData.WalkResult = try self.walkRef( + const failure_order: DocData.WalkResult = try self.walkRef( file, parent_scope, parent_src, diff --git a/src/Compilation.zig b/src/Compilation.zig index 529ba9d33b..4917f40b29 100644 --- a/src/Compilation.zig +++ b/src/Compilation.zig @@ -1759,7 +1759,7 @@ pub fn create(gpa: Allocator, options: InitOptions) !*Compilation { const digest = hash.final(); const artifact_sub_dir = try std.fs.path.join(arena, &[_][]const u8{ "o", &digest }); - var artifact_dir = try options.local_cache_directory.handle.makeOpenPath(artifact_sub_dir, .{}); + const artifact_dir = try options.local_cache_directory.handle.makeOpenPath(artifact_sub_dir, .{}); owned_link_dir = artifact_dir; const link_artifact_directory: Directory = .{ .handle = artifact_dir, @@ -2173,7 +2173,7 @@ pub fn create(gpa: Allocator, options: InitOptions) !*Compilation { // LLD might drop some symbols as unused during LTO and GCing, therefore, // we force mark them for resolution here. - var tls_index_sym = switch (comp.getTarget().cpu.arch) { + const tls_index_sym = switch (comp.getTarget().cpu.arch) { .x86 => "__tls_index", else => "_tls_index", }; @@ -2576,7 +2576,7 @@ pub fn update(comp: *Compilation, main_progress_node: *std.Progress.Node) !void var artifact_dir = try comp.local_cache_directory.handle.openDir(o_sub_path, .{}); defer artifact_dir.close(); - var dir_path = try comp.local_cache_directory.join(comp.gpa, &.{o_sub_path}); + const dir_path = try comp.local_cache_directory.join(comp.gpa, &.{o_sub_path}); defer comp.gpa.free(dir_path); module.zig_cache_artifact_directory = .{ @@ -4961,7 +4961,7 @@ fn updateWin32Resource(comp: *Compilation, win32_resource: *Win32Resource, win32 var cli_diagnostics = resinator.cli.Diagnostics.init(comp.gpa); defer cli_diagnostics.deinit(); - var options = resinator.cli.parse(comp.gpa, resinator_args.items, &cli_diagnostics) catch |err| switch (err) { + const options = resinator.cli.parse(comp.gpa, resinator_args.items, &cli_diagnostics) catch |err| switch (err) { error.ParseError => { return comp.failWin32ResourceCli(win32_resource, &cli_diagnostics); }, @@ -5062,7 +5062,7 @@ fn updateWin32Resource(comp: *Compilation, win32_resource: *Win32Resource, win32 log.warn("failed to delete '{s}': {s}", .{ out_dep_path, @errorName(err) }); }; - var full_input = std.fs.cwd().readFileAlloc(arena, out_rcpp_path, std.math.maxInt(usize)) catch |err| switch (err) { + const full_input = std.fs.cwd().readFileAlloc(arena, out_rcpp_path, std.math.maxInt(usize)) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => |e| { return comp.failWin32Resource(win32_resource, "failed to read preprocessed file '{s}': {s}", .{ out_rcpp_path, @errorName(e) }); @@ -5072,7 +5072,7 @@ fn updateWin32Resource(comp: *Compilation, win32_resource: *Win32Resource, win32 var mapping_results = try resinator.source_mapping.parseAndRemoveLineCommands(arena, full_input, full_input, .{ .initial_filename = rc_src.src_path }); defer mapping_results.mappings.deinit(arena); - var final_input = resinator.comments.removeComments(mapping_results.result, mapping_results.result, &mapping_results.mappings); + const final_input = resinator.comments.removeComments(mapping_results.result, mapping_results.result, &mapping_results.mappings); var output_file = zig_cache_tmp_dir.createFile(out_res_path, .{}) catch |err| { return comp.failWin32Resource(win32_resource, "failed to create output file '{s}': {s}", .{ out_res_path, @errorName(err) }); diff --git a/src/Package/Fetch/git.zig b/src/Package/Fetch/git.zig index 1fdf5152d6..827b608cc6 100644 --- a/src/Package/Fetch/git.zig +++ b/src/Package/Fetch/git.zig @@ -83,7 +83,7 @@ pub const Repository = struct { ) !void { try repository.odb.seekOid(commit_oid); const tree_oid = tree_oid: { - var commit_object = try repository.odb.readObject(); + const commit_object = try repository.odb.readObject(); if (commit_object.type != .commit) return error.NotACommit; break :tree_oid try getCommitTree(commit_object.data); }; @@ -122,14 +122,14 @@ pub const Repository = struct { var file = try dir.createFile(entry.name, .{}); defer file.close(); try repository.odb.seekOid(entry.oid); - var file_object = try repository.odb.readObject(); + const file_object = try repository.odb.readObject(); if (file_object.type != .blob) return error.InvalidFile; try file.writeAll(file_object.data); try file.sync(); }, .symlink => { try repository.odb.seekOid(entry.oid); - var symlink_object = try repository.odb.readObject(); + const symlink_object = try repository.odb.readObject(); if (symlink_object.type != .blob) return error.InvalidFile; const link_name = symlink_object.data; dir.symLink(link_name, entry.name, .{}) catch |e| { @@ -1230,7 +1230,7 @@ fn resolveDeltaChain( const delta_offset = delta_offsets[i]; try pack.seekTo(delta_offset); const delta_header = try EntryHeader.read(pack.reader()); - var delta_data = try readObjectRaw(allocator, pack.reader(), delta_header.uncompressedLength()); + const delta_data = try readObjectRaw(allocator, pack.reader(), delta_header.uncompressedLength()); defer allocator.free(delta_data); var delta_stream = std.io.fixedBufferStream(delta_data); const delta_reader = delta_stream.reader(); @@ -1238,7 +1238,7 @@ fn resolveDeltaChain( const expanded_size = try readSizeVarInt(delta_reader); const expanded_alloc_size = std.math.cast(usize, expanded_size) orelse return error.ObjectTooLarge; - var expanded_data = try allocator.alloc(u8, expanded_alloc_size); + const expanded_data = try allocator.alloc(u8, expanded_alloc_size); errdefer allocator.free(expanded_data); var expanded_delta_stream = std.io.fixedBufferStream(expanded_data); var base_stream = std.io.fixedBufferStream(base_data); @@ -1259,7 +1259,7 @@ fn readObjectRaw(allocator: Allocator, reader: anytype, size: u64) ![]u8 { var buffered_reader = std.io.bufferedReader(reader); var decompress_stream = try std.compress.zlib.decompressStream(allocator, buffered_reader.reader()); defer decompress_stream.deinit(); - var data = try allocator.alloc(u8, alloc_size); + const data = try allocator.alloc(u8, alloc_size); errdefer allocator.free(data); try decompress_stream.reader().readNoEof(data); _ = decompress_stream.reader().readByte() catch |e| switch (e) { @@ -1290,14 +1290,14 @@ fn expandDelta(base_object: anytype, delta_reader: anytype, writer: anytype) !vo size2: bool, size3: bool, } = @bitCast(inst.value); - var offset_parts: packed struct { offset1: u8, offset2: u8, offset3: u8, offset4: u8 } = .{ + const offset_parts: packed struct { offset1: u8, offset2: u8, offset3: u8, offset4: u8 } = .{ .offset1 = if (available.offset1) try delta_reader.readByte() else 0, .offset2 = if (available.offset2) try delta_reader.readByte() else 0, .offset3 = if (available.offset3) try delta_reader.readByte() else 0, .offset4 = if (available.offset4) try delta_reader.readByte() else 0, }; const offset: u32 = @bitCast(offset_parts); - var size_parts: packed struct { size1: u8, size2: u8, size3: u8 } = .{ + const size_parts: packed struct { size1: u8, size2: u8, size3: u8 } = .{ .size1 = if (available.size1) try delta_reader.readByte() else 0, .size2 = if (available.size2) try delta_reader.readByte() else 0, .size3 = if (available.size3) try delta_reader.readByte() else 0, @@ -1414,7 +1414,7 @@ test "packfile indexing and checkout" { defer walker.deinit(); while (try walker.next()) |entry| { if (entry.kind != .file) continue; - var path = try testing.allocator.dupe(u8, entry.path); + const path = try testing.allocator.dupe(u8, entry.path); errdefer testing.allocator.free(path); mem.replaceScalar(u8, path, std.fs.path.sep, '/'); try actual_files.append(testing.allocator, path); diff --git a/src/Sema.zig b/src/Sema.zig index 9672f1bae0..d8f87f50e0 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -22899,7 +22899,7 @@ fn checkSimdBinOp( const rhs_ty = sema.typeOf(uncasted_rhs); try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src); - var vec_len: ?usize = if (lhs_ty.zigTypeTag(mod) == .Vector) lhs_ty.vectorLen(mod) else null; + const vec_len: ?usize = if (lhs_ty.zigTypeTag(mod) == .Vector) lhs_ty.vectorLen(mod) else null; const result_ty = try sema.resolvePeerTypes(block, src, &.{ uncasted_lhs, uncasted_rhs }, .{ .override = &[_]?LazySrcLoc{ lhs_src, rhs_src }, }); @@ -23286,8 +23286,8 @@ fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air const elem_ty = try sema.resolveType(block, elem_ty_src, extra.elem_type); try sema.checkVectorElemType(block, elem_ty_src, elem_ty); - var a = try sema.resolveInst(extra.a); - var b = try sema.resolveInst(extra.b); + const a = try sema.resolveInst(extra.a); + const b = try sema.resolveInst(extra.b); var mask = try sema.resolveInst(extra.mask); var mask_ty = sema.typeOf(mask); @@ -23328,7 +23328,7 @@ fn analyzeShuffle( .child = elem_ty.toIntern(), }); - var maybe_a_len = switch (sema.typeOf(a).zigTypeTag(mod)) { + const maybe_a_len = switch (sema.typeOf(a).zigTypeTag(mod)) { .Array, .Vector => sema.typeOf(a).arrayLen(mod), .Undefined => null, else => return sema.fail(block, a_src, "expected vector or array with element type '{}', found '{}'", .{ @@ -23336,7 +23336,7 @@ fn analyzeShuffle( sema.typeOf(a).fmt(sema.mod), }), }; - var maybe_b_len = switch (sema.typeOf(b).zigTypeTag(mod)) { + const maybe_b_len = switch (sema.typeOf(b).zigTypeTag(mod)) { .Array, .Vector => sema.typeOf(b).arrayLen(mod), .Undefined => null, else => return sema.fail(block, b_src, "expected vector or array with element type '{}', found '{}'", .{ @@ -23801,7 +23801,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError const call_src = inst_data.src(); const extra = sema.code.extraData(Zir.Inst.BuiltinCall, inst_data.payload_index).data; - var func = try sema.resolveInst(extra.callee); + const func = try sema.resolveInst(extra.callee); const modifier_ty = try sema.getBuiltinType("CallModifier"); const air_ref = try sema.resolveInst(extra.modifier); @@ -23859,7 +23859,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError return sema.fail(block, args_src, "expected a tuple, found '{}'", .{args_ty.fmt(sema.mod)}); } - var resolved_args: []Air.Inst.Ref = try sema.arena.alloc(Air.Inst.Ref, args_ty.structFieldCount(mod)); + const resolved_args: []Air.Inst.Ref = try sema.arena.alloc(Air.Inst.Ref, args_ty.structFieldCount(mod)); for (resolved_args, 0..) |*resolved, i| { resolved.* = try sema.tupleFieldValByIndex(block, args_src, args, @intCast(i), args_ty); } @@ -33274,8 +33274,8 @@ fn resolvePeerTypes( else => {}, } - var peer_tys = try sema.arena.alloc(?Type, instructions.len); - var peer_vals = try sema.arena.alloc(?Value, instructions.len); + const peer_tys = try sema.arena.alloc(?Type, instructions.len); + const peer_vals = try sema.arena.alloc(?Value, instructions.len); for (instructions, peer_tys, peer_vals) |inst, *ty, *val| { ty.* = sema.typeOf(inst); diff --git a/src/arch/riscv64/CodeGen.zig b/src/arch/riscv64/CodeGen.zig index 0e56a1cda1..c52fc33915 100644 --- a/src/arch/riscv64/CodeGen.zig +++ b/src/arch/riscv64/CodeGen.zig @@ -2648,6 +2648,11 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues { // conventions var next_register: usize = 0; var next_stack_offset: u32 = 0; + // TODO: this is never assigned, which is a bug, but I don't know how this code works + // well enough to try and fix it. I *think* `next_register += next_stack_offset` is + // supposed to be `next_stack_offset += param_size` in every case where it appears. + _ = &next_stack_offset; + const argument_registers = [_]Register{ .a0, .a1, .a2, .a3, .a4, .a5, .a6, .a7 }; for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| { diff --git a/src/arch/sparc64/CodeGen.zig b/src/arch/sparc64/CodeGen.zig index 40f134ec90..be624c8d95 100644 --- a/src/arch/sparc64/CodeGen.zig +++ b/src/arch/sparc64/CodeGen.zig @@ -4481,6 +4481,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView) var next_register: usize = 0; var next_stack_offset: u32 = 0; + // TODO: this is never assigned, which is a bug, but I don't know how this code works + // well enough to try and fix it. I *think* `next_register += next_stack_offset` is + // supposed to be `next_stack_offset += param_size` in every case where it appears. + _ = &next_stack_offset; // The caller puts the argument in %o0-%o5, which becomes %i0-%i5 inside the callee. const argument_registers = switch (role) { diff --git a/src/arch/wasm/CodeGen.zig b/src/arch/wasm/CodeGen.zig index 7c752490c6..da0226b54c 100644 --- a/src/arch/wasm/CodeGen.zig +++ b/src/arch/wasm/CodeGen.zig @@ -2139,7 +2139,7 @@ fn airRetPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void { const mod = func.bin_file.base.options.module.?; const child_type = func.typeOfIndex(inst).childType(mod); - var result = result: { + const result = result: { if (!child_type.isFnOrHasRuntimeBitsIgnoreComptime(mod)) { break :result try func.allocStack(Type.usize); // create pointer to void } @@ -5001,7 +5001,7 @@ fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void { return func.finishAir(inst, try WValue.toLocal(.stack, func, elem_ty), &.{ bin_op.lhs, bin_op.rhs }); }, else => { - var stack_vec = try func.allocStack(array_ty); + const stack_vec = try func.allocStack(array_ty); try func.store(stack_vec, array, array_ty, 0); // Is a non-unrolled vector (v128) @@ -5944,7 +5944,7 @@ fn airAddSubWithOverflow(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerErro rhs.free(func); }; - var bin_op = try (try func.binOp(lhs, rhs, lhs_ty, op)).toLocal(func, lhs_ty); + const bin_op = try (try func.binOp(lhs, rhs, lhs_ty, op)).toLocal(func, lhs_ty); var result = if (wasm_bits != int_info.bits) blk: { break :blk try (try func.wrapOperand(bin_op, lhs_ty)).toLocal(func, lhs_ty); } else bin_op; @@ -6335,7 +6335,7 @@ fn airMulAdd(func: *CodeGen, inst: Air.Inst.Index) InnerError!void { const lhs_ext = try func.fpext(lhs, ty, Type.f32); const addend_ext = try func.fpext(addend, ty, Type.f32); // call to compiler-rt `fn fmaf(f32, f32, f32) f32` - var result = try func.callIntrinsic( + const result = try func.callIntrinsic( "fmaf", &.{ .f32_type, .f32_type, .f32_type }, Type.f32, diff --git a/src/arch/x86_64/CodeGen.zig b/src/arch/x86_64/CodeGen.zig index 822ff0ec2d..ed3863462b 100644 --- a/src/arch/x86_64/CodeGen.zig +++ b/src/arch/x86_64/CodeGen.zig @@ -2181,7 +2181,7 @@ fn genLazy(self: *Self, lazy_sym: link.File.LazySymbol) InnerError!void { const ret_reg = param_regs[0]; const enum_mcv = MCValue{ .register = param_regs[1] }; - var exitlude_jump_relocs = try self.gpa.alloc(Mir.Inst.Index, enum_ty.enumFieldCount(mod)); + const exitlude_jump_relocs = try self.gpa.alloc(Mir.Inst.Index, enum_ty.enumFieldCount(mod)); defer self.gpa.free(exitlude_jump_relocs); const data_reg = try self.register_manager.allocReg(null, abi.RegisterClass.gp); diff --git a/src/arch/x86_64/Disassembler.zig b/src/arch/x86_64/Disassembler.zig index b15327fd21..e0117fa17b 100644 --- a/src/arch/x86_64/Disassembler.zig +++ b/src/arch/x86_64/Disassembler.zig @@ -234,13 +234,12 @@ fn inst(encoding: Encoding, args: struct { op3: Instruction.Operand = .none, op4: Instruction.Operand = .none, }) Instruction { - var i = Instruction{ .encoding = encoding, .prefix = args.prefix, .ops = .{ + return .{ .encoding = encoding, .prefix = args.prefix, .ops = .{ args.op1, args.op2, args.op3, args.op4, } }; - return i; } const Prefixes = struct { diff --git a/src/arch/x86_64/Lower.zig b/src/arch/x86_64/Lower.zig index b26cbe1503..0c309991f6 100644 --- a/src/arch/x86_64/Lower.zig +++ b/src/arch/x86_64/Lower.zig @@ -342,7 +342,7 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand) .Lib => lower.bin_file.options.link_mode == .Static, }; - var emit_prefix = prefix; + const emit_prefix = prefix; var emit_mnemonic = mnemonic; var emit_ops_storage: [4]Operand = undefined; const emit_ops = emit_ops_storage[0..ops.len]; diff --git a/src/arch/x86_64/encoder.zig b/src/arch/x86_64/encoder.zig index 517dd1af8d..b499ccfdca 100644 --- a/src/arch/x86_64/encoder.zig +++ b/src/arch/x86_64/encoder.zig @@ -244,7 +244,7 @@ pub const Instruction = struct { }), }, .imm => |imm| if (enc_op.isSigned()) { - var imms = imm.asSigned(enc_op.immBitSize()); + const imms = imm.asSigned(enc_op.immBitSize()); if (imms < 0) try writer.writeByte('-'); try writer.print("0x{x}", .{@abs(imms)}); } else try writer.print("0x{x}", .{imm.asUnsigned(enc_op.immBitSize())}), @@ -1077,7 +1077,7 @@ fn expectEqualHexStrings(expected: []const u8, given: []const u8, assembly: []co const given_fmt = try std.fmt.allocPrint(testing.allocator, "{x}", .{std.fmt.fmtSliceHexLower(given)}); defer testing.allocator.free(given_fmt); const idx = std.mem.indexOfDiff(u8, expected_fmt, given_fmt).?; - var padding = try testing.allocator.alloc(u8, idx + 5); + const padding = try testing.allocator.alloc(u8, idx + 5); defer testing.allocator.free(padding); @memset(padding, ' '); std.debug.print("\nASM: {s}\nEXP: {s}\nGIV: {s}\n{s}^ -- first differing byte\n", .{ diff --git a/src/aro_translate_c.zig b/src/aro_translate_c.zig index a13867be30..cd9e4fa5cb 100644 --- a/src/aro_translate_c.zig +++ b/src/aro_translate_c.zig @@ -346,7 +346,7 @@ fn transFnDecl(c: *Context, fn_decl: NodeIndex) Error!void { defer block_scope.deinit(); var scope = &block_scope.base; - _ = scope; + _ = &scope; var param_id: c_uint = 0; for (proto_payload.data.params, fn_ty.data.func.params) |*param, param_info| { @@ -534,7 +534,7 @@ fn transFnType( ctx: FnProtoContext, ) !ZigNode { const param_count: usize = fn_ty.data.func.params.len; - var fn_params = try c.arena.alloc(ast.Payload.Param, param_count); + const fn_params = try c.arena.alloc(ast.Payload.Param, param_count); for (fn_ty.data.func.params, fn_params) |param_info, *param_node| { const param_ty = param_info.ty; diff --git a/src/codegen.zig b/src/codegen.zig index 94f1f6ea0e..c624998e7b 100644 --- a/src/codegen.zig +++ b/src/codegen.zig @@ -368,7 +368,7 @@ pub fn generateSymbol( .bytes => |bytes| try code.appendSlice(bytes), .elems, .repeated_elem => { var index: u64 = 0; - var len_including_sentinel = + const len_including_sentinel = array_type.len + @intFromBool(array_type.sentinel != .none); while (index < len_including_sentinel) : (index += 1) { switch (try generateSymbol(bin_file, src_loc, .{ diff --git a/src/codegen/llvm/BitcodeReader.zig b/src/codegen/llvm/BitcodeReader.zig index 3232d58608..668e610a69 100644 --- a/src/codegen/llvm/BitcodeReader.zig +++ b/src/codegen/llvm/BitcodeReader.zig @@ -410,7 +410,7 @@ fn readVbr(bc: *BitcodeReader, comptime T: type, bits: u7) !T { var result: u64 = 0; var shift: u6 = 0; while (true) { - var chunk = try bc.readFixed(u64, bits); + const chunk = try bc.readFixed(u64, bits); result |= (chunk & (chunk_msb - 1)) << shift; if (chunk & chunk_msb == 0) break; shift += chunk_bits; diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index dcb3329c57..8bee639b60 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -1284,7 +1284,7 @@ const DeclGen = struct { const elem_ty = ty.childType(mod); const elem_ty_ref = try self.resolveType(elem_ty, .indirect); - var total_len = std.math.cast(u32, ty.arrayLenIncludingSentinel(mod)) orelse { + const total_len = std.math.cast(u32, ty.arrayLenIncludingSentinel(mod)) orelse { return self.fail("array type of {} elements is too large", .{ty.arrayLenIncludingSentinel(mod)}); }; const ty_ref = if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) blk: { @@ -2115,7 +2115,7 @@ const DeclGen = struct { const child_ty = ty.childType(mod); const vector_len = ty.vectorLen(mod); - var constituents = try self.gpa.alloc(IdRef, vector_len); + const constituents = try self.gpa.alloc(IdRef, vector_len); defer self.gpa.free(constituents); for (constituents, 0..) |*constituent, i| { @@ -2312,7 +2312,7 @@ const DeclGen = struct { if (ty.isVector(mod)) { const child_ty = ty.childType(mod); const vector_len = ty.vectorLen(mod); - var constituents = try self.gpa.alloc(IdRef, vector_len); + const constituents = try self.gpa.alloc(IdRef, vector_len); defer self.gpa.free(constituents); for (constituents, 0..) |*constituent, i| { @@ -2727,7 +2727,7 @@ const DeclGen = struct { const child_ty = ty.childType(mod); const vector_len = ty.vectorLen(mod); - var constituents = try self.gpa.alloc(IdRef, vector_len); + const constituents = try self.gpa.alloc(IdRef, vector_len); defer self.gpa.free(constituents); for (constituents, 0..) |*constituent, i| { diff --git a/src/link/C.zig b/src/link/C.zig index 40dfc0771d..f97f19f85b 100644 --- a/src/link/C.zig +++ b/src/link/C.zig @@ -103,7 +103,7 @@ pub fn openPath(gpa: Allocator, sub_path: []const u8, options: link.Options) !*C }); errdefer file.close(); - var c_file = try gpa.create(C); + const c_file = try gpa.create(C); errdefer gpa.destroy(c_file); c_file.* = .{ diff --git a/src/link/Coff.zig b/src/link/Coff.zig index 0d26e24b2d..16736ab1af 100644 --- a/src/link/Coff.zig +++ b/src/link/Coff.zig @@ -563,7 +563,7 @@ fn allocateAtom(self: *Coff, atom_index: Atom.Index, new_atom_size: u32, alignme // First we look for an appropriately sized free list node. // The list is unordered. We'll just take the first thing that works. - var vaddr = blk: { + const vaddr = blk: { var i: usize = 0; while (i < free_list.items.len) { const big_atom_index = free_list.items[i]; @@ -815,7 +815,7 @@ fn writeAtom(self: *Coff, atom_index: Atom.Index, code: []u8) !void { } fn debugMem(allocator: Allocator, handle: std.ChildProcess.Id, pvaddr: std.os.windows.LPVOID, code: []const u8) !void { - var buffer = try allocator.alloc(u8, code.len); + const buffer = try allocator.alloc(u8, code.len); defer allocator.free(buffer); const memread = try std.os.windows.ReadProcessMemory(handle, pvaddr, buffer); log.debug("to write: {x}", .{std.fmt.fmtSliceHexLower(code)}); @@ -1071,7 +1071,7 @@ pub fn updateFunc(self: *Coff, mod: *Module, func_index: InternPool.Index, air: &code_buffer, .none, ); - var code = switch (res) { + const code = switch (res) { .ok => code_buffer.items, .fail => |em| { decl.analysis = .codegen_failure; @@ -1132,7 +1132,7 @@ fn lowerConst(self: *Coff, name: []const u8, tv: TypedValue, required_alignment: const res = try codegen.generateSymbol(&self.base, src_loc, tv, &code_buffer, .none, .{ .parent_atom_index = self.getAtom(atom_index).getSymbolIndex().?, }); - var code = switch (res) { + const code = switch (res) { .ok => code_buffer.items, .fail => |em| return .{ .fail = em }, }; @@ -1196,7 +1196,7 @@ pub fn updateDecl( }, &code_buffer, .none, .{ .parent_atom_index = atom.getSymbolIndex().?, }); - var code = switch (res) { + const code = switch (res) { .ok => code_buffer.items, .fail => |em| { decl.analysis = .codegen_failure; diff --git a/src/link/Dwarf.zig b/src/link/Dwarf.zig index 385f09c2fc..8c889fa30d 100644 --- a/src/link/Dwarf.zig +++ b/src/link/Dwarf.zig @@ -303,7 +303,7 @@ pub const DeclState = struct { // DW.AT.name, DW.FORM.string try dbg_info_buffer.writer().print("{d}\x00", .{field_index}); // DW.AT.type, DW.FORM.ref4 - var index = dbg_info_buffer.items.len; + const index = dbg_info_buffer.items.len; try dbg_info_buffer.resize(index + 4); try self.addTypeRelocGlobal(atom_index, field_ty.toType(), @intCast(index)); // DW.AT.data_member_location, DW.FORM.udata @@ -329,7 +329,7 @@ pub const DeclState = struct { // DW.AT.name, DW.FORM.string try dbg_info_buffer.writer().print("{d}\x00", .{field_index}); // DW.AT.type, DW.FORM.ref4 - var index = dbg_info_buffer.items.len; + const index = dbg_info_buffer.items.len; try dbg_info_buffer.resize(index + 4); try self.addTypeRelocGlobal(atom_index, field_ty.toType(), @intCast(index)); // DW.AT.data_member_location, DW.FORM.udata @@ -350,7 +350,7 @@ pub const DeclState = struct { dbg_info_buffer.appendSliceAssumeCapacity(field_name); dbg_info_buffer.appendAssumeCapacity(0); // DW.AT.type, DW.FORM.ref4 - var index = dbg_info_buffer.items.len; + const index = dbg_info_buffer.items.len; try dbg_info_buffer.resize(index + 4); try self.addTypeRelocGlobal(atom_index, field_ty.toType(), @intCast(index)); // DW.AT.data_member_location, DW.FORM.udata diff --git a/src/link/Elf.zig b/src/link/Elf.zig index 3883f76268..e64ad222ad 100644 --- a/src/link/Elf.zig +++ b/src/link/Elf.zig @@ -967,7 +967,7 @@ pub fn flushModule(self: *Elf, comp: *Compilation, prog_node: *std.Progress.Node // --verbose-link if (self.base.options.verbose_link) try self.dumpArgv(comp); - var csu = try CsuObjects.init(arena, self.base.options, comp); + const csu = try CsuObjects.init(arena, self.base.options, comp); const compiler_rt_path: ?[]const u8 = blk: { if (comp.compiler_rt_lib) |x| break :blk x.full_object_path; if (comp.compiler_rt_obj) |x| break :blk x.full_object_path; @@ -1493,7 +1493,7 @@ fn dumpArgv(self: *Elf, comp: *Compilation) !void { } else null; const gc_sections = self.base.options.gc_sections orelse false; - var csu = try CsuObjects.init(arena, self.base.options, comp); + const csu = try CsuObjects.init(arena, self.base.options, comp); const compiler_rt_path: ?[]const u8 = blk: { if (comp.compiler_rt_lib) |x| break :blk x.full_object_path; if (comp.compiler_rt_obj) |x| break :blk x.full_object_path; @@ -2599,7 +2599,7 @@ fn linkWithLLD(self: *Elf, comp: *Compilation, prog_node: *std.Progress.Node) !v try argv.append(full_out_path); // csu prelude - var csu = try CsuObjects.init(arena, self.base.options, comp); + const csu = try CsuObjects.init(arena, self.base.options, comp); if (csu.crt0) |v| try argv.append(v); if (csu.crti) |v| try argv.append(v); if (csu.crtbegin) |v| try argv.append(v); @@ -3852,7 +3852,7 @@ fn sortPhdrs(self: *Elf) error{OutOfMemory}!void { backlinks[entry.phndx] = @as(u16, @intCast(i)); } - var slice = try self.phdrs.toOwnedSlice(gpa); + const slice = try self.phdrs.toOwnedSlice(gpa); defer gpa.free(slice); try self.phdrs.ensureTotalCapacityPrecise(gpa, slice.len); @@ -3957,7 +3957,7 @@ fn sortShdrs(self: *Elf) !void { backlinks[entry.shndx] = @as(u16, @intCast(i)); } - var slice = try self.shdrs.toOwnedSlice(gpa); + const slice = try self.shdrs.toOwnedSlice(gpa); defer gpa.free(slice); try self.shdrs.ensureTotalCapacityPrecise(gpa, slice.len); diff --git a/src/link/Elf/eh_frame.zig b/src/link/Elf/eh_frame.zig index 73857d03d2..1d24285b30 100644 --- a/src/link/Elf/eh_frame.zig +++ b/src/link/Elf/eh_frame.zig @@ -217,7 +217,7 @@ pub const Iterator = struct { var stream = std.io.fixedBufferStream(it.data[it.pos..]); const reader = stream.reader(); - var size = try reader.readInt(u32, .little); + const size = try reader.readInt(u32, .little); if (size == 0xFFFFFFFF) @panic("TODO"); const id = try reader.readInt(u32, .little); diff --git a/src/link/MachO.zig b/src/link/MachO.zig index f0938a3c19..67c9aaac05 100644 --- a/src/link/MachO.zig +++ b/src/link/MachO.zig @@ -2252,7 +2252,7 @@ pub fn updateFunc(self: *MachO, mod: *Module, func_index: InternPool.Index, air: else try codegen.generateFunction(&self.base, decl.srcLoc(mod), func_index, air, liveness, &code_buffer, .none); - var code = switch (res) { + const code = switch (res) { .ok => code_buffer.items, .fail => |em| { decl.analysis = .codegen_failure; @@ -2332,7 +2332,7 @@ fn lowerConst( const res = try codegen.generateSymbol(&self.base, src_loc, tv, &code_buffer, .none, .{ .parent_atom_index = self.getAtom(atom_index).getSymbolIndex().?, }); - var code = switch (res) { + const code = switch (res) { .ok => code_buffer.items, .fail => |em| return .{ .fail = em }, }; @@ -2418,7 +2418,7 @@ pub fn updateDecl(self: *MachO, mod: *Module, decl_index: Module.Decl.Index) !vo .parent_atom_index = sym_index, }); - var code = switch (res) { + const code = switch (res) { .ok => code_buffer.items, .fail => |em| { decl.analysis = .codegen_failure; @@ -2587,7 +2587,7 @@ fn updateThreadlocalVariable(self: *MachO, module: *Module, decl_index: Module.D .parent_atom_index = init_sym_index, }); - var code = switch (res) { + const code = switch (res) { .ok => code_buffer.items, .fail => |em| { decl.analysis = .codegen_failure; @@ -3427,7 +3427,7 @@ fn allocateAtom(self: *MachO, atom_index: Atom.Index, new_atom_size: u64, alignm // First we look for an appropriately sized free list node. // The list is unordered. We'll just take the first thing that works. - var vaddr = blk: { + const vaddr = blk: { var i: usize = 0; while (i < free_list.items.len) { const big_atom_index = free_list.items[i]; @@ -3971,7 +3971,7 @@ fn writeDyldInfoData(self: *MachO) !void { link_seg.filesize = needed_size; assert(mem.isAlignedGeneric(u64, link_seg.fileoff + link_seg.filesize, @alignOf(u64))); - var buffer = try gpa.alloc(u8, needed_size); + const buffer = try gpa.alloc(u8, needed_size); defer gpa.free(buffer); @memset(buffer, 0); @@ -5228,7 +5228,7 @@ fn reportMissingLibraryError( ) error{OutOfMemory}!void { const gpa = self.base.allocator; try self.misc_errors.ensureUnusedCapacity(gpa, 1); - var notes = try gpa.alloc(File.ErrorMsg, checked_paths.len); + const notes = try gpa.alloc(File.ErrorMsg, checked_paths.len); errdefer gpa.free(notes); for (checked_paths, notes) |path, *note| { note.* = .{ .msg = try std.fmt.allocPrint(gpa, "tried {s}", .{path}) }; diff --git a/src/link/MachO/Archive.zig b/src/link/MachO/Archive.zig index 6bdc6d916d..ba3915f51b 100644 --- a/src/link/MachO/Archive.zig +++ b/src/link/MachO/Archive.zig @@ -98,7 +98,7 @@ pub fn parse(self: *Archive, allocator: Allocator, reader: anytype) !void { _ = try reader.readBytesNoEof(SARMAG); self.header = try reader.readStruct(ar_hdr); const name_or_length = try self.header.nameOrLength(); - var embedded_name = try parseName(allocator, name_or_length, reader); + const embedded_name = try parseName(allocator, name_or_length, reader); log.debug("parsing archive '{s}' at '{s}'", .{ embedded_name, self.name }); defer allocator.free(embedded_name); @@ -124,7 +124,7 @@ fn parseName(allocator: Allocator, name_or_length: ar_hdr.NameOrLength, reader: fn parseTableOfContents(self: *Archive, allocator: Allocator, reader: anytype) !void { const symtab_size = try reader.readInt(u32, .little); - var symtab = try allocator.alloc(u8, symtab_size); + const symtab = try allocator.alloc(u8, symtab_size); defer allocator.free(symtab); reader.readNoEof(symtab) catch { @@ -133,7 +133,7 @@ fn parseTableOfContents(self: *Archive, allocator: Allocator, reader: anytype) ! }; const strtab_size = try reader.readInt(u32, .little); - var strtab = try allocator.alloc(u8, strtab_size); + const strtab = try allocator.alloc(u8, strtab_size); defer allocator.free(strtab); reader.readNoEof(strtab) catch { diff --git a/src/link/MachO/Dylib.zig b/src/link/MachO/Dylib.zig index 91411dc572..65d503b1ae 100644 --- a/src/link/MachO/Dylib.zig +++ b/src/link/MachO/Dylib.zig @@ -167,7 +167,7 @@ pub fn parseFromBinary( .REEXPORT_DYLIB => { if (should_lookup_reexports) { // Parse install_name to dependent dylib. - var id = try Id.fromLoadCommand( + const id = try Id.fromLoadCommand( allocator, cmd.cast(macho.dylib_command).?, cmd.getDylibPathName(), @@ -410,7 +410,7 @@ pub fn parseFromStub( log.debug(" (found re-export '{s}')", .{lib}); - var dep_id = try Id.default(allocator, lib); + const dep_id = try Id.default(allocator, lib); try dependent_libs.writeItem(.{ .id = dep_id, .parent = dylib_id }); } } @@ -527,7 +527,7 @@ pub fn parseFromStub( log.debug(" (found re-export '{s}')", .{lib}); - var dep_id = try Id.default(allocator, lib); + const dep_id = try Id.default(allocator, lib); try dependent_libs.writeItem(.{ .id = dep_id, .parent = dylib_id }); } } diff --git a/src/link/MachO/Trie.zig b/src/link/MachO/Trie.zig index d86338f84b..98add0315c 100644 --- a/src/link/MachO/Trie.zig +++ b/src/link/MachO/Trie.zig @@ -150,7 +150,7 @@ pub fn deinit(self: *Trie, allocator: Allocator) void { } test "Trie node count" { - var gpa = testing.allocator; + const gpa = testing.allocator; var trie: Trie = .{}; defer trie.deinit(gpa); try trie.init(gpa); @@ -196,7 +196,7 @@ test "Trie node count" { } test "Trie basic" { - var gpa = testing.allocator; + const gpa = testing.allocator; var trie: Trie = .{}; defer trie.deinit(gpa); try trie.init(gpa); @@ -254,7 +254,7 @@ fn expectEqualHexStrings(expected: []const u8, given: []const u8) !void { const given_fmt = try std.fmt.allocPrint(testing.allocator, "{x}", .{std.fmt.fmtSliceHexLower(given)}); defer testing.allocator.free(given_fmt); const idx = mem.indexOfDiff(u8, expected_fmt, given_fmt).?; - var padding = try testing.allocator.alloc(u8, idx + 5); + const padding = try testing.allocator.alloc(u8, idx + 5); defer testing.allocator.free(padding); @memset(padding, ' '); std.debug.print("\nEXP: {s}\nGIV: {s}\n{s}^ -- first differing byte\n", .{ expected_fmt, given_fmt, padding }); @@ -292,7 +292,7 @@ test "write Trie to a byte stream" { 0x3, 0x0, 0x80, 0x20, 0x0, // terminal node }; - var buffer = try gpa.alloc(u8, trie.size); + const buffer = try gpa.alloc(u8, trie.size); defer gpa.free(buffer); var stream = std.io.fixedBufferStream(buffer); { @@ -331,7 +331,7 @@ test "parse Trie from byte stream" { try trie.finalize(gpa); - var out_buffer = try gpa.alloc(u8, trie.size); + const out_buffer = try gpa.alloc(u8, trie.size); defer gpa.free(out_buffer); var out_stream = std.io.fixedBufferStream(out_buffer); _ = try trie.write(out_stream.writer()); @@ -362,7 +362,7 @@ test "ordering bug" { 0x00, 0x12, 0x03, 0x00, 0xD8, 0x0A, 0x00, }; - var buffer = try gpa.alloc(u8, trie.size); + const buffer = try gpa.alloc(u8, trie.size); defer gpa.free(buffer); var stream = std.io.fixedBufferStream(buffer); // Writing finalized trie again should yield the same result. @@ -426,7 +426,7 @@ pub const Node = struct { // To: A -> C -> B const mid = try allocator.create(Node); mid.* = .{ .base = self.base }; - var to_label = try allocator.dupe(u8, edge.label[match..]); + const to_label = try allocator.dupe(u8, edge.label[match..]); allocator.free(edge.label); const to_node = edge.to; edge.to = mid; @@ -573,7 +573,7 @@ pub const Node = struct { /// Updates offset of this node in the output byte stream. fn finalize(self: *Node, offset_in_trie: u64) !FinalizeResult { var stream = std.io.countingWriter(std.io.null_writer); - var writer = stream.writer(); + const writer = stream.writer(); var node_size: u64 = 0; if (self.terminal_info) |info| { diff --git a/src/link/MachO/UnwindInfo.zig b/src/link/MachO/UnwindInfo.zig index c588b65ea3..be6c9dbb34 100644 --- a/src/link/MachO/UnwindInfo.zig +++ b/src/link/MachO/UnwindInfo.zig @@ -417,7 +417,7 @@ pub fn collect(info: *UnwindInfo, macho_file: *MachO) !void { gop.value_ptr.count += 1; } - var slice = common_encodings_counts.values(); + const slice = common_encodings_counts.values(); mem.sort(CommonEncWithCount, slice, {}, CommonEncWithCount.greaterThan); var i: u7 = 0; diff --git a/src/link/MachO/eh_frame.zig b/src/link/MachO/eh_frame.zig index 189d9b25cd..0f021a569c 100644 --- a/src/link/MachO/eh_frame.zig +++ b/src/link/MachO/eh_frame.zig @@ -586,7 +586,7 @@ pub const Iterator = struct { var stream = std.io.fixedBufferStream(it.data[it.pos..]); const reader = stream.reader(); - var size = try reader.readInt(u32, .little); + const size = try reader.readInt(u32, .little); if (size == 0xFFFFFFFF) { log.debug("MachO doesn't support 64bit DWARF CFI __eh_frame records", .{}); return error.BadDwarfCfi; diff --git a/src/link/MachO/load_commands.zig b/src/link/MachO/load_commands.zig index 669e806728..f064415739 100644 --- a/src/link/MachO/load_commands.zig +++ b/src/link/MachO/load_commands.zig @@ -112,7 +112,7 @@ pub fn calcMinHeaderPad(gpa: Allocator, options: *const link.Options, ctx: CalcL log.debug("minimum requested headerpad size 0x{x}", .{padding + @sizeOf(macho.mach_header_64)}); if (options.headerpad_max_install_names) { - var min_headerpad_size: u32 = try calcLCsSize(gpa, options, ctx, true); + const min_headerpad_size: u32 = try calcLCsSize(gpa, options, ctx, true); log.debug("headerpad_max_install_names minimum headerpad size 0x{x}", .{ min_headerpad_size + @sizeOf(macho.mach_header_64), }); diff --git a/src/link/MachO/zld.zig b/src/link/MachO/zld.zig index 79433b3b1b..e627b91f11 100644 --- a/src/link/MachO/zld.zig +++ b/src/link/MachO/zld.zig @@ -503,7 +503,7 @@ pub fn linkWithZld( const size = math.cast(usize, linkedit.fileoff - start) orelse return error.Overflow; if (size > 0) { log.debug("zeroing out zerofill area of length {x} at {x}", .{ size, start }); - var padding = try gpa.alloc(u8, size); + const padding = try gpa.alloc(u8, size); defer gpa.free(padding); @memset(padding, 0); try macho_file.base.file.?.pwriteAll(padding, start); diff --git a/src/link/Plan9.zig b/src/link/Plan9.zig index d8b6f39f76..4221aa7dee 100644 --- a/src/link/Plan9.zig +++ b/src/link/Plan9.zig @@ -300,7 +300,7 @@ pub fn createEmpty(gpa: Allocator, options: link.Options) !*Plan9 { else => return error.UnsupportedP9Architecture, }; - var arena_allocator = std.heap.ArenaAllocator.init(gpa); + const arena_allocator = std.heap.ArenaAllocator.init(gpa); const self = try gpa.create(Plan9); self.* = .{ @@ -467,7 +467,7 @@ pub fn lowerUnnamedConst(self: *Plan9, tv: TypedValue, decl_index: Module.Decl.I const sym_index = try self.allocateSymbolIndex(); const new_atom_idx = try self.createAtom(); - var info: Atom = .{ + const info: Atom = .{ .type = .d, .offset = null, .sym_index = sym_index, @@ -496,7 +496,7 @@ pub fn lowerUnnamedConst(self: *Plan9, tv: TypedValue, decl_index: Module.Decl.I }, }; // duped_code is freed when the unnamed const is freed - var duped_code = try self.base.allocator.dupe(u8, code); + const duped_code = try self.base.allocator.dupe(u8, code); errdefer self.base.allocator.free(duped_code); const new_atom = self.getAtomPtr(new_atom_idx); new_atom.* = info; @@ -1024,7 +1024,7 @@ pub fn freeDecl(self: *Plan9, decl_index: Module.Decl.Index) void { const decl = mod.declPtr(decl_index); const is_fn = decl.val.isFuncBody(mod); if (is_fn) { - var symidx_and_submap = self.fn_decl_table.get(decl.getFileScope(mod)).?; + const symidx_and_submap = self.fn_decl_table.get(decl.getFileScope(mod)).?; var submap = symidx_and_submap.functions; if (submap.fetchSwapRemove(decl_index)) |removed_entry| { self.base.allocator.free(removed_entry.value.code); @@ -1204,7 +1204,7 @@ fn updateLazySymbolAtom(self: *Plan9, sym: File.LazySymbol, atom_index: Atom.Ind }, }; // duped_code is freed when the atom is freed - var duped_code = try self.base.allocator.dupe(u8, code); + const duped_code = try self.base.allocator.dupe(u8, code); errdefer self.base.allocator.free(duped_code); self.getAtomPtr(atom_index).code = .{ .code_ptr = duped_code.ptr, @@ -1489,7 +1489,7 @@ pub fn lowerAnonDecl(self: *Plan9, decl_val: InternPool.Index, src_loc: Module.S // to put it in some location. // ... const gpa = self.base.allocator; - var gop = try self.anon_decls.getOrPut(gpa, decl_val); + const gop = try self.anon_decls.getOrPut(gpa, decl_val); const mod = self.base.options.module.?; if (!gop.found_existing) { const ty = mod.intern_pool.typeOf(decl_val).toType(); diff --git a/src/link/Wasm.zig b/src/link/Wasm.zig index 2677184c12..da8753ac29 100644 --- a/src/link/Wasm.zig +++ b/src/link/Wasm.zig @@ -860,7 +860,7 @@ fn resolveSymbolsInArchives(wasm: *Wasm) !void { // Parse object and and resolve symbols again before we check remaining // undefined symbols. const object_file_index = @as(u16, @intCast(wasm.objects.items.len)); - var object = try archive.parseObject(wasm.base.allocator, offset.items[0]); + const object = try archive.parseObject(wasm.base.allocator, offset.items[0]); try wasm.objects.append(wasm.base.allocator, object); try wasm.resolveSymbolsInObject(object_file_index); @@ -1344,7 +1344,7 @@ pub fn deinit(wasm: *Wasm) void { /// Will re-use slots when a symbol was freed at an earlier stage. pub fn allocateSymbol(wasm: *Wasm) !u32 { try wasm.symbols.ensureUnusedCapacity(wasm.base.allocator, 1); - var symbol: Symbol = .{ + const symbol: Symbol = .{ .name = std.math.maxInt(u32), // will be set after updateDecl as well as during atom creation for decls .flags = @intFromEnum(Symbol.Flag.WASM_SYM_BINDING_LOCAL), .tag = .undefined, // will be set after updateDecl @@ -1655,7 +1655,7 @@ pub fn getGlobalSymbol(wasm: *Wasm, name: []const u8, lib_name: ?[]const u8) !u3 symbol.setUndefined(true); const sym_index = if (wasm.symbols_free_list.popOrNull()) |index| index else blk: { - var index = @as(u32, @intCast(wasm.symbols.items.len)); + const index: u32 = @intCast(wasm.symbols.items.len); try wasm.symbols.ensureUnusedCapacity(wasm.base.allocator, 1); wasm.symbols.items.len += 1; break :blk index; @@ -2632,7 +2632,7 @@ fn setupImports(wasm: *Wasm) !void { // We copy the import to a new import to ensure the names contain references // to the internal string table, rather than of the object file. - var new_imp: types.Import = .{ + const new_imp: types.Import = .{ .module_name = try wasm.string_table.put(wasm.base.allocator, object.string_table.get(import.module_name)), .name = try wasm.string_table.put(wasm.base.allocator, object.string_table.get(import.name)), .kind = import.kind, @@ -3800,7 +3800,7 @@ fn writeToFile( const table_loc = wasm.findGlobalSymbol("__indirect_function_table").?; const table_sym = table_loc.getSymbol(wasm); - var flags: u32 = if (table_sym.index == 0) 0x0 else 0x02; // passive with implicit 0-index table or set table index manually + const flags: u32 = if (table_sym.index == 0) 0x0 else 0x02; // passive with implicit 0-index table or set table index manually try leb.writeULEB128(binary_writer, flags); if (flags == 0x02) { try leb.writeULEB128(binary_writer, table_sym.index); diff --git a/src/link/Wasm/Object.zig b/src/link/Wasm/Object.zig index 359ff20d94..4f5dae8c09 100644 --- a/src/link/Wasm/Object.zig +++ b/src/link/Wasm/Object.zig @@ -252,7 +252,7 @@ fn checkLegacyIndirectFunctionTable(object: *Object) !?Symbol { return error.MissingTableSymbols; } - var table_import: types.Import = for (object.imports) |imp| { + const table_import: types.Import = for (object.imports) |imp| { if (imp.kind == .table) { break imp; } @@ -512,7 +512,7 @@ fn Parser(comptime ReaderType: type) type { try assertEnd(reader); }, .code => { - var start = reader.context.bytes_left; + const start = reader.context.bytes_left; var index: u32 = 0; const count = try readLeb(u32, reader); while (index < count) : (index += 1) { @@ -532,7 +532,7 @@ fn Parser(comptime ReaderType: type) type { } }, .data => { - var start = reader.context.bytes_left; + const start = reader.context.bytes_left; var index: u32 = 0; const count = try readLeb(u32, reader); while (index < count) : (index += 1) { diff --git a/src/link/tapi/yaml.zig b/src/link/tapi/yaml.zig index 5e3602f620..7afa229401 100644 --- a/src/link/tapi/yaml.zig +++ b/src/link/tapi/yaml.zig @@ -491,7 +491,7 @@ pub fn stringify(allocator: Allocator, input: anytype, writer: anytype) !void { var arena = ArenaAllocator.init(allocator); defer arena.deinit(); - var maybe_value = try Value.encode(arena.allocator(), input); + const maybe_value = try Value.encode(arena.allocator(), input); if (maybe_value) |value| { // TODO should we output as an explicit doc? diff --git a/src/main.zig b/src/main.zig index 7c451c242b..6bab14df56 100644 --- a/src/main.zig +++ b/src/main.zig @@ -4479,7 +4479,7 @@ fn cmdRc(gpa: Allocator, arena: Allocator, args: []const []const u8) !void { try stdout_writer.writeByte('\n'); } - var full_input = full_input: { + const full_input = full_input: { if (options.preprocess != .no) { if (!build_options.have_llvm) { fatal("clang not available: compiler built without LLVM extensions", .{}); @@ -4526,7 +4526,7 @@ fn cmdRc(gpa: Allocator, arena: Allocator, args: []const []const u8) !void { } if (process.can_spawn) { - var result = std.ChildProcess.run(.{ + const result = std.ChildProcess.run(.{ .allocator = gpa, .argv = argv.items, .max_output_bytes = std.math.maxInt(u32), @@ -4593,7 +4593,7 @@ fn cmdRc(gpa: Allocator, arena: Allocator, args: []const []const u8) !void { var mapping_results = try resinator.source_mapping.parseAndRemoveLineCommands(gpa, full_input, full_input, .{ .initial_filename = options.input_filename }); defer mapping_results.mappings.deinit(gpa); - var final_input = resinator.comments.removeComments(mapping_results.result, mapping_results.result, &mapping_results.mappings); + const final_input = resinator.comments.removeComments(mapping_results.result, mapping_results.result, &mapping_results.mappings); var output_file = std.fs.cwd().createFile(options.output_filename, .{}) catch |err| { try resinator.utils.renderErrorMessage(stderr.writer(), stderr_config, .err, "unable to create output file '{s}': {s}", .{ options.output_filename, @errorName(err) }); @@ -4762,7 +4762,7 @@ pub fn cmdLibC(gpa: Allocator, args: []const []const u8) !void { const libc_installation: ?*LibCInstallation = libc: { if (input_file) |libc_file| { - var libc = try arena.create(LibCInstallation); + const libc = try arena.create(LibCInstallation); libc.* = LibCInstallation.parse(arena, libc_file, cross_target) catch |err| { fatal("unable to parse libc file at path {s}: {s}", .{ libc_file, @errorName(err) }); }; @@ -4781,7 +4781,7 @@ pub fn cmdLibC(gpa: Allocator, args: []const []const u8) !void { const target = cross_target.toTarget(); const is_native_abi = cross_target.isNativeAbi(); - var libc_dirs = Compilation.detectLibCIncludeDirs( + const libc_dirs = Compilation.detectLibCIncludeDirs( arena, zig_lib_directory.path.?, target, @@ -4960,7 +4960,7 @@ pub const usage_build = pub fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void { const work_around_btrfs_bug = builtin.os.tag == .linux and EnvVar.ZIG_BTRFS_WORKAROUND.isSet(); - var color: Color = .auto; + const color: Color = .auto; // We want to release all the locks before executing the child process, so we make a nice // big block here to ensure the cleanup gets run when we extract out our argv. @@ -6001,7 +6001,7 @@ const ArgIteratorResponseFile = process.ArgIteratorGeneral(.{ .comments = true, /// Initialize the arguments from a Response File. "*.rsp" fn initArgIteratorResponseFile(allocator: Allocator, resp_file_path: []const u8) !ArgIteratorResponseFile { const max_bytes = 10 * 1024 * 1024; // 10 MiB of command line arguments is a reasonable limit - var cmd_line = try fs.cwd().readFileAlloc(allocator, resp_file_path, max_bytes); + const cmd_line = try fs.cwd().readFileAlloc(allocator, resp_file_path, max_bytes); errdefer allocator.free(cmd_line); return ArgIteratorResponseFile.initTakeOwnership(allocator, cmd_line); diff --git a/src/resinator/bmp.zig b/src/resinator/bmp.zig index 1c7e0f6aad..134ee81966 100644 --- a/src/resinator/bmp.zig +++ b/src/resinator/bmp.zig @@ -120,7 +120,7 @@ pub fn read(reader: anytype, max_size: u64) ReadError!BitmapInfo { var dib_header_buf: [@sizeOf(BITMAPCOREHEADER)]u8 align(@alignOf(BITMAPCOREHEADER)) = undefined; std.mem.writeInt(u32, dib_header_buf[0..4], bitmap_info.dib_header_size, .little); reader.readNoEof(dib_header_buf[4..]) catch return error.UnexpectedEOF; - var dib_header: *BITMAPCOREHEADER = @ptrCast(&dib_header_buf); + const dib_header: *BITMAPCOREHEADER = @ptrCast(&dib_header_buf); structFieldsLittleToNative(BITMAPCOREHEADER, dib_header); // > The size of the color palette is calculated from the BitsPerPixel value. diff --git a/src/resinator/cli.zig b/src/resinator/cli.zig index 50dbed5ad6..7fb6573c22 100644 --- a/src/resinator/cli.zig +++ b/src/resinator/cli.zig @@ -163,15 +163,15 @@ pub const Options = struct { // we shouldn't change anything. if (val_ptr.* == .undefine) return; // Otherwise, the new value takes precedence. - var duped_value = try self.allocator.dupe(u8, value); + const duped_value = try self.allocator.dupe(u8, value); errdefer self.allocator.free(duped_value); val_ptr.deinit(self.allocator); val_ptr.* = .{ .define = duped_value }; return; } - var duped_key = try self.allocator.dupe(u8, identifier); + const duped_key = try self.allocator.dupe(u8, identifier); errdefer self.allocator.free(duped_key); - var duped_value = try self.allocator.dupe(u8, value); + const duped_value = try self.allocator.dupe(u8, value); errdefer self.allocator.free(duped_value); try self.symbols.put(self.allocator, duped_key, .{ .define = duped_value }); } @@ -183,7 +183,7 @@ pub const Options = struct { action.* = .{ .undefine = {} }; return; } - var duped_key = try self.allocator.dupe(u8, identifier); + const duped_key = try self.allocator.dupe(u8, identifier); errdefer self.allocator.free(duped_key); try self.symbols.put(self.allocator, duped_key, .{ .undefine = {} }); } @@ -828,7 +828,7 @@ pub fn parse(allocator: Allocator, args: []const []const u8, diagnostics: *Diagn } } - var positionals = args[arg_i..]; + const positionals = args[arg_i..]; if (positionals.len < 1) { var err_details = Diagnostics.ErrorDetails{ .print_args = false, .arg_index = arg_i }; diff --git a/src/resinator/code_pages.zig b/src/resinator/code_pages.zig index 4b9a87ce7a..be89ed3f02 100644 --- a/src/resinator/code_pages.zig +++ b/src/resinator/code_pages.zig @@ -302,8 +302,8 @@ pub const Utf8 = struct { pub fn decode(bytes: []const u8) Codepoint { std.debug.assert(bytes.len > 0); - var first_byte = bytes[0]; - var expected_len = sequenceLength(first_byte) orelse { + const first_byte = bytes[0]; + const expected_len = sequenceLength(first_byte) orelse { return .{ .value = Codepoint.invalid, .byte_len = 1 }; }; if (expected_len == 1) return .{ .value = first_byte, .byte_len = 1 }; @@ -367,7 +367,7 @@ pub const Utf8 = struct { test "Utf8.WellFormedDecoder" { const invalid_utf8 = "\xF0\x80"; - var decoded = Utf8.WellFormedDecoder.decode(invalid_utf8); + const decoded = Utf8.WellFormedDecoder.decode(invalid_utf8); try std.testing.expectEqual(Codepoint.invalid, decoded.value); try std.testing.expectEqual(@as(usize, 2), decoded.byte_len); } diff --git a/src/resinator/comments.zig b/src/resinator/comments.zig index cfb27ae341..a631b8bb93 100644 --- a/src/resinator/comments.zig +++ b/src/resinator/comments.zig @@ -206,9 +206,9 @@ inline fn handleMultilineCarriageReturn( } pub fn removeCommentsAlloc(allocator: Allocator, source: []const u8, source_mappings: ?*SourceMappings) ![]u8 { - var buf = try allocator.alloc(u8, source.len); + const buf = try allocator.alloc(u8, source.len); errdefer allocator.free(buf); - var result = removeComments(source, buf, source_mappings); + const result = removeComments(source, buf, source_mappings); return allocator.realloc(buf, result.len); } @@ -326,7 +326,7 @@ test "remove comments with mappings" { try mappings.set(allocator, 3, .{ .start_line = 3, .end_line = 3, .filename_offset = 0 }); defer mappings.deinit(allocator); - var result = removeComments(&mut_source, &mut_source, &mappings); + const result = removeComments(&mut_source, &mut_source, &mappings); try std.testing.expectEqualStrings("blahblah", result); try std.testing.expectEqual(@as(usize, 1), mappings.mapping.items.len); @@ -335,6 +335,6 @@ test "remove comments with mappings" { test "in place" { var mut_source = "blah /* comment */ blah".*; - var result = removeComments(&mut_source, &mut_source, null); + const result = removeComments(&mut_source, &mut_source, null); try std.testing.expectEqualStrings("blah blah", result); } diff --git a/src/resinator/compile.zig b/src/resinator/compile.zig index ae0232a737..2f768b2b31 100644 --- a/src/resinator/compile.zig +++ b/src/resinator/compile.zig @@ -666,7 +666,7 @@ pub const Compiler = struct { }, }, .dib => { - var bitmap_header: *ico.BitmapHeader = @ptrCast(@alignCast(&header_bytes)); + const bitmap_header: *ico.BitmapHeader = @ptrCast(@alignCast(&header_bytes)); if (native_endian == .big) { std.mem.byteSwapAllFields(ico.BitmapHeader, bitmap_header); } @@ -1773,13 +1773,13 @@ pub const Compiler = struct { } try data_writer.writeByteNTimes(0, num_padding); - var style = if (control.style) |style_expression| + const style = if (control.style) |style_expression| // Certain styles are implied by the control type evaluateFlagsExpressionWithDefault(res.ControlClass.getImpliedStyle(control_type), style_expression, self.source, self.input_code_pages) else res.ControlClass.getImpliedStyle(control_type); - var exstyle = if (control.exstyle) |exstyle_expression| + const exstyle = if (control.exstyle) |exstyle_expression| evaluateFlagsExpressionWithDefault(0, exstyle_expression, self.source, self.input_code_pages) else 0; @@ -3205,7 +3205,7 @@ pub const StringTable = struct { const trimmed_string = trim: { // Two NUL characters in a row act as a terminator // Note: This is only the case for STRINGTABLE strings - var trimmed = trimToDoubleNUL(u16, utf16_string); + const trimmed = trimToDoubleNUL(u16, utf16_string); // We also want to trim any trailing NUL characters break :trim std.mem.trimRight(u16, trimmed, &[_]u16{0}); }; diff --git a/src/resinator/lang.zig b/src/resinator/lang.zig index d43380fa05..513d775bae 100644 --- a/src/resinator/lang.zig +++ b/src/resinator/lang.zig @@ -98,7 +98,7 @@ pub fn tagToId(tag: []const u8) error{InvalidLanguageTag}!?LanguageId { var normalized_buf: [longest_known_tag]u8 = undefined; // To allow e.g. `de-de_phoneb` to get looked up as `de-de`, we need to // omit the suffix, but only if the tag contains a valid alternate sort order. - var tag_to_normalize = if (parsed.isSuffixValidSortOrder()) tag[0 .. tag.len - (parsed.suffix.?.len + 1)] else tag; + const tag_to_normalize = if (parsed.isSuffixValidSortOrder()) tag[0 .. tag.len - (parsed.suffix.?.len + 1)] else tag; const normalized_tag = normalizeTag(tag_to_normalize, &normalized_buf); return std.meta.stringToEnum(LanguageId, normalized_tag) orelse { // special case for a tag that has been mapped to the same ID diff --git a/src/resinator/parse.zig b/src/resinator/parse.zig index 2e528bea65..68537b94f6 100644 --- a/src/resinator/parse.zig +++ b/src/resinator/parse.zig @@ -100,7 +100,7 @@ pub const Parser = struct { // because it almost always leads to unhelpful error messages // (usually it will end up with bogus things like 'file // not found: {') - var statement = try self.parseStatement(); + const statement = try self.parseStatement(); try statements.append(statement); } } @@ -698,7 +698,7 @@ pub const Parser = struct { .dlginclude => { const common_resource_attributes = try self.parseCommonResourceAttributes(); - var filename_expression = try self.parseExpression(.{ + const filename_expression = try self.parseExpression(.{ .allowed_types = .{ .string = true }, }); @@ -756,7 +756,7 @@ pub const Parser = struct { return &node.base; } - var filename_expression = try self.parseExpression(.{ + const filename_expression = try self.parseExpression(.{ // Don't tell the user that numbers are accepted since we error on // number expressions and regular number literals are treated as unquoted // literals rather than numbers, so from the users perspective @@ -934,8 +934,8 @@ pub const Parser = struct { style = try optional_param_parser.parse(.{ .not_expression_allowed = true }); } - var exstyle: ?*Node = try optional_param_parser.parse(.{ .not_expression_allowed = true }); - var help_id: ?*Node = switch (resource) { + const exstyle: ?*Node = try optional_param_parser.parse(.{ .not_expression_allowed = true }); + const help_id: ?*Node = switch (resource) { .dialogex => try optional_param_parser.parse(.{}), else => null, }; @@ -1526,7 +1526,7 @@ pub const Parser = struct { pub fn toErrorDetails(options: ParseExpressionOptions, token: Token) ErrorDetails { // TODO: expected_types_override interaction with is_known_to_be_number_expression? - var expected_types = options.expected_types_override orelse ErrorDetails.ExpectedTypes{ + const expected_types = options.expected_types_override orelse ErrorDetails.ExpectedTypes{ .number = options.allowed_types.number, .number_expression = options.allowed_types.number, .string_literal = options.allowed_types.string and !options.is_known_to_be_number_expression, diff --git a/src/resinator/res.zig b/src/resinator/res.zig index 7db3f0d749..86102b4e77 100644 --- a/src/resinator/res.zig +++ b/src/resinator/res.zig @@ -357,7 +357,7 @@ pub const NameOrOrdinal = union(enum) { /// RC compiler would have allowed them, so that a proper warning/error /// can be emitted. pub fn maybeNonAsciiOrdinalFromString(bytes: SourceBytes) ?NameOrOrdinal { - var buf = bytes.slice; + const buf = bytes.slice; const radix = 10; if (buf.len > 2 and buf[0] == '0') { switch (buf[1]) { @@ -514,7 +514,7 @@ test "NameOrOrdinal" { { var expected = blk: { // the input before the 𐐷 character, but uppercased - var expected_u8_bytes = "00614982008907933748980730280674788429543776231864944218790698304852300002973622122844631429099469274282385299397783838528QFFL7SHNSIETG0QKLR1UYPBTUV1PMFQRRA0VJDG354GQEDJMUPGPP1W1EXVNTZVEIZ6K3IPQM1AWGEYALMEODYVEZGOD3MFMGEY8FNR4JUETTB1PZDEWSNDRGZUA8SNXP3NGO"; + const expected_u8_bytes = "00614982008907933748980730280674788429543776231864944218790698304852300002973622122844631429099469274282385299397783838528QFFL7SHNSIETG0QKLR1UYPBTUV1PMFQRRA0VJDG354GQEDJMUPGPP1W1EXVNTZVEIZ6K3IPQM1AWGEYALMEODYVEZGOD3MFMGEY8FNR4JUETTB1PZDEWSNDRGZUA8SNXP3NGO"; var buf: [256:0]u16 = undefined; for (expected_u8_bytes, 0..) |byte, i| { buf[i] = std.mem.nativeToLittle(u16, byte); diff --git a/src/resinator/source_mapping.zig b/src/resinator/source_mapping.zig index 27e888f87a..f8f99de401 100644 --- a/src/resinator/source_mapping.zig +++ b/src/resinator/source_mapping.zig @@ -251,7 +251,7 @@ pub fn handleLineCommand(allocator: Allocator, line_command: []const u8, current } pub fn parseAndRemoveLineCommandsAlloc(allocator: Allocator, source: []const u8, options: ParseAndRemoveLineCommandsOptions) !ParseLineCommandsResult { - var buf = try allocator.alloc(u8, source.len); + const buf = try allocator.alloc(u8, source.len); errdefer allocator.free(buf); var result = try parseAndRemoveLineCommands(allocator, source, buf, options); result.result = try allocator.realloc(buf, result.result.len); @@ -440,7 +440,7 @@ pub const SourceMappings = struct { } pub fn set(self: *SourceMappings, allocator: Allocator, line_num: usize, span: SourceSpan) !void { - var ptr = try self.expandAndGet(allocator, line_num); + const ptr = try self.expandAndGet(allocator, line_num); ptr.* = span; } diff --git a/src/translate_c.zig b/src/translate_c.zig index 73dc7b8c19..ea4cdf860a 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -456,7 +456,7 @@ fn visitFnDecl(c: *Context, fn_decl: *const clang.FunctionDecl) Error!void { block_scope.return_type = return_qt; defer block_scope.deinit(); - var scope = &block_scope.base; + const scope = &block_scope.base; var param_id: c_uint = 0; for (proto_node.data.params) |*param| { @@ -1363,7 +1363,7 @@ fn transSimpleOffsetOfExpr(c: *Context, expr: *const clang.OffsetOfExpr) TransEr if (c.decl_table.get(@intFromPtr(record_decl.getCanonicalDecl()))) |type_name| { const type_node = try Tag.type.create(c.arena, type_name); - var raw_field_name = try c.str(@as(*const clang.NamedDecl, @ptrCast(field_decl)).getName_bytes_begin()); + const raw_field_name = try c.str(@as(*const clang.NamedDecl, @ptrCast(field_decl)).getName_bytes_begin()); const quoted_field_name = try std.fmt.allocPrint(c.arena, "\"{s}\"", .{raw_field_name}); const field_name_node = try Tag.string_literal.create(c.arena, quoted_field_name); @@ -1967,7 +1967,7 @@ fn transBoolExpr( return Node{ .tag_if_small_enough = @intFromEnum(([2]Tag{ .true_literal, .false_literal })[@intFromBool(is_zero)]) }; } - var res = try transExpr(c, scope, expr, used); + const res = try transExpr(c, scope, expr, used); if (isBoolRes(res)) { return maybeSuppressResult(c, used, res); } @@ -3477,7 +3477,7 @@ fn cIsFunctionDeclRef(expr: *const clang.Expr) bool { fn transCallExpr(c: *Context, scope: *Scope, stmt: *const clang.CallExpr, result_used: ResultUsed) TransError!Node { const callee = stmt.getCallee(); - var raw_fn_expr = try transExpr(c, scope, callee, .used); + const raw_fn_expr = try transExpr(c, scope, callee, .used); var is_ptr = false; const fn_ty = qualTypeGetFnProto(callee.getType(), &is_ptr); @@ -5889,7 +5889,7 @@ fn escapeUnprintables(ctx: *Context, m: *MacroCtx) ![]const u8 { const formatter = std.fmt.fmtSliceEscapeLower(zigified); const encoded_size = @as(usize, @intCast(std.fmt.count("{s}", .{formatter}))); - var output = try ctx.arena.alloc(u8, encoded_size); + const output = try ctx.arena.alloc(u8, encoded_size); return std.fmt.bufPrint(output, "{s}", .{formatter}) catch |err| switch (err) { error.NoSpaceLeft => unreachable, else => |e| return e, diff --git a/src/value.zig b/src/value.zig index 6af43063d1..256b537573 100644 --- a/src/value.zig +++ b/src/value.zig @@ -2136,7 +2136,7 @@ pub const Value = struct { lhs_bigint.limbs.len + rhs_bigint.limbs.len, ); var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; - var limbs_buffer = try arena.alloc( + const limbs_buffer = try arena.alloc( std.math.big.Limb, std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1), ); @@ -2249,7 +2249,7 @@ pub const Value = struct { ), ); var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; - var limbs_buffer = try arena.alloc( + const limbs_buffer = try arena.alloc( std.math.big.Limb, std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1), ); @@ -2788,7 +2788,7 @@ pub const Value = struct { lhs_bigint.limbs.len + rhs_bigint.limbs.len, ); var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; - var limbs_buffer = try allocator.alloc( + const limbs_buffer = try allocator.alloc( std.math.big.Limb, std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1), ); diff --git a/src/windows_sdk.zig b/src/windows_sdk.zig index 85c10226bd..d6add063d8 100644 --- a/src/windows_sdk.zig +++ b/src/windows_sdk.zig @@ -69,7 +69,7 @@ fn iterateAndFilterBySemVer(iterator: *std.fs.IterableDir.Iterator, allocator: s try dirs_filtered_list.append(subfolder_name_allocated); } - var dirs_filtered_slice = try dirs_filtered_list.toOwnedSlice(); + const dirs_filtered_slice = try dirs_filtered_list.toOwnedSlice(); // Keep in mind that order of these names is not guaranteed by Windows, // so we cannot just reverse or "while (popOrNull())" this ArrayList. std.mem.sortUnstable([]const u8, dirs_filtered_slice, {}, struct { @@ -129,7 +129,7 @@ const RegistryUtf8 = struct { const value_utf16le = try registry_utf16le.getString(allocator, subkey_utf16le, value_name_utf16le); defer allocator.free(value_utf16le); - var value_utf8: []u8 = std.unicode.utf16leToUtf8Alloc(allocator, value_utf16le) catch |err| switch (err) { + const value_utf8: []u8 = std.unicode.utf16leToUtf8Alloc(allocator, value_utf16le) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.StringNotFound, }; @@ -246,7 +246,7 @@ const RegistryUtf16Le = struct { else => return error.NotAString, } - var value_utf16le_buf: []u16 = try allocator.alloc(u16, std.math.divCeil(u32, value_utf16le_buf_size, 2) catch unreachable); + const value_utf16le_buf: []u16 = try allocator.alloc(u16, std.math.divCeil(u32, value_utf16le_buf_size, 2) catch unreachable); errdefer allocator.free(value_utf16le_buf); return_code_int = windows.advapi32.RegGetValueW( @@ -354,7 +354,7 @@ pub const Windows10Sdk = struct { defer v10_key.closeKey(); const path: []const u8 = path10: { - var path_maybe_with_trailing_slash = v10_key.getString(allocator, "", "InstallationFolder") catch |err| switch (err) { + const path_maybe_with_trailing_slash = v10_key.getString(allocator, "", "InstallationFolder") catch |err| switch (err) { error.NotAString => return error.Windows10SdkNotFound, error.ValueNameNotFound => return error.Windows10SdkNotFound, error.StringNotFound => return error.Windows10SdkNotFound, @@ -381,7 +381,7 @@ pub const Windows10Sdk = struct { const version: []const u8 = version10: { // note(dimenus): Microsoft doesn't include the .0 in the ProductVersion key.... - var version_without_0 = v10_key.getString(allocator, "", "ProductVersion") catch |err| switch (err) { + const version_without_0 = v10_key.getString(allocator, "", "ProductVersion") catch |err| switch (err) { error.NotAString => return error.Windows10SdkNotFound, error.ValueNameNotFound => return error.Windows10SdkNotFound, error.StringNotFound => return error.Windows10SdkNotFound, @@ -445,7 +445,7 @@ pub const Windows81Sdk = struct { /// After finishing work, call `free(allocator)`. fn find(allocator: std.mem.Allocator, roots_key: *const RegistryUtf8) error{ OutOfMemory, Windows81SdkNotFound, PathTooLong, VersionTooLong }!Windows81Sdk { const path: []const u8 = path81: { - var path_maybe_with_trailing_slash = roots_key.getString(allocator, "", "KitsRoot81") catch |err| switch (err) { + const path_maybe_with_trailing_slash = roots_key.getString(allocator, "", "KitsRoot81") catch |err| switch (err) { error.NotAString => return error.Windows81SdkNotFound, error.ValueNameNotFound => return error.Windows81SdkNotFound, error.StringNotFound => return error.Windows81SdkNotFound, @@ -752,7 +752,7 @@ const MsvcLibDir = struct { const config_subkey = std.fmt.bufPrint(config_subkey_buf[0..], "Software\\Microsoft\\VisualStudio\\{s}_Config", .{vs_version}) catch unreachable; - var source_directories_value = visualstudio_registry.getString(allocator, config_subkey, "Source Directories") catch |err| switch (err) { + const source_directories_value = visualstudio_registry.getString(allocator, config_subkey, "Source Directories") catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => continue, }; @@ -768,7 +768,7 @@ const MsvcLibDir = struct { var source_directories_splitted = std.mem.splitScalar(u8, source_directories, ';'); const msvc_dir: []const u8 = msvc_dir: { - var msvc_include_dir_maybe_with_trailing_slash = try allocator.dupe(u8, source_directories_splitted.first()); + const msvc_include_dir_maybe_with_trailing_slash = try allocator.dupe(u8, source_directories_splitted.first()); if (msvc_include_dir_maybe_with_trailing_slash.len > std.fs.MAX_PATH_BYTES or !std.fs.path.isAbsolute(msvc_include_dir_maybe_with_trailing_slash)) { allocator.free(msvc_include_dir_maybe_with_trailing_slash); @@ -833,7 +833,7 @@ const MsvcLibDir = struct { const vs7_key = RegistryUtf8.openKey("SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7") catch return error.PathNotFound; defer vs7_key.closeKey(); try_vs7_key: { - var path_maybe_with_trailing_slash = vs7_key.getString(allocator, "", "14.0") catch |err| switch (err) { + const path_maybe_with_trailing_slash = vs7_key.getString(allocator, "", "14.0") catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => break :try_vs7_key, }; -- cgit v1.2.3 From 3c585730f2d259963716684ede87dcfce2607973 Mon Sep 17 00:00:00 2001 From: mlugg Date: Fri, 17 Nov 2023 04:58:49 +0000 Subject: AstGen: preserve result type in comptime block --- src/AstGen.zig | 28 +++++++++++++++++++++------- test/behavior/cast.zig | 5 +++++ 2 files changed, 26 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/AstGen.zig b/src/AstGen.zig index be6e88af0a..0d1fa6c061 100644 --- a/src/AstGen.zig +++ b/src/AstGen.zig @@ -1971,6 +1971,17 @@ fn comptimeExpr( .block_two, .block_two_semicolon, .block, .block_semicolon => { const token_tags = tree.tokens.items(.tag); const lbrace = main_tokens[node]; + // Careful! We can't pass in the real result location here, since it may + // refer to runtime memory. A runtime-to-comptime boundary has to remove + // result location information, compute the result, and copy it to the true + // result location at runtime. We do this below as well. + const ty_only_ri: ResultInfo = .{ + .ctx = ri.ctx, + .rl = if (try ri.rl.resultType(gz, node)) |res_ty| + .{ .coerced_ty = res_ty } + else + .none, + }; if (token_tags[lbrace - 1] == .colon and token_tags[lbrace - 2] == .identifier) { @@ -1985,17 +1996,13 @@ fn comptimeExpr( else stmts[0..2]; - // Careful! We can't pass in the real result location here, since it may - // refer to runtime memory. A runtime-to-comptime boundary has to remove - // result location information, compute the result, and copy it to the true - // result location at runtime. We do this below as well. - const block_ref = try labeledBlockExpr(gz, scope, .{ .rl = .none }, node, stmt_slice, true); + const block_ref = try labeledBlockExpr(gz, scope, ty_only_ri, node, stmt_slice, true); return rvalue(gz, ri, block_ref, node); }, .block, .block_semicolon => { const stmts = tree.extra_data[node_datas[node].lhs..node_datas[node].rhs]; // Replace result location and copy back later - see above. - const block_ref = try labeledBlockExpr(gz, scope, .{ .rl = .none }, node, stmts, true); + const block_ref = try labeledBlockExpr(gz, scope, ty_only_ri, node, stmts, true); return rvalue(gz, ri, block_ref, node); }, else => unreachable, @@ -2013,7 +2020,14 @@ fn comptimeExpr( const block_inst = try gz.makeBlockInst(.block_comptime, node); // Replace result location and copy back later - see above. - const block_result = try expr(&block_scope, scope, .{ .rl = .none }, node); + const ty_only_ri: ResultInfo = .{ + .ctx = ri.ctx, + .rl = if (try ri.rl.resultType(gz, node)) |res_ty| + .{ .coerced_ty = res_ty } + else + .none, + }; + const block_result = try expr(&block_scope, scope, ty_only_ri, node); if (!gz.refIsNoReturn(block_result)) { _ = try block_scope.addBreak(.@"break", block_inst, block_result); } diff --git a/test/behavior/cast.zig b/test/behavior/cast.zig index 486014074d..3bbb1e9a9a 100644 --- a/test/behavior/cast.zig +++ b/test/behavior/cast.zig @@ -2522,3 +2522,8 @@ test "@intCast vector of signed integer" { try expect(y[2] == 3); try expect(y[3] == 4); } + +test "result type is preserved into comptime block" { + const x: u32 = comptime @intCast(123); + try expect(x == 123); +} -- cgit v1.2.3 From ff838d86315ccb49f9c3de839458508fda857231 Mon Sep 17 00:00:00 2001 From: mlugg Date: Fri, 17 Nov 2023 13:16:39 +0000 Subject: translate-c: work around unnecessary uses of 'var' --- src/translate_c/common.zig | 8 ++ test/translate_c.zig | 178 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 186 insertions(+) (limited to 'src') diff --git a/src/translate_c/common.zig b/src/translate_c/common.zig index c26ab2798b..478f41626b 100644 --- a/src/translate_c/common.zig +++ b/src/translate_c/common.zig @@ -291,6 +291,14 @@ pub fn ScopeExtra(comptime Context: type, comptime Type: type) type { } pub fn skipVariableDiscard(inner: *Scope, name: []const u8) void { + if (true) { + // TODO: due to 'local variable is never mutated' errors, we can + // only skip discards if a variable is used as an lvalue, which + // we don't currently have detection for in translate-c. + // Once #17584 is completed, perhaps we can do away with this + // logic entirely, and instead rely on render to fixup code. + return; + } var scope = inner; while (true) { switch (scope.id) { diff --git a/test/translate_c.zig b/test/translate_c.zig index 2df0f8c6cf..fb4ab33480 100644 --- a/test/translate_c.zig +++ b/test/translate_c.zig @@ -37,6 +37,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo(arg_a: c_int) void { \\ var a = arg_a; + \\ _ = &a; \\ while (true) { \\ if (a != 0) break; \\ } @@ -81,9 +82,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo(arg_x: c_ulong) c_ulong { \\ var x = arg_x; + \\ _ = &x; \\ const union_unnamed_1 = extern union { \\ _x: c_ulong, \\ }; + \\ _ = &union_unnamed_1; \\ return (union_unnamed_1{ \\ ._x = x, \\ })._x; @@ -142,6 +145,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub extern fn bar(...) c_int; \\pub export fn foo() void { \\ var a: c_int = undefined; + \\ _ = &a; \\ if (a != 0) a = 2 else _ = bar(); \\} }); @@ -194,6 +198,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ B: c_int = @import("std").mem.zeroes(c_int), \\ C: c_int = @import("std").mem.zeroes(c_int), \\ }; + \\ _ = &struct_Foo; \\ var a: struct_Foo = struct_Foo{ \\ .A = @as(c_int, 0), \\ .B = 0, @@ -206,6 +211,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ B: c_int = @import("std").mem.zeroes(c_int), \\ C: c_int = @import("std").mem.zeroes(c_int), \\ }; + \\ _ = &struct_Foo_1; \\ var a_2: struct_Foo_1 = struct_Foo_1{ \\ .A = @as(c_int, 0), \\ .B = 0, @@ -242,6 +248,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ }; \\ _ = &union_unnamed_1; \\ const Foo = union_unnamed_1; + \\ _ = &Foo; \\ var a: Foo = Foo{ \\ .A = @as(c_int, 0), \\ }; @@ -254,6 +261,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ }; \\ _ = &union_unnamed_2; \\ const Foo_1 = union_unnamed_2; + \\ _ = &Foo_1; \\ var a_2: Foo_1 = Foo_1{ \\ .A = @as(c_int, 0), \\ }; @@ -268,6 +276,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\#define MEM_PHYSICAL_TO_K0(x) (void*)((uint32_t)(x) + SYS_BASE_CACHED) , &[_][]const u8{ \\pub inline fn MEM_PHYSICAL_TO_K0(x: anytype) ?*anyopaque { + \\ _ = &x; \\ return @import("std").zig.c_translation.cast(?*anyopaque, @import("std").zig.c_translation.cast(u32, x) + SYS_BASE_CACHED); \\} }); @@ -310,6 +319,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub const VALUE = ((((@as(c_int, 1) + (@as(c_int, 2) * @as(c_int, 3))) + (@as(c_int, 4) * @as(c_int, 5))) + @as(c_int, 6)) << @as(c_int, 7)) | @intFromBool(@as(c_int, 8) == @as(c_int, 9)); , \\pub inline fn _AL_READ3BYTES(p: anytype) @TypeOf((@import("std").zig.c_translation.cast([*c]u8, p).* | ((@import("std").zig.c_translation.cast([*c]u8, p) + @as(c_int, 1)).* << @as(c_int, 8))) | ((@import("std").zig.c_translation.cast([*c]u8, p) + @as(c_int, 2)).* << @as(c_int, 16))) { + \\ _ = &p; \\ return (@import("std").zig.c_translation.cast([*c]u8, p).* | ((@import("std").zig.c_translation.cast([*c]u8, p) + @as(c_int, 1)).* << @as(c_int, 8))) | ((@import("std").zig.c_translation.cast([*c]u8, p) + @as(c_int, 2)).* << @as(c_int, 16)); \\} }); @@ -390,6 +400,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub const Color = struct_Color; , \\pub inline fn CLITERAL(@"type": anytype) @TypeOf(@"type") { + \\ _ = &@"type"; \\ return @"type"; \\} , @@ -407,6 +418,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\}; , \\pub inline fn A(_x: anytype) MyCStruct { + \\ _ = &_x; \\ return @import("std").mem.zeroInit(MyCStruct, .{ \\ .x = _x, \\ }); @@ -438,6 +450,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\#define __ferror_unlocked_body(_fp) (((_fp)->_flags & _IO_ERR_SEEN) != 0) , &[_][]const u8{ \\pub inline fn __ferror_unlocked_body(_fp: anytype) @TypeOf((_fp.*._flags & _IO_ERR_SEEN) != @as(c_int, 0)) { + \\ _ = &_fp; \\ return (_fp.*._flags & _IO_ERR_SEEN) != @as(c_int, 0); \\} }); @@ -447,6 +460,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\#define BAR 1 && 2 > 4 , &[_][]const u8{ \\pub inline fn FOO(x: anytype) @TypeOf(@intFromBool(x >= @as(c_int, 0)) + @intFromBool(x >= @as(c_int, 0))) { + \\ _ = &x; \\ return @intFromBool(x >= @as(c_int, 0)) + @intFromBool(x >= @as(c_int, 0)); \\} , @@ -512,6 +526,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\}; , \\pub inline fn bar(x: anytype) @TypeOf(baz(@as(c_int, 1), @as(c_int, 2))) { + \\ _ = &x; \\ return blk_1: { \\ _ = &x; \\ _ = @as(c_int, 3); @@ -642,6 +657,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\}; \\pub export fn foo(arg_x: [*c]outer) void { \\ var x = arg_x; + \\ _ = &x; \\ x.*.unnamed_0.unnamed_0.y = @as(c_int, @bitCast(@as(c_uint, x.*.unnamed_0.x))); \\} }); @@ -728,6 +744,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub const struct_opaque_2 = opaque {}; \\pub export fn function(arg_opaque_1: ?*struct_opaque) void { \\ var opaque_1 = arg_opaque_1; + \\ _ = &opaque_1; \\ var cast: ?*struct_opaque_2 = @as(?*struct_opaque_2, @ptrCast(opaque_1)); \\ _ = &cast; \\} @@ -827,6 +844,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = undefined; + \\ _ = &a; \\ _ = @as(c_int, 1); \\ _ = "hey"; \\ _ = @as(c_int, 1) + @as(c_int, 1); @@ -912,6 +930,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub extern fn foo() void; \\pub export fn bar() void { \\ var func_ptr: ?*anyopaque = @as(?*anyopaque, @ptrCast(&foo)); + \\ _ = &func_ptr; \\ var typed_func_ptr: ?*const fn () callconv(.C) void = @as(?*const fn () callconv(.C) void, @ptrFromInt(@as(c_ulong, @intCast(@intFromPtr(func_ptr))))); \\ _ = &typed_func_ptr; \\} @@ -953,8 +972,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn s() c_int { \\ var a: c_int = undefined; + \\ _ = &a; \\ var b: c_int = undefined; + \\ _ = &b; \\ var c: c_int = undefined; + \\ _ = &c; \\ c = a + b; \\ c = a - b; \\ c = a * b; @@ -964,8 +986,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\} \\pub export fn u() c_uint { \\ var a: c_uint = undefined; + \\ _ = &a; \\ var b: c_uint = undefined; + \\ _ = &b; \\ var c: c_uint = undefined; + \\ _ = &c; \\ c = a +% b; \\ c = a -% b; \\ c = a *% b; @@ -1361,6 +1386,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub export fn foo() void { \\ var a: c_int = undefined; \\ _ = &a; + \\ _ = &a; \\} }); @@ -1372,6 +1398,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() ?*anyopaque { \\ var x: [*c]c_ushort = undefined; + \\ _ = &x; \\ return @as(?*anyopaque, @ptrCast(x)); \\} }); @@ -1496,6 +1523,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub export fn foo() void { \\ { \\ var i: c_int = 0; + \\ _ = &i; \\ while (i != 0) : (i += 1) {} \\ } \\} @@ -1519,6 +1547,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var i: c_int = undefined; + \\ _ = &i; \\ { \\ i = 3; \\ while (i != 0) : (i -= 1) {} @@ -1562,6 +1591,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn ptrcast() [*c]f32 { \\ var a: [*c]c_int = undefined; + \\ _ = &a; \\ return @as([*c]f32, @ptrCast(@alignCast(a))); \\} }); @@ -1574,6 +1604,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn ptrptrcast() [*c][*c]f32 { \\ var a: [*c][*c]c_int = undefined; + \\ _ = &a; \\ return @as([*c][*c]f32, @ptrCast(@alignCast(a))); \\} }); @@ -1597,6 +1628,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn test_ptr_cast() void { \\ var p: ?*anyopaque = undefined; + \\ _ = &p; \\ { \\ var to_char: [*c]u8 = @as([*c]u8, @ptrCast(@alignCast(p))); \\ _ = &to_char; @@ -1633,8 +1665,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn while_none_bool() c_int { \\ var a: c_int = undefined; + \\ _ = &a; \\ var b: f32 = undefined; + \\ _ = &b; \\ var c: ?*anyopaque = undefined; + \\ _ = &c; \\ while (a != 0) return 0; \\ while (b != 0) return 1; \\ while (c != null) return 2; @@ -1655,8 +1690,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn for_none_bool() c_int { \\ var a: c_int = undefined; + \\ _ = &a; \\ var b: f32 = undefined; + \\ _ = &b; \\ var c: ?*anyopaque = undefined; + \\ _ = &c; \\ while (a != 0) return 0; \\ while (b != 0) return 1; \\ while (c != null) return 2; @@ -1693,6 +1731,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var x: [*c]c_int = undefined; + \\ _ = &x; \\ x.* = 1; \\} }); @@ -1706,7 +1745,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() c_int { \\ var x: c_int = 1234; + \\ _ = &x; \\ var ptr: [*c]c_int = &x; + \\ _ = &ptr; \\ return ptr.*; \\} }); @@ -1719,6 +1760,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() c_int { \\ var x: c_int = undefined; + \\ _ = &x; \\ return ~x; \\} }); @@ -1736,8 +1778,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() c_int { \\ var a: c_int = undefined; + \\ _ = &a; \\ var b: f32 = undefined; + \\ _ = &b; \\ var c: ?*anyopaque = undefined; + \\ _ = &c; \\ return @intFromBool(!(a == @as(c_int, 0))); \\ return @intFromBool(!(a != 0)); \\ return @intFromBool(!(b != 0)); @@ -2051,10 +2096,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub extern var c: c_int; , \\pub inline fn BASIC(c_1: anytype) @TypeOf(c_1 * @as(c_int, 2)) { + \\ _ = &c_1; \\ return c_1 * @as(c_int, 2); \\} , \\pub inline fn FOO(L: anytype, b: anytype) @TypeOf(L + b) { + \\ _ = &L; + \\ _ = &b; \\ return L + b; \\} , @@ -2109,7 +2157,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ var c_1 = arg_c_1; \\ _ = &c_1; \\ var a_2: c_int = undefined; + \\ _ = &a_2; \\ var b_3: u8 = 123; + \\ _ = &b_3; \\ b_3 = @as(u8, @bitCast(@as(i8, @truncate(a_2)))); \\ { \\ var d: c_int = 5; @@ -2150,7 +2200,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = undefined; + \\ _ = &a; \\ var b: c_int = undefined; + \\ _ = &b; \\ a = blk: { \\ const tmp = @as(c_int, 2); \\ b = tmp; @@ -2180,11 +2232,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() c_int { \\ var a: c_int = 5; + \\ _ = &a; \\ while (true) { \\ a = 2; \\ } \\ while (true) { \\ var a_1: c_int = 4; + \\ _ = &a_1; \\ a_1 = 9; \\ return blk: { \\ _ = @as(c_int, 6); @@ -2193,6 +2247,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ } \\ while (true) { \\ var a_1: c_int = 2; + \\ _ = &a_1; \\ a_1 = 12; \\ } \\ while (true) { @@ -2214,10 +2269,12 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub export fn foo() void { \\ { \\ var i: c_int = 2; + \\ _ = &i; \\ var b: c_int = 4; \\ _ = &b; \\ while ((i + @as(c_int, 2)) != 0) : (i = 2) { \\ var a: c_int = 2; + \\ _ = &a; \\ _ = blk: { \\ _ = blk_1: { \\ a = 6; @@ -2309,7 +2366,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn switch_fn(arg_i: c_int) void { \\ var i = arg_i; + \\ _ = &i; \\ var res: c_int = 0; + \\ _ = &res; \\ while (true) { \\ switch (i) { \\ @as(c_int, 0) => { @@ -2398,7 +2457,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn max(arg_a: c_int) void { \\ var a = arg_a; + \\ _ = &a; \\ var tmp: c_int = undefined; + \\ _ = &tmp; \\ tmp = a; \\ a = tmp; \\} @@ -2412,8 +2473,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn max(arg_a: c_int) void { \\ var a = arg_a; + \\ _ = &a; \\ var b: c_int = undefined; + \\ _ = &b; \\ var c: c_int = undefined; + \\ _ = &c; \\ c = blk: { \\ const tmp = a; \\ b = tmp; @@ -2442,6 +2506,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn int_from_float(arg_a: f32) c_int { \\ var a = arg_a; + \\ _ = &a; \\ return @as(c_int, @intFromFloat(a)); \\} }); @@ -2505,11 +2570,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = 2; + \\ _ = &a; \\ while (true) { \\ a = a - @as(c_int, 1); \\ if (!(a != 0)) break; \\ } \\ var b: c_int = 2; + \\ _ = &b; \\ while (true) { \\ b = b - @as(c_int, 1); \\ if (!(b != 0)) break; @@ -2550,21 +2617,37 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub const SomeTypedef = c_int; \\pub export fn and_or_non_bool(arg_a: c_int, arg_b: f32, arg_c: ?*anyopaque) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var b = arg_b; + \\ _ = &b; \\ var c = arg_c; + \\ _ = &c; \\ var d: enum_Foo = @as(c_uint, @bitCast(FooA)); + \\ _ = &d; \\ var e: c_int = @intFromBool((a != 0) and (b != 0)); + \\ _ = &e; \\ var f: c_int = @intFromBool((b != 0) and (c != null)); + \\ _ = &f; \\ var g: c_int = @intFromBool((a != 0) and (c != null)); + \\ _ = &g; \\ var h: c_int = @intFromBool((a != 0) or (b != 0)); + \\ _ = &h; \\ var i: c_int = @intFromBool((b != 0) or (c != null)); + \\ _ = &i; \\ var j: c_int = @intFromBool((a != 0) or (c != null)); + \\ _ = &j; \\ var k: c_int = @intFromBool((a != 0) or (@as(c_int, @bitCast(d)) != 0)); + \\ _ = &k; \\ var l: c_int = @intFromBool((@as(c_int, @bitCast(d)) != 0) and (b != 0)); + \\ _ = &l; \\ var m: c_int = @intFromBool((c != null) or (d != 0)); + \\ _ = &m; \\ var td: SomeTypedef = 44; + \\ _ = &td; \\ var o: c_int = @intFromBool((td != 0) or (b != 0)); + \\ _ = &o; \\ var p: c_int = @intFromBool((c != null) and (td != 0)); + \\ _ = &p; \\ return (((((((((e + f) + g) + h) + i) + j) + k) + l) + m) + o) + p; \\} , @@ -2604,7 +2687,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn max(arg_a: c_int, arg_b: c_int) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var b = arg_b; + \\ _ = &b; \\ return (a & b) ^ (a | b); \\} }); @@ -2623,14 +2708,23 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn test_comparisons(arg_a: c_int, arg_b: c_int) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var b = arg_b; + \\ _ = &b; \\ var c: c_int = @intFromBool(a < b); + \\ _ = &c; \\ var d: c_int = @intFromBool(a > b); + \\ _ = &d; \\ var e: c_int = @intFromBool(a <= b); + \\ _ = &e; \\ var f: c_int = @intFromBool(a >= b); + \\ _ = &f; \\ var g: c_int = @intFromBool(c < d); + \\ _ = &g; \\ var h: c_int = @intFromBool(e < f); + \\ _ = &h; \\ var i: c_int = @intFromBool(g < h); + \\ _ = &i; \\ return i; \\} }); @@ -2646,7 +2740,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn max(arg_a: c_int, arg_b: c_int) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var b = arg_b; + \\ _ = &b; \\ if (a == b) return a; \\ if (a != b) return b; \\ return a; @@ -2663,6 +2759,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub const yes = [*c]u8; \\pub export fn foo() void { \\ var a: yes = undefined; + \\ _ = &a; \\ if (a != null) { \\ _ = @as(c_int, 2); \\ } @@ -2682,6 +2779,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ return blk: { \\ var a: c_int = 1; \\ _ = &a; + \\ _ = &a; \\ break :blk a; \\ }; \\} @@ -2707,6 +2805,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub export var b: f32 = 2.0; \\pub export fn foo() void { \\ var c: [*c]struct_Foo = undefined; + \\ _ = &c; \\ _ = a.b; \\ _ = c.*.b; \\} @@ -2726,6 +2825,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub export var array: [100]c_int = [1]c_int{0} ** 100; \\pub export fn foo(arg_index: c_int) c_int { \\ var index = arg_index; + \\ _ = &index; \\ return array[@as(c_uint, @intCast(index))]; \\} , @@ -2740,7 +2840,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: [10]c_int = undefined; + \\ _ = &a; \\ var i: c_int = 0; + \\ _ = &i; \\ a[@as(c_uint, @intCast(i))] = 0; \\} }); @@ -2753,7 +2855,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: [10]c_longlong = undefined; + \\ _ = &a; \\ var i: c_longlong = 0; + \\ _ = &i; \\ a[@as(usize, @intCast(i))] = 0; \\} }); @@ -2766,7 +2870,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: [10]c_uint = undefined; + \\ _ = &a; \\ var i: c_uint = 0; + \\ _ = &i; \\ a[i] = 0; \\} }); @@ -2776,6 +2882,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\int bar(int x) { return x; } , &[_][]const u8{ \\pub inline fn CALL(arg: anytype) @TypeOf(bar(arg)) { + \\ _ = &arg; \\ return bar(arg); \\} }); @@ -2801,7 +2908,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn max(arg_a: c_int, arg_b: c_int) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var b = arg_b; + \\ _ = &b; \\ if ((a < b) or (a == b)) return b; \\ if ((a >= b) and (a == b)) return a; \\ return a; @@ -2823,7 +2932,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn max(arg_a: c_int, arg_b: c_int) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var b = arg_b; + \\ _ = &b; \\ if (a < b) return b; \\ if (a < b) return b else return a; \\ if (a < b) {} else {} @@ -2874,9 +2985,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\; \\pub export fn if_none_bool(arg_a: c_int, arg_b: f32, arg_c: ?*anyopaque, arg_d: enum_SomeEnum) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var b = arg_b; + \\ _ = &b; \\ var c = arg_c; + \\ _ = &c; \\ var d = arg_d; + \\ _ = &d; \\ if (a != 0) return 0; \\ if (b != 0) return 1; \\ if (c != null) return 2; @@ -2904,6 +3019,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn abs(arg_a: c_int) c_int { \\ var a = arg_a; + \\ _ = &a; \\ return if (a < @as(c_int, 0)) -a else a; \\} }); @@ -2924,16 +3040,19 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo1(arg_a: c_uint) c_uint { \\ var a = arg_a; + \\ _ = &a; \\ a +%= 1; \\ return a; \\} \\pub export fn foo2(arg_a: c_int) c_int { \\ var a = arg_a; + \\ _ = &a; \\ a += 1; \\ return a; \\} \\pub export fn foo3(arg_a: [*c]c_int) [*c]c_int { \\ var a = arg_a; + \\ _ = &a; \\ a += 1; \\ return a; \\} @@ -2959,7 +3078,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\} \\pub export fn bar() void { \\ var f: ?*const fn () callconv(.C) void = &foo; + \\ _ = &f; \\ var b: ?*const fn () callconv(.C) c_int = &baz; + \\ _ = &b; \\ f.?(); \\ f.?(); \\ foo(); @@ -2985,7 +3106,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var i: c_int = 0; + \\ _ = &i; \\ var u: c_uint = 0; + \\ _ = &u; \\ i += 1; \\ i -= 1; \\ u +%= 1; @@ -3024,7 +3147,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn log2(arg_a: c_uint) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var i: c_int = 0; + \\ _ = &i; \\ while (a > @as(c_uint, @bitCast(@as(c_int, 0)))) { \\ a >>= @intCast(@as(c_int, 1)); \\ } @@ -3044,7 +3169,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn log2(arg_a: u32) c_int { \\ var a = arg_a; + \\ _ = &a; \\ var i: c_int = 0; + \\ _ = &i; \\ while (a > @as(u32, @bitCast(@as(c_int, 0)))) { \\ a >>= @intCast(@as(c_int, 1)); \\ } @@ -3072,7 +3199,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = 0; + \\ _ = &a; \\ var b: c_uint = 0; + \\ _ = &b; \\ a += blk: { \\ const ref = &a; \\ ref.* += @as(c_int, 1); @@ -3151,6 +3280,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_uint = 0; + \\ _ = &a; \\ a +%= blk: { \\ const ref = &a; \\ ref.* +%= @as(c_uint, @bitCast(@as(c_int, 1))); @@ -3210,7 +3340,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var i: c_int = 0; + \\ _ = &i; \\ var u: c_uint = 0; + \\ _ = &u; \\ i += 1; \\ i -= 1; \\ u +%= 1; @@ -3305,6 +3437,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\pub fn bar() callconv(.C) void {} \\pub export fn foo(arg_baz: ?*const fn () callconv(.C) [*c]c_int) void { \\ var baz = arg_baz; + \\ _ = &baz; \\ bar(); \\ _ = baz.?(); \\} @@ -3375,10 +3508,14 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\#define MAX(a, b) ((b) > (a) ? (b) : (a)) , &[_][]const u8{ \\pub inline fn MIN(a: anytype, b: anytype) @TypeOf(if (b < a) b else a) { + \\ _ = &a; + \\ _ = &b; \\ return if (b < a) b else a; \\} , \\pub inline fn MAX(a: anytype, b: anytype) @TypeOf(if (b > a) b else a) { + \\ _ = &a; + \\ _ = &b; \\ return if (b > a) b else a; \\} }); @@ -3390,7 +3527,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo(arg_p: [*c]c_int, arg_x: c_int) c_int { \\ var p = arg_p; + \\ _ = &p; \\ var x = arg_x; + \\ _ = &x; \\ return blk: { \\ const tmp = x; \\ (blk_1: { @@ -3417,6 +3556,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\} \\pub export fn bar(arg_x: c_long) c_ushort { \\ var x = arg_x; + \\ _ = &x; \\ return @as(c_ushort, @bitCast(@as(c_short, @truncate(x)))); \\} }); @@ -3429,6 +3569,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo(arg_bar_1: c_int) void { \\ var bar_1 = arg_bar_1; + \\ _ = &bar_1; \\ bar_1 = 2; \\} \\pub export var bar: c_int = 4; @@ -3442,6 +3583,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo(arg_bar_1: c_int) void { \\ var bar_1 = arg_bar_1; + \\ _ = &bar_1; \\ bar_1 = 2; \\} , @@ -3475,10 +3617,12 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\} \\pub export fn bar(arg_a: [*c]const c_int) void { \\ var a = arg_a; + \\ _ = &a; \\ foo(@as([*c]c_int, @ptrCast(@volatileCast(@constCast(a))))); \\} \\pub export fn baz(arg_a: [*c]volatile c_int) void { \\ var a = arg_a; + \\ _ = &a; \\ foo(@as([*c]c_int, @ptrCast(@volatileCast(@constCast(a))))); \\} }); @@ -3493,9 +3637,13 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo(arg_x: bool) bool { \\ var x = arg_x; + \\ _ = &x; \\ var a: bool = @as(c_int, @intFromBool(x)) != @as(c_int, 1); + \\ _ = &a; \\ var b: bool = @as(c_int, @intFromBool(a)) != @as(c_int, 0); + \\ _ = &b; \\ var c: bool = @intFromPtr(&foo) != 0; + \\ _ = &c; \\ return foo(@as(c_int, @intFromBool(c)) != @as(c_int, @intFromBool(b))); \\} }); @@ -3506,7 +3654,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\} , &[_][]const u8{ \\pub export fn max(x: c_int, arg_y: c_int) c_int { + \\ _ = &x; \\ var y = arg_y; + \\ _ = &y; \\ return if (x > y) x else y; \\} }); @@ -3567,6 +3717,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ , &[_][]const u8{ \\pub inline fn DefaultScreen(dpy: anytype) @TypeOf(@import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.default_screen) { + \\ _ = &dpy; \\ return @import("std").zig.c_translation.cast(_XPrivDisplay, dpy).*.default_screen; \\} }); @@ -3809,6 +3960,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { \\ const foo = struct { \\ var static: struct_FOO = @import("std").mem.zeroes(struct_FOO); \\ }; + \\ _ = &foo; \\ return foo.static.x; \\} }); @@ -3830,12 +3982,14 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn bar(arg_x: c_int, arg_y: c_int) c_int { \\ var x = arg_x; + \\ _ = &x; \\ var y = arg_y; \\ _ = &y; \\ return x; \\} , \\pub inline fn FOO(A: anytype, B: anytype) @TypeOf(A) { + \\ _ = &A; \\ _ = &B; \\ return A; \\} @@ -3911,6 +4065,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: c_int = undefined; + \\ _ = &a; \\ if ((blk: { \\ const tmp = @intFromBool(@as(c_int, 1) > @as(c_int, 0)); \\ a = tmp; @@ -3929,7 +4084,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: S = undefined; + \\ _ = &a; \\ var b: S = undefined; + \\ _ = &b; \\ var c: c_longlong = @divExact(@as(c_longlong, @bitCast(@intFromPtr(a) -% @intFromPtr(b))), @sizeOf(u8)); \\ _ = &c; \\} @@ -3944,7 +4101,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var a: S = undefined; + \\ _ = &a; \\ var b: S = undefined; + \\ _ = &b; \\ var c: c_long = @divExact(@as(c_long, @bitCast(@intFromPtr(a) -% @intFromPtr(b))), @sizeOf(u8)); \\ _ = &c; \\} @@ -3973,7 +4132,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var n: c_int = undefined; + \\ _ = &n; \\ var tmp: c_int = 1; + \\ _ = &tmp; \\ if ((blk: { \\ const tmp_1 = tmp; \\ n = tmp_1; @@ -3990,7 +4151,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var tmp: c_int = undefined; + \\ _ = &tmp; \\ var n: c_int = 1; + \\ _ = &n; \\ if ((blk: { \\ const tmp_1 = n; \\ tmp = tmp_1; @@ -4007,7 +4170,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var n: c_int = undefined; + \\ _ = &n; \\ var ref: c_int = 1; + \\ _ = &ref; \\ if ((blk: { \\ const tmp = blk_1: { \\ const ref_2 = &ref; @@ -4028,7 +4193,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var n: c_int = undefined; + \\ _ = &n; \\ var ref: c_int = 1; + \\ _ = &ref; \\ if ((blk: { \\ const tmp = blk_1: { \\ const ref_2 = &ref; @@ -4050,7 +4217,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var n: c_int = undefined; + \\ _ = &n; \\ var ref: c_int = 1; + \\ _ = &ref; \\ if ((blk: { \\ const ref_1 = &n; \\ ref_1.* += ref; @@ -4067,7 +4236,9 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var ref: c_int = undefined; + \\ _ = &ref; \\ var n: c_int = 1; + \\ _ = &n; \\ if ((blk: { \\ const ref_1 = &ref; \\ ref_1.* += n; @@ -4085,8 +4256,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var f: c_int = 1; + \\ _ = &f; \\ var n: c_int = undefined; + \\ _ = &n; \\ var cond_temp: c_int = 1; + \\ _ = &cond_temp; \\ if ((blk: { \\ const tmp = blk_1: { \\ const cond_temp_2 = cond_temp; @@ -4107,8 +4281,11 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn foo() void { \\ var cond_temp: c_int = 1; + \\ _ = &cond_temp; \\ var n: c_int = undefined; + \\ _ = &n; \\ var f: c_int = 1; + \\ _ = &f; \\ if ((blk: { \\ const tmp = blk_1: { \\ const cond_temp_2 = f; @@ -4149,6 +4326,7 @@ pub fn addCases(cases: *tests.TranslateCContext) void { , &[_][]const u8{ \\pub export fn somefunc() void { \\ var y: c_int = undefined; + \\ _ = &y; \\ _ = blk: { \\ y = 1; \\ }; -- cgit v1.2.3