Skip to content

zig fmt: canonicalize nested cast builtin order #24199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/compiler_rt/memcpy.zig
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ inline fn copyForwards(
const d = dest + alignment_offset;
const s = src + alignment_offset;

copyBlocksAlignedSource(@ptrCast(d), @alignCast(@ptrCast(s)), n);
copyBlocksAlignedSource(@ptrCast(d), @ptrCast(@alignCast(s)), n);

// copy last `@sizeOf(Element)` bytes unconditionally, since block copy
// methods only copy a multiple of `@sizeOf(Element)` bytes.
Expand Down
2 changes: 1 addition & 1 deletion lib/compiler_rt/memmove.zig
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ inline fn copyForwards(
const d = dest + alignment_offset;
const s = src + alignment_offset;

copyBlocksAlignedSource(@ptrCast(d), @alignCast(@ptrCast(s)), n);
copyBlocksAlignedSource(@ptrCast(d), @ptrCast(@alignCast(s)), n);

// copy last `copy_size` bytes unconditionally, since block copy
// methods only copy a multiple of `copy_size` bytes.
Expand Down
2 changes: 1 addition & 1 deletion lib/fuzzer/web/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export fn coveredSourceLocations() usize {
}

fn getCoverageUpdateHeader() *abi.CoverageUpdateHeader {
return @alignCast(@ptrCast(recent_coverage_update.items[0..@sizeOf(abi.CoverageUpdateHeader)]));
return @ptrCast(@alignCast(recent_coverage_update.items[0..@sizeOf(abi.CoverageUpdateHeader)]));
}

export fn totalRuns() u64 {
Expand Down
4 changes: 2 additions & 2 deletions lib/std/array_hash_map.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2086,7 +2086,7 @@ const IndexHeader = struct {
/// Returns the attached array of indexes. I must match the type
/// returned by capacityIndexType.
fn indexes(header: *IndexHeader, comptime I: type) []Index(I) {
const start_ptr: [*]Index(I) = @alignCast(@ptrCast(@as([*]u8, @ptrCast(header)) + @sizeOf(IndexHeader)));
const start_ptr: [*]Index(I) = @ptrCast(@alignCast(@as([*]u8, @ptrCast(header)) + @sizeOf(IndexHeader)));
return start_ptr[0..header.length()];
}

Expand Down Expand Up @@ -2122,7 +2122,7 @@ const IndexHeader = struct {
const nbytes = @sizeOf(IndexHeader) + index_size * len;
const bytes = try gpa.alignedAlloc(u8, .of(IndexHeader), nbytes);
@memset(bytes[@sizeOf(IndexHeader)..], 0xff);
const result: *IndexHeader = @alignCast(@ptrCast(bytes.ptr));
const result: *IndexHeader = @ptrCast(@alignCast(bytes.ptr));
result.* = .{
.bit_index = new_bit_index,
};
Expand Down
2 changes: 1 addition & 1 deletion lib/std/crypto/codecs/asn1/der/Encoder.zig
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn anyTag(self: *Encoder, tag_: Tag, val: anytype) !void {
// > The encoding of a set value or sequence value shall not include an encoding for any
// > component value which is equal to its default value.
const is_default = if (f.is_comptime) false else if (f.default_value_ptr) |v| brk: {
const default_val: *const f.type = @alignCast(@ptrCast(v));
const default_val: *const f.type = @ptrCast(@alignCast(v));
break :brk std.mem.eql(u8, std.mem.asBytes(default_val), std.mem.asBytes(&field_val));
} else false;

Expand Down
2 changes: 1 addition & 1 deletion lib/std/crypto/timing_safe.zig
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ fn markSecret(ptr: anytype, comptime action: enum { classify, declassify }) void
@compileError("A pointer value is always assumed leak information via side channels");
},
else => {
const mem8: *const [@sizeOf(@TypeOf(ptr.*))]u8 = @constCast(@ptrCast(ptr));
const mem8: *const [@sizeOf(@TypeOf(ptr.*))]u8 = @ptrCast(@constCast(ptr));
if (action == .classify) {
std.valgrind.memcheck.makeMemUndefined(mem8);
} else {
Expand Down
2 changes: 1 addition & 1 deletion lib/std/debug/SelfInfo.zig
Original file line number Diff line number Diff line change
Expand Up @@ -836,7 +836,7 @@ pub const WindowsModule = struct {

pub fn deinit(self: @This()) void {
const process_handle = windows.GetCurrentProcess();
assert(windows.ntdll.NtUnmapViewOfSection(process_handle, @constCast(@ptrCast(self.section_view.ptr))) == .SUCCESS);
assert(windows.ntdll.NtUnmapViewOfSection(process_handle, @ptrCast(@constCast(self.section_view.ptr))) == .SUCCESS);
windows.CloseHandle(self.section_handle);
self.file.close();
}
Expand Down
2 changes: 1 addition & 1 deletion lib/std/hash_map.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1511,7 +1511,7 @@ pub fn HashMapUnmanaged(

const total_size = std.mem.alignForward(usize, vals_end, max_align);

const slice = @as([*]align(max_align) u8, @alignCast(@ptrCast(self.header())))[0..total_size];
const slice = @as([*]align(max_align) u8, @ptrCast(@alignCast(self.header())))[0..total_size];
allocator.free(slice);

self.metadata = null;
Expand Down
2 changes: 1 addition & 1 deletion lib/std/heap.zig
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ const CAllocator = struct {
};

fn getHeader(ptr: [*]u8) *[*]u8 {
return @alignCast(@ptrCast(ptr - @sizeOf(usize)));
return @ptrCast(@alignCast(ptr - @sizeOf(usize)));
}

fn alignedAlloc(len: usize, alignment: Alignment) ?[*]u8 {
Expand Down
2 changes: 1 addition & 1 deletion lib/std/heap/SmpAllocator.zig
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ fn free(context: *anyopaque, memory: []u8, alignment: mem.Alignment, ra: usize)
return PageAllocator.unmap(@alignCast(memory));
}

const node: *usize = @alignCast(@ptrCast(memory.ptr));
const node: *usize = @ptrCast(@alignCast(memory.ptr));

const t = Thread.lock();
defer t.unlock();
Expand Down
2 changes: 1 addition & 1 deletion lib/std/heap/debug_allocator.zig
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ pub fn DebugAllocator(comptime config: Config) type {

fn usedBits(bucket: *BucketHeader, index: usize) *usize {
const ptr: [*]u8 = @ptrCast(bucket);
const bits: [*]usize = @alignCast(@ptrCast(ptr + @sizeOf(BucketHeader)));
const bits: [*]usize = @ptrCast(@alignCast(ptr + @sizeOf(BucketHeader)));
return &bits[index];
}

Expand Down
8 changes: 4 additions & 4 deletions lib/std/http/Server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ pub const Request = struct {
};

fn read_cl(context: *const anyopaque, buffer: []u8) ReadError!usize {
const request: *Request = @constCast(@alignCast(@ptrCast(context)));
const request: *Request = @ptrCast(@alignCast(@constCast(context)));
const s = request.server;

const remaining_content_length = &request.reader_state.remaining_content_length;
Expand Down Expand Up @@ -653,7 +653,7 @@ pub const Request = struct {
}

fn read_chunked(context: *const anyopaque, buffer: []u8) ReadError!usize {
const request: *Request = @constCast(@alignCast(@ptrCast(context)));
const request: *Request = @ptrCast(@alignCast(@constCast(context)));
const s = request.server;

const cp = &request.reader_state.chunk_parser;
Expand Down Expand Up @@ -895,7 +895,7 @@ pub const Response = struct {
}

fn write_cl(context: *const anyopaque, bytes: []const u8) WriteError!usize {
const r: *Response = @constCast(@alignCast(@ptrCast(context)));
const r: *Response = @ptrCast(@alignCast(@constCast(context)));

var trash: u64 = std.math.maxInt(u64);
const len = switch (r.transfer_encoding) {
Expand Down Expand Up @@ -945,7 +945,7 @@ pub const Response = struct {
}

fn write_chunked(context: *const anyopaque, bytes: []const u8) WriteError!usize {
const r: *Response = @constCast(@alignCast(@ptrCast(context)));
const r: *Response = @ptrCast(@alignCast(@constCast(context)));
assert(r.transfer_encoding == .chunked);

if (r.elide_body)
Expand Down
4 changes: 2 additions & 2 deletions lib/std/io.zig
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ pub fn GenericReader(
const Self = @This();

fn typeErasedReadFn(context: *const anyopaque, buffer: []u8) anyerror!usize {
const ptr: *const Context = @alignCast(@ptrCast(context));
const ptr: *const Context = @ptrCast(@alignCast(context));
return readFn(ptr.*, buffer);
}
};
Expand Down Expand Up @@ -344,7 +344,7 @@ pub fn GenericWriter(
}

fn typeErasedWriteFn(context: *const anyopaque, bytes: []const u8) anyerror!usize {
const ptr: *const Context = @alignCast(@ptrCast(context));
const ptr: *const Context = @ptrCast(@alignCast(context));
return writeFn(ptr.*, bytes);
}
};
Expand Down
2 changes: 1 addition & 1 deletion lib/std/os/windows.zig
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ pub fn CreatePipe(rd: *HANDLE, wr: *HANDLE, sattr: *const SECURITY_ATTRIBUTES) C
const name = UNICODE_STRING{
.Length = len,
.MaximumLength = len,
.Buffer = @constCast(@ptrCast(str)),
.Buffer = @ptrCast(@constCast(str)),
};
const attrs = OBJECT_ATTRIBUTES{
.ObjectName = @constCast(&name),
Expand Down
4 changes: 2 additions & 2 deletions lib/std/pie.zig
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ pub fn relocate(phdrs: []const elf.Phdr) void {

const rel = sorted_dynv[elf.DT_REL];
if (rel != 0) {
const rels: []const elf.Rel = @alignCast(@ptrCast(
const rels: []const elf.Rel = @ptrCast(@alignCast(
@as([*]align(@alignOf(elf.Rel)) const u8, @ptrFromInt(base_addr + rel))[0..sorted_dynv[elf.DT_RELSZ]],
));
for (rels) |r| {
Expand All @@ -275,7 +275,7 @@ pub fn relocate(phdrs: []const elf.Phdr) void {

const rela = sorted_dynv[elf.DT_RELA];
if (rela != 0) {
const relas: []const elf.Rela = @alignCast(@ptrCast(
const relas: []const elf.Rela = @ptrCast(@alignCast(
@as([*]align(@alignOf(elf.Rela)) const u8, @ptrFromInt(base_addr + rela))[0..sorted_dynv[elf.DT_RELASZ]],
));
for (relas) |r| {
Expand Down
2 changes: 1 addition & 1 deletion lib/std/zig/c_translation.zig
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ fn castInt(comptime DestType: type, target: anytype) DestType {
}

fn castPtr(comptime DestType: type, target: anytype) DestType {
return @constCast(@volatileCast(@alignCast(@ptrCast(target))));
return @ptrCast(@alignCast(@constCast(@volatileCast(target))));
}

fn castToPtr(comptime DestType: type, comptime SourceType: type, target: anytype) DestType {
Expand Down
52 changes: 51 additions & 1 deletion lib/std/zig/render.zig
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,57 @@ fn renderExpression(r: *Render, node: Ast.Node.Index, space: Space) Error!void {
=> {
var buf: [2]Ast.Node.Index = undefined;
const params = tree.builtinCallParams(&buf, node).?;
return renderBuiltinCall(r, tree.nodeMainToken(node), params, space);
var builtin_token = tree.nodeMainToken(node);

if (params.len == 1) canonicalize: {
const CastKind = enum {
ptr,
@"align",
addrSpace,
@"const",
@"volatile",
};
const kind = blk: {
const slice = tree.tokenSlice(builtin_token);
if (!mem.endsWith(u8, slice, "Cast")) break :canonicalize;
const end = slice.len - "Cast".len;
break :blk meta.stringToEnum(CastKind, slice[1..end]) orelse break :canonicalize;
};

var cast_map = std.EnumMap(CastKind, Ast.TokenIndex).init(.{});
cast_map.put(kind, builtin_token);

var casts_before: usize = 0;
if (builtin_token >= 2) {
var prev_builtin_token = builtin_token - 2;
while (tree.tokenTag(prev_builtin_token) == .builtin) : (prev_builtin_token -= 2) {
const slice = tree.tokenSlice(prev_builtin_token);
if (!mem.endsWith(u8, slice, "Cast")) break;
const end = slice.len - "Cast".len;
const prev_kind = meta.stringToEnum(CastKind, slice[1..end]) orelse break;
if (cast_map.contains(prev_kind)) break :canonicalize;
cast_map.put(prev_kind, prev_builtin_token);
casts_before += 1;
}
}

var next_builtin_token = builtin_token + 2;
while (tree.tokenTag(next_builtin_token) == .builtin) : (next_builtin_token += 2) {
const slice = tree.tokenSlice(next_builtin_token);
if (!mem.endsWith(u8, slice, "Cast")) break;
const end = slice.len - "Cast".len;
const next_kind = meta.stringToEnum(CastKind, slice[1..end]) orelse break;
if (cast_map.contains(next_kind)) break :canonicalize;
cast_map.put(next_kind, next_builtin_token);
}

var it = cast_map.iterator();
builtin_token = it.next().?.value.*;
while (casts_before > 0) : (casts_before -= 1) {
builtin_token = it.next().?.value.*;
}
}
return renderBuiltinCall(r, builtin_token, params, space);
},

.fn_proto_simple,
Expand Down
14 changes: 7 additions & 7 deletions lib/ubsan_rt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ const Value = extern struct {
}

return switch (size) {
64 => @as(*const u64, @alignCast(@ptrCast(value.handle))).*,
128 => @as(*const u128, @alignCast(@ptrCast(value.handle))).*,
64 => @as(*const u64, @ptrCast(@alignCast(value.handle))).*,
128 => @as(*const u128, @ptrCast(@alignCast(value.handle))).*,
else => @trap(),
};
}
Expand All @@ -74,8 +74,8 @@ const Value = extern struct {
return (handle << extra_bits) >> extra_bits;
}
return switch (size) {
64 => @as(*const i64, @alignCast(@ptrCast(value.handle))).*,
128 => @as(*const i128, @alignCast(@ptrCast(value.handle))).*,
64 => @as(*const i64, @ptrCast(@alignCast(value.handle))).*,
128 => @as(*const i128, @ptrCast(@alignCast(value.handle))).*,
else => @trap(),
};
}
Expand All @@ -92,9 +92,9 @@ const Value = extern struct {
}, @bitCast(@intFromPtr(value.handle)));
}
return @floatCast(switch (size) {
64 => @as(*const f64, @alignCast(@ptrCast(value.handle))).*,
80 => @as(*const f80, @alignCast(@ptrCast(value.handle))).*,
128 => @as(*const f128, @alignCast(@ptrCast(value.handle))).*,
64 => @as(*const f64, @ptrCast(@alignCast(value.handle))).*,
80 => @as(*const f80, @ptrCast(@alignCast(value.handle))).*,
128 => @as(*const f128, @ptrCast(@alignCast(value.handle))).*,
else => @trap(),
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/InternPool.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1359,7 +1359,7 @@ const Local = struct {
capacity: u32,
};
fn header(list: ListSelf) *Header {
return @alignCast(@ptrCast(list.bytes - bytes_offset));
return @ptrCast(@alignCast(list.bytes - bytes_offset));
}
pub fn view(list: ListSelf) View {
const capacity = list.header().capacity;
Expand Down Expand Up @@ -1568,7 +1568,7 @@ const Shard = struct {
}
};
fn header(map: @This()) *Header {
return @alignCast(@ptrCast(@as([*]u8, @ptrCast(map.entries)) - entries_offset));
return @ptrCast(@alignCast(@as([*]u8, @ptrCast(map.entries)) - entries_offset));
}

const Entry = extern struct {
Expand Down
2 changes: 1 addition & 1 deletion src/Package/Fetch.zig
Original file line number Diff line number Diff line change
Expand Up @@ -882,7 +882,7 @@ const Resource = union(enum) {
}

fn read(context: *const anyopaque, buffer: []u8) anyerror!usize {
const resource: *Resource = @constCast(@ptrCast(@alignCast(context)));
const resource: *Resource = @ptrCast(@alignCast(@constCast(context)));
switch (resource.*) {
.file => |*f| return f.read(buffer),
.http_request => |*r| return r.read(buffer),
Expand Down
4 changes: 2 additions & 2 deletions src/codegen/c.zig
Original file line number Diff line number Diff line change
Expand Up @@ -7966,7 +7966,7 @@ fn arrayListWriter(list: *std.ArrayList(u8)) ArrayListWriter {
.context = list,
.writeFn = struct {
fn write(context: *const anyopaque, bytes: []const u8) anyerror!usize {
const l: *std.ArrayList(u8) = @alignCast(@constCast(@ptrCast(context)));
const l: *std.ArrayList(u8) = @ptrCast(@alignCast(@constCast(context)));
return l.writer().write(bytes);
}
}.write,
Expand Down Expand Up @@ -8005,7 +8005,7 @@ fn IndentWriter(comptime UnderlyingWriter: type) type {
}

fn writeAny(context: *const anyopaque, bytes: []const u8) anyerror!usize {
const self: *Self = @alignCast(@constCast(@ptrCast(context)));
const self: *Self = @ptrCast(@alignCast(@constCast(context)));
return self.write(bytes);
}

Expand Down
6 changes: 3 additions & 3 deletions src/translate_c.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4008,11 +4008,11 @@ fn transCreateCompoundAssign(
}

fn removeCVQualifiers(c: *Context, dst_type_node: Node, expr: Node) Error!Node {
const const_casted = try Tag.const_cast.create(c.arena, expr);
const volatile_casted = try Tag.volatile_cast.create(c.arena, const_casted);
const volatile_casted = try Tag.volatile_cast.create(c.arena, expr);
const const_casted = try Tag.const_cast.create(c.arena, volatile_casted);
return Tag.as.create(c.arena, .{
.lhs = dst_type_node,
.rhs = try Tag.ptr_cast.create(c.arena, volatile_casted),
.rhs = try Tag.ptr_cast.create(c.arena, const_casted),
});
}

Expand Down
2 changes: 1 addition & 1 deletion test/behavior/array.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1126,7 +1126,7 @@ test "initialize pointer to anyopaque with reference to empty array initializer"
const ptr: *const anyopaque = &.{};
// The above acts like an untyped initializer, since the `.{}` has no result type.
// So, `ptr` points in memory to an empty tuple (`@TypeOf(.{})`).
const casted: *const @TypeOf(.{}) = @alignCast(@ptrCast(ptr));
const casted: *const @TypeOf(.{}) = @ptrCast(@alignCast(ptr));
const loaded = casted.*;
// `val` should be a `@TypeOf(.{})`, as expected.
// We can't check the value, but it's zero-bit, so the type matching is good enough.
Expand Down
2 changes: 1 addition & 1 deletion test/behavior/comptime_memory.zig
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ fn GenericIntApplier(
}

fn typeErasedApplyFn(context: *const anyopaque, arg: u32) void {
const ptr: *const Context = @alignCast(@ptrCast(context));
const ptr: *const Context = @ptrCast(@alignCast(context));
applyFn(ptr.*, arg);
}
};
Expand Down
2 changes: 1 addition & 1 deletion test/behavior/extern.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ test "anyopaque extern symbol" {
if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest;

const a = @extern(*anyopaque, .{ .name = "a_mystery_symbol" });
const b: *i32 = @alignCast(@ptrCast(a));
const b: *i32 = @ptrCast(@alignCast(a));
try expect(b.* == 1234);
}

Expand Down
2 changes: 1 addition & 1 deletion test/cases/compile_errors/nested_ptr_cast_bad_operand.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export fn b() void {
_ = @constCast(@volatileCast(123));
}
export fn c() void {
const x: ?*f32 = @constCast(@ptrCast(@addrSpaceCast(@volatileCast(p))));
const x: ?*f32 = @ptrCast(@addrSpaceCast(@constCast(@volatileCast(p))));
_ = x;
}

Expand Down
Loading
Loading