Commit 6695fa4f32

LemonBoy <thatlemon@gmail.com>
2020-04-01 18:30:40
ir: Fix comparison of ?T values
The code assumed that every ?T had a pointer child type T, add some more checks to make sure the type is effectively a pointer. Closes #4789
1 parent 212e235
Changed files (2)
src/ir.cpp
@@ -11454,10 +11454,8 @@ static ConstCastOnly types_match_const_cast_only(IrAnalyze *ira, ZigType *wanted
     bool actual_allows_zero = ptr_allows_addr_zero(actual_type);
     bool wanted_is_c_ptr = wanted_type->id == ZigTypeIdPointer && wanted_type->data.pointer.ptr_len == PtrLenC;
     bool actual_is_c_ptr = actual_type->id == ZigTypeIdPointer && actual_type->data.pointer.ptr_len == PtrLenC;
-    bool wanted_opt_or_ptr = wanted_ptr_type != nullptr &&
-        (wanted_type->id == ZigTypeIdPointer || wanted_type->id == ZigTypeIdOptional);
-    bool actual_opt_or_ptr = actual_ptr_type != nullptr &&
-        (actual_type->id == ZigTypeIdPointer || actual_type->id == ZigTypeIdOptional);
+    bool wanted_opt_or_ptr = wanted_ptr_type != nullptr && wanted_ptr_type->id == ZigTypeIdPointer;
+    bool actual_opt_or_ptr = actual_ptr_type != nullptr && actual_ptr_type->id == ZigTypeIdPointer;
     if (wanted_opt_or_ptr && actual_opt_or_ptr) {
         bool ok_null_term_ptrs =
             wanted_ptr_type->data.pointer.sentinel == nullptr ||
test/compile_errors.zig
@@ -2,6 +2,19 @@ const tests = @import("tests.zig");
 const std = @import("std");
 
 pub fn addCases(cases: *tests.CompileErrorContext) void {
+    cases.addTest("cast between ?T where T is not a pointer",
+        \\pub const fnty1 = ?fn (i8) void;
+        \\pub const fnty2 = ?fn (u64) void;
+        \\export fn entry() void {
+        \\    var a: fnty1 = undefined;
+        \\    var b: fnty2 = undefined;
+        \\    a = b;
+        \\}
+    , &[_][]const u8{
+        "tmp.zig:6:9: error: expected type '?fn(i8) void', found '?fn(u64) void'",
+        "tmp.zig:6:9: note: optional type child 'fn(u64) void' cannot cast into optional type child 'fn(i8) void'",
+    });
+
     cases.addTest("unused variable error on errdefer",
         \\fn foo() !void {
         \\    errdefer |a| unreachable;