Skip to content

Commit c580379

Browse files
committed
Add compile error for @ptrCast from 0-bit pointer to non-0-bit pointer
Fixes #1469
1 parent 288198e commit c580379

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/ir.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29460,6 +29460,20 @@ static IrInstGen *ir_analyze_ptr_cast(IrAnalyze *ira, IrInst* source_instr, IrIn
2946029460
return ira->codegen->invalid_inst_gen;
2946129461
}
2946229462

29463+
if (safety_check_on &&
29464+
!type_has_bits(ira->codegen, dest_type) &&
29465+
type_has_bits(ira->codegen, if_slice_ptr_type))
29466+
{
29467+
ErrorMsg *msg = ir_add_error(ira, source_instr,
29468+
buf_sprintf("'%s' and '%s' do not have the same in-memory representation",
29469+
buf_ptr(&src_type->name), buf_ptr(&dest_type->name)));
29470+
add_error_note(ira->codegen, msg, ptr_src->source_node,
29471+
buf_sprintf("'%s' has in-memory bits", buf_ptr(&src_type->name)));
29472+
add_error_note(ira->codegen, msg, dest_type_src->source_node,
29473+
buf_sprintf("'%s' has no in-memory bits", buf_ptr(&dest_type->name)));
29474+
return ira->codegen->invalid_inst_gen;
29475+
}
29476+
2946329477
// For slices, follow the `ptr` field.
2946429478
if (is_slice(src_type)) {
2946529479
TypeStructField *ptr_field = src_type->data.structure.fields[slice_ptr_index];

test/compile_errors.zig

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@ const tests = @import("tests.zig");
22
const std = @import("std");
33

44
pub fn addCases(cases: *tests.CompileErrorContext) void {
5+
cases.add("casting non-zero-sized-type pointer to zero-sized-type pointer",
6+
\\export fn entry() void {
7+
\\ var i = @as(usize, 0);
8+
\\ var v = @ptrCast(*void, &i);
9+
\\ v.* = {};
10+
\\}
11+
, &[_][]const u8{
12+
"tmp.zig:3:13: error: '*usize' and '*void' do not have the same in-memory representation",
13+
"tmp.zig:3:30: note: '*usize' has in-memory bits",
14+
"tmp.zig:3:22: note: '*void' has no in-memory bits",
15+
});
16+
517
cases.add("slice sentinel mismatch",
618
\\export fn entry() void {
719
\\ const y: [:1]const u8 = &[_:2]u8{ 1, 2 };

0 commit comments

Comments
 (0)