From b16229da1de90295b4d173f1a0ddbca677e8cdf2 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 17 Sep 2018 19:41:11 -0400 Subject: [PATCH] add compile error for @ptrCast 0 bit type to non-0 bit type --- src/ir.cpp | 20 +++++++++++++++++--- test/compile_errors.zig | 13 +++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/ir.cpp b/src/ir.cpp index d073f3296..0cb09df01 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -11528,7 +11528,13 @@ static bool optional_value_is_null(ConstExprValue *val) { static ZigType *ir_analyze_bin_op_cmp(IrAnalyze *ira, IrInstructionBinOp *bin_op_instruction) { Error err; IrInstruction *op1 = bin_op_instruction->op1->other; + if (type_is_invalid(op1->value.type)) + return ira->codegen->builtin_types.entry_invalid; + IrInstruction *op2 = bin_op_instruction->op2->other; + if (type_is_invalid(op2->value.type)) + return ira->codegen->builtin_types.entry_invalid; + AstNode *source_node = bin_op_instruction->base.source_node; IrBinOp op_id = bin_op_instruction->op_id; @@ -20190,11 +20196,19 @@ static ZigType *ir_analyze_instruction_ptr_cast(IrAnalyze *ira, IrInstructionPtr instruction->base.source_node, nullptr, ptr); casted_ptr->value.type = dest_type; + if (type_has_bits(dest_type) && !type_has_bits(src_type)) { + ErrorMsg *msg = ir_add_error(ira, &instruction->base, + 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->source_node, + buf_sprintf("'%s' has no in-memory bits", buf_ptr(&src_type->name))); + add_error_note(ira->codegen, msg, dest_type_value->source_node, + buf_sprintf("'%s' has in-memory bits", buf_ptr(&dest_type->name))); + return ira->codegen->builtin_types.entry_invalid; + } + // Keep the bigger alignment, it can only help- // unless the target is zero bits. - if ((err = type_resolve(ira->codegen, dest_type, ResolveStatusZeroBitsKnown))) - return ira->codegen->builtin_types.entry_invalid; - IrInstruction *result; if (src_align_bytes > dest_align_bytes && type_has_bits(dest_type)) { result = ir_align_cast(ira, casted_ptr, src_align_bytes, false); diff --git a/test/compile_errors.zig b/test/compile_errors.zig index d1e9f6d03..a1dd33fb4 100644 --- a/test/compile_errors.zig +++ b/test/compile_errors.zig @@ -1,6 +1,19 @@ const tests = @import("tests.zig"); pub fn addCases(cases: *tests.CompileErrorContext) void { + cases.add( + "@ptrCast a 0 bit type to a non- 0 bit type", + \\export fn entry() bool { + \\ var x: u0 = 0; + \\ const p = @ptrCast(?*u0, &x); + \\ return p == null; + \\} + , + ".tmp_source.zig:3:15: error: '*u0' and '?*u0' do not have the same in-memory representation", + ".tmp_source.zig:3:31: note: '*u0' has no in-memory bits", + ".tmp_source.zig:3:24: note: '?*u0' has in-memory bits", + ); + cases.add( "comparing a non-optional pointer against null", \\export fn entry() void {