Skip to content

Commit

Permalink
all: fix unnecessary uses of 'var'
Browse files Browse the repository at this point in the history
These were noticed downstream, since I am in the process of implementing
an error for uses of 'var' when one provably could have used 'const'.

Note that the changes in 'deps' are not currently in the Zig codebase,
but will be a part of an imminent PR there. I thought it made sense to
make them now to avoid having to sync this code once the new error is
introduced.
  • Loading branch information
mlugg authored and Vexu committed Nov 14, 2023
1 parent e245be7 commit 623404a
Show file tree
Hide file tree
Showing 14 changed files with 32 additions and 33 deletions.
6 changes: 3 additions & 3 deletions build/GenerateDef.zig
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ fn generate(self: *GenerateDef, input: []const u8) ![]const u8 {
}

{
var sorted_list = try arena.dupe([]const u8, values.keys());
const sorted_list = try arena.dupe([]const u8, values.keys());
defer arena.free(sorted_list);
std.mem.sort([]const u8, sorted_list, {}, struct {
pub fn lessThan(_: void, a: []const u8, b: []const u8) bool {
Expand Down Expand Up @@ -460,7 +460,7 @@ const DafsaBuilder = struct {
var arena = std.heap.ArenaAllocator.init(allocator);
errdefer arena.deinit();

var root = try arena.allocator().create(Node);
const root = try arena.allocator().create(Node);
root.* = .{};
return DafsaBuilder{
.root = root,
Expand Down Expand Up @@ -540,7 +540,7 @@ const DafsaBuilder = struct {
std.debug.assert(node.children[c] == null);

var arena = self.arena.promote(self.allocator);
var child = try arena.allocator().create(Node);
const child = try arena.allocator().create(Node);
self.arena = arena.state;

child.* = .{};
Expand Down
3 changes: 1 addition & 2 deletions deps/zig/arch/x86_64/Disassembler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion deps/zig/arch/x86_64/Lower.zig
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ fn emit(lower: *Lower, prefix: Prefix, mnemonic: Mnemonic, ops: []const Operand)
.Obj => true,
.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];
Expand Down
2 changes: 1 addition & 1 deletion deps/zig/arch/x86_64/encoder.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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())}),
Expand Down
2 changes: 1 addition & 1 deletion src/aro/Compilation.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1142,7 +1142,7 @@ pub fn addSourceFromOwnedBuffer(comp: *Compilation, buf: []u8, path: []const u8,
if (i != contents.len) contents = try comp.gpa.realloc(contents, i);
errdefer @compileError("errdefers in callers would possibly free the realloced slice using the original len");

var source = Source{
const source = Source{
.id = source_id,
.path = duped_path,
.buf = contents,
Expand Down
18 changes: 9 additions & 9 deletions src/aro/Parser.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1651,7 +1651,7 @@ fn gnuAttributeList(p: *Parser) Error!void {

fn c23AttributeList(p: *Parser) Error!void {
while (p.tok_ids[p.tok_i] != .r_bracket) {
var namespace_tok = try p.expectIdentifier();
const namespace_tok = try p.expectIdentifier();
var namespace: ?[]const u8 = null;
if (p.eatToken(.colon_colon)) |_| {
namespace = p.tokSlice(namespace_tok);
Expand Down Expand Up @@ -3209,7 +3209,7 @@ fn paramDecls(p: *Parser, d: *Declarator) Error!?[]Type.Func.Param {
fn typeName(p: *Parser) Error!?Type {
const attr_buf_top = p.attr_buf.len;
defer p.attr_buf.len = attr_buf_top;
var ty = (try p.specQual()) orelse return null;
const ty = (try p.specQual()) orelse return null;
if (try p.declarator(ty, .abstract)) |some| {
if (some.old_style_func) |tok_i| try p.errTok(.invalid_old_style_params, tok_i);
return try Attribute.applyTypeAttributes(p, some.ty, attr_buf_top, .align_ignored);
Expand Down Expand Up @@ -3636,7 +3636,7 @@ fn coerceArrayInit(p: *Parser, item: *Result, tok: TokenIndex, target: Type) !bo

if (target.get(.array)) |arr_ty| {
assert(item.ty.specifier == .array);
var len = item.ty.arrayLen().?;
const len = item.ty.arrayLen().?;
const array_len = arr_ty.arrayLen().?;
if (is_str_lit) {
// the null byte of a string can be dropped
Expand Down Expand Up @@ -5222,7 +5222,7 @@ pub const Result = struct {

fn lvalConversion(res: *Result, p: *Parser) Error!void {
if (res.ty.isFunc()) {
var elem_ty = try p.arena.create(Type);
const elem_ty = try p.arena.create(Type);
elem_ty.* = res.ty;
res.ty.specifier = .pointer;
res.ty.data = .{ .sub_type = elem_ty };
Expand Down Expand Up @@ -6114,7 +6114,7 @@ fn condExpr(p: *Parser) Error!Result {
}

// Prepare for possible binary conditional expression.
var maybe_colon = p.eatToken(.colon);
const maybe_colon = p.eatToken(.colon);

// Depending on the value of the condition, avoid evaluating unreachable branches.
var then_expr = blk: {
Expand Down Expand Up @@ -6506,7 +6506,7 @@ fn typesCompatible(p: *Parser) Error!Result {

const compatible = first_unqual.eql(second_unqual, p.comp, true);

var res = Result{
const res = Result{
.val = Value.fromBool(compatible),
.node = try p.addNode(.{ .tag = .builtin_types_compatible_p, .ty = Type.int, .data = .{ .bin = .{
.lhs = lhs,
Expand Down Expand Up @@ -7772,9 +7772,9 @@ fn stringLiteral(p: *Parser) Error!Result {
switch (char_width) {
.@"1" => p.strings.appendSliceAssumeCapacity(view.bytes),
.@"2" => {
var capacity_slice: []align(@alignOf(u16)) u8 = @alignCast(p.strings.unusedCapacitySlice());
const capacity_slice: []align(@alignOf(u16)) u8 = @alignCast(p.strings.unusedCapacitySlice());
const dest_len = std.mem.alignBackward(usize, capacity_slice.len, 2);
var dest = std.mem.bytesAsSlice(u16, capacity_slice[0..dest_len]);
const dest = std.mem.bytesAsSlice(u16, capacity_slice[0..dest_len]);
const words_written = std.unicode.utf8ToUtf16Le(dest, view.bytes) catch unreachable;
p.strings.resize(p.strings.items.len + words_written * 2) catch unreachable;
},
Expand Down Expand Up @@ -7915,7 +7915,7 @@ fn charLiteral(p: *Parser) Error!Result {
else
p.comp.types.intmax;

var res = Result{
const res = Result{
.ty = if (p.in_macro) macro_ty else ty,
.val = try Value.int(val, p.comp),
.node = try p.addNode(.{ .tag = .char_literal, .ty = ty, .data = undefined }),
Expand Down
4 changes: 2 additions & 2 deletions src/aro/Preprocessor.zig
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ pub fn tokenize(pp: *Preprocessor, source: Source) Error!Token {
try pp.tokens.ensureTotalCapacity(pp.gpa, pp.tokens.len + estimated_token_count);

while (true) {
var tok = tokenizer.next();
const tok = tokenizer.next();
if (tok.id == .eof) return tokFromRaw(tok);
try pp.tokens.append(pp.gpa, tokFromRaw(tok));
}
Expand Down Expand Up @@ -797,7 +797,7 @@ fn expr(pp: *Preprocessor, tokenizer: *Tokenizer) MacroError!bool {

pp.top_expansion_buf.items.len = 0;
const eof = while (true) {
var tok = tokenizer.next();
const tok = tokenizer.next();
switch (tok.id) {
.nl, .eof => break tok,
.whitespace => if (pp.top_expansion_buf.items.len == 0) continue,
Expand Down
8 changes: 4 additions & 4 deletions src/aro/Type.zig
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,10 @@ pub const Attributed = struct {
base: Type,

pub fn create(allocator: std.mem.Allocator, base: Type, existing_attributes: []const Attribute, attributes: []const Attribute) !*Attributed {
var attributed_type = try allocator.create(Attributed);
const attributed_type = try allocator.create(Attributed);
errdefer allocator.destroy(attributed_type);

var all_attrs = try allocator.alloc(Attribute, existing_attributes.len + attributes.len);
const all_attrs = try allocator.alloc(Attribute, existing_attributes.len + attributes.len);
std.mem.copy(Attribute, all_attrs, existing_attributes);
std.mem.copy(Attribute, all_attrs[existing_attributes.len..], attributes);

Expand Down Expand Up @@ -1715,15 +1715,15 @@ pub const Builder = struct {
// TODO this really should be easier
switch (ty.specifier) {
.array, .static_array, .incomplete_array => {
var old = ty.data.array;
const old = ty.data.array;
ty.data.array = try p.arena.create(Array);
ty.data.array.* = .{
.len = old.len,
.elem = elem,
};
},
.variable_len_array, .unspecified_variable_len_array => {
var old = ty.data.expr;
const old = ty.data.expr;
ty.data.expr = try p.arena.create(Expr);
ty.data.expr.* = .{
.node = old.node,
Expand Down
2 changes: 1 addition & 1 deletion src/aro/Value.zig
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ pub fn mul(res: *Value, lhs: Value, rhs: Value, ty: Type, comp: *Compilation) !b
defer comp.gpa.free(limbs);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };

var limbs_buffer = try comp.gpa.alloc(
const limbs_buffer = try comp.gpa.alloc(
std.math.big.Limb,
std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1),
);
Expand Down
2 changes: 1 addition & 1 deletion src/aro/pragmas/message.zig
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn init(allocator: mem.Allocator) !*Pragma {
}

fn deinit(pragma: *Pragma, comp: *Compilation) void {
var self = @fieldParentPtr(Message, "pragma", pragma);
const self = @fieldParentPtr(Message, "pragma", pragma);
comp.gpa.destroy(self);
}

Expand Down
6 changes: 3 additions & 3 deletions src/backend/Object/Elf.zig
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ pub fn finish(elf: *Elf, file: std.fs.File) !void {
const sh_offset = strtab_offset + elf.strtab_len;
const sh_offset_aligned = std.mem.alignForward(u64, sh_offset, 16);

var elf_header = std.elf.Elf64_Ehdr{
const elf_header = std.elf.Elf64_Ehdr{
.e_ident = .{ 0x7F, 'E', 'L', 'F', 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
.e_type = std.elf.ET.REL, // we only produce relocatables
.e_machine = elf.obj.target.cpu.arch.toElfMachine(),
Expand Down Expand Up @@ -299,7 +299,7 @@ pub fn finish(elf: *Elf, file: std.fs.File) !void {

// write strtab section header
{
var sect_header = std.elf.Elf64_Shdr{
const sect_header = std.elf.Elf64_Shdr{
.sh_name = strtab_name,
.sh_type = std.elf.SHT_STRTAB,
.sh_flags = 0,
Expand All @@ -316,7 +316,7 @@ pub fn finish(elf: *Elf, file: std.fs.File) !void {

// write symtab section header
{
var sect_header = std.elf.Elf64_Shdr{
const sect_header = std.elf.Elf64_Shdr{
.sh_name = symtab_name,
.sh_type = std.elf.SHT_SYMTAB,
.sh_flags = 0,
Expand Down
2 changes: 1 addition & 1 deletion test/fuzz/fuzz_lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export fn compile_c_buf(buf: [*]const u8, len: c_int) void {

fn compileSlice(buf: []const u8) !void {
var fixed_allocator = std.heap.FixedBufferAllocator.init(fixed_buffer_mem[0..]);
var allocator = fixed_allocator.allocator();
const allocator = fixed_allocator.allocator();

var comp = Compilation.init(allocator);
defer comp.deinit();
Expand Down
6 changes: 3 additions & 3 deletions test/record_runner.zig
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const Stats = struct {
};

fn recordResult(self: *Stats, kind: ResultKind) void {
var ptr = switch (kind) {
const ptr = switch (kind) {
.ok => &self.ok_count,
.fail => &self.fail_count,
.skip => &self.skip_count,
Expand Down Expand Up @@ -96,7 +96,7 @@ pub fn main() !void {
const gpa = general_purpose_allocator.allocator();
defer if (general_purpose_allocator.deinit() == .leak) std.process.exit(1);

var args = try std.process.argsAlloc(gpa);
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);

if (args.len != 2) {
Expand Down Expand Up @@ -188,7 +188,7 @@ pub fn main() !void {

fn runTestCases(allocator: std.mem.Allocator, test_dir: []const u8, wg: *std.Thread.WaitGroup, test_cases: []const TestCase, stride: usize, stats: *Stats) void {
defer wg.finish();
var mem = allocator.alloc(u8, MAX_MEM_PER_TEST) catch |err| {
const mem = allocator.alloc(u8, MAX_MEM_PER_TEST) catch |err| {
std.log.err("{s}", .{@errorName(err)});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
Expand Down
2 changes: 1 addition & 1 deletion test/runner.zig
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ pub fn main() !void {
const gpa = general_purpose_allocator.allocator();
defer if (general_purpose_allocator.deinit() == .leak) std.process.exit(1);

var args = try std.process.argsAlloc(gpa);
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);

if (args.len != 3) {
Expand Down

0 comments on commit 623404a

Please sign in to comment.