Skip to content

Add compile error for @ptrCast from non-0-bit pointer to 0-bit pointer #6432

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

Closed
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
14 changes: 14 additions & 0 deletions src/stage1/ir.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29327,6 +29327,20 @@ static IrInstGen *ir_analyze_ptr_cast(IrAnalyze *ira, IrInst* source_instr, IrIn
return ira->codegen->invalid_inst_gen;
}

if (safety_check_on &&
!type_has_bits(ira->codegen, dest_type) &&
type_has_bits(ira->codegen, if_slice_ptr_type))
{
ErrorMsg *msg = ir_add_error(ira, source_instr,
buf_sprintf("'%s' and '%s' do not have the same in-memory representation",
buf_ptr(&src_type->name), buf_ptr(&dest_type->name)));
add_error_note(ira->codegen, msg, ptr_src->source_node,
buf_sprintf("'%s' has in-memory bits", buf_ptr(&src_type->name)));
add_error_note(ira->codegen, msg, dest_type_src->source_node,
buf_sprintf("'%s' has no in-memory bits", buf_ptr(&dest_type->name)));
return ira->codegen->invalid_inst_gen;
}

// For slices, follow the `ptr` field.
if (is_slice(src_type)) {
TypeStructField *ptr_field = src_type->data.structure.fields[slice_ptr_index];
Expand Down
12 changes: 12 additions & 0 deletions test/compile_errors.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ const tests = @import("tests.zig");
const std = @import("std");

pub fn addCases(cases: *tests.CompileErrorContext) void {
cases.add("casting non-zero-sized-type pointer to zero-sized-type pointer",
\\export fn entry() void {
\\ var i = @as(usize, 0);
\\ var v = @ptrCast(*void, &i);
\\ v.* = {};
\\}
, &[_][]const u8{
"tmp.zig:3:13: error: '*usize' and '*void' do not have the same in-memory representation",
"tmp.zig:3:30: note: '*usize' has in-memory bits",
"tmp.zig:3:22: note: '*void' has no in-memory bits",
});

cases.add("slice sentinel mismatch",
\\export fn entry() void {
\\ const x = @import("std").meta.Vector(3, f32){ 25, 75, 5, 0 };
Expand Down
6 changes: 0 additions & 6 deletions test/stage1/behavior/cast.zig
Original file line number Diff line number Diff line change
Expand Up @@ -459,12 +459,6 @@ fn incrementVoidPtrArray(array: ?*c_void, len: usize) void {
}
}

test "*usize to *void" {
var i = @as(usize, 0);
var v = @ptrCast(*void, &i);
v.* = {};
}

test "compile time int to ptr of function" {
foobar(FUNCTION_CONSTANT);
}
Expand Down