stage2: add compile error for invalid null/undefined pointer cast

This commit is contained in:
InKryption 2022-08-10 17:09:27 +02:00 committed by Andrew Kelley
parent 0e118ed0ac
commit e218b7ea0c
3 changed files with 31 additions and 0 deletions

View File

@ -17272,6 +17272,15 @@ fn zirPtrCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
else
operand;
if (try sema.resolveMaybeUndefVal(block, operand_src, operand)) |operand_val| {
if (!dest_ty.ptrAllowsZero() and operand_val.isUndef()) {
return sema.failWithUseOfUndef(block, operand_src);
}
if (!dest_ty.ptrAllowsZero() and operand_val.isNull()) {
return sema.fail(block, operand_src, "null pointer casted to type {}", .{dest_ty.fmt(sema.mod)});
}
}
const dest_elem_ty = dest_ty.elemType2();
try sema.resolveTypeLayout(block, dest_ty_src, dest_elem_ty);
const dest_align = dest_ty.ptrAlignment(target);

View File

@ -0,0 +1,11 @@
comptime {
var opt_ptr: ?*i32 = null;
const ptr = @ptrCast(*i32, opt_ptr);
_ = ptr;
}
// error
// backend=llvm
// target=native
//
// :3:32: error: null pointer casted to type *i32

View File

@ -0,0 +1,11 @@
comptime {
var undef_ptr: *i32 = undefined;
const ptr = @ptrCast(*i32, undef_ptr);
_ = ptr;
}
// error
// backend=llvm
// target=native
//
// :3:32: error: use of undefined value here causes undefined behavior