Commit a385547786

LemonBoy <thatlemon@gmail.com>
2020-02-20 13:14:19
ir: Compile error on result_loc type mismatch w/ slicing
Closes #4508
1 parent c49ab04
Changed files (3)
src/ir.cpp
@@ -26677,9 +26677,19 @@ static IrInstGen *ir_analyze_instruction_slice(IrAnalyze *ira, IrInstSrcSlice *i
 
     IrInstGen *result_loc = ir_resolve_result(ira, &instruction->base.base, instruction->result_loc,
             return_type, nullptr, true, true);
-    if (type_is_invalid(result_loc->value->type) || result_loc->value->type->id == ZigTypeIdUnreachable) {
-        return result_loc;
+
+    if (result_loc != nullptr) {
+        if (type_is_invalid(result_loc->value->type) || result_loc->value->type->id == ZigTypeIdUnreachable) {
+            return result_loc;
+        }
+        IrInstGen *dummy_value = ir_const(ira, &instruction->base.base, return_type);
+        dummy_value->value->special = ConstValSpecialRuntime;
+        IrInstGen *dummy_result = ir_implicit_cast2(ira, &instruction->base.base,
+                dummy_value, result_loc->value->type->data.pointer.child_type);
+        if (type_is_invalid(dummy_result->value->type))
+            return ira->codegen->invalid_inst_gen;
     }
+
     return ir_build_slice_gen(ira, &instruction->base.base, return_type,
         ptr_ptr, casted_start, end, instruction->safety_check_on, result_loc);
 }
test/compile_errors.zig
@@ -3,6 +3,18 @@ const builtin = @import("builtin");
 const Target = @import("std").Target;
 
 pub fn addCases(cases: *tests.CompileErrorContext) void {
+    cases.addTest("slice to pointer conversion mismatch",
+        \\pub fn bytesAsSlice(bytes: var) [*]align(1) const u16 {
+        \\    return @ptrCast([*]align(1) const u16, bytes.ptr)[0..1];
+        \\}
+        \\test "bytesAsSlice" {
+        \\    const bytes = [_]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
+        \\    const slice = bytesAsSlice(bytes[0..]);
+        \\}
+    , &[_][]const u8{
+        "tmp.zig:2:54: error: expected type '[*]align(1) const u16', found '[]align(1) const u16'",
+    });
+
     cases.addTest("access invalid @typeInfo decl",
         \\const A = B;
         \\test "Crash" {
test/tests.zig
@@ -677,8 +677,10 @@ pub const StackTracesContext = struct {
             const got: []const u8 = got_result: {
                 var buf = try Buffer.initSize(b.allocator, 0);
                 defer buf.deinit();
-                var bytes = stderr.toSliceConst();
-                if (bytes.len != 0 and bytes[bytes.len - 1] == '\n') bytes = bytes[0 .. bytes.len - 1];
+                const bytes = if (stderr.endsWith("\n"))
+                    stderr.toSliceConst()[0 .. stderr.len() - 1]
+                else
+                    stderr.toSliceConst()[0..stderr.len()];
                 var it = mem.separate(bytes, "\n");
                 process_lines: while (it.next()) |line| {
                     if (line.len == 0) continue;