Commit 4a64f26627

emekoi <emekankurumeh@outlook.com>
2019-03-31 21:19:13
added error for implicit cast from *const T to *[1]T. credit: @kristate
1 parent a4afacd
Changed files (2)
src/ir.cpp
@@ -11090,6 +11090,7 @@ static IrInstruction *ir_analyze_ptr_to_array(IrAnalyze *ira, IrInstruction *sou
     Error err;
     if ((err = type_resolve(ira->codegen, target->value.type->data.pointer.child_type, ResolveStatusAlignmentKnown)))
         return ira->codegen->invalid_instruction;
+    assert((wanted_type->data.pointer.is_const && target->value.type->data.pointer.is_const) || !target->value.type->data.pointer.is_const);
     wanted_type = adjust_ptr_align(ira->codegen, wanted_type, get_ptr_align(ira->codegen, target->value.type));
     ZigType *array_type = wanted_type->data.pointer.child_type;
     assert(array_type->id == ZigTypeIdArray);
@@ -11651,7 +11652,11 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
         if (array_type->id == ZigTypeIdArray && array_type->data.array.len == 1 &&
             types_match_const_cast_only(ira, array_type->data.array.child_type,
             actual_type->data.pointer.child_type, source_node,
-            !wanted_type->data.pointer.is_const).id == ConstCastResultIdOk)
+            !wanted_type->data.pointer.is_const).id == ConstCastResultIdOk &&
+            // This should be the job of `types_match_const_cast_only`
+            // but `types_match_const_cast_only` only gets info for child_types
+            ((wanted_type->data.pointer.is_const && actual_type->data.pointer.is_const) ||
+            !actual_type->data.pointer.is_const))
         {
             if ((err = type_resolve(ira->codegen, wanted_type->data.pointer.child_type,
                             ResolveStatusAlignmentKnown)))
test/compile_errors.zig
@@ -5869,4 +5869,27 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
         \\    comptime testCompileLog(Bar{.X = 123});
         \\}
     , "tmp.zig:6:5: error: found compile log statement");
+
+    cases.add(
+        "attempted implicit cast from *const T to *[1]T",
+        \\export fn entry(byte: u8) void {
+        \\    const w: i32 = 1234;
+        \\    var x: *const i32 = &w;
+        \\    var y: *[1]i32 = x;
+        \\    y[0] += 1;
+        \\}
+    ,
+        "tmp.zig:4:22: error: expected type '*[1]i32', found '*const i32'",
+        "tmp.zig:4:22: note: pointer type child 'i32' cannot cast into pointer type child '[1]i32'",
+    );
+
+    cases.add(
+        "attempted implicit cast from *const T to []T",
+        \\export fn entry() void {
+        \\    const u: u32 = 42;
+        \\    const x: []u32 = &u;
+        \\}
+    ,
+        "tmp.zig:3:23: error: expected type '[]u32', found '*const u32'",
+    );
 }