authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-09-20 12:24:51-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2018-09-20 12:24:51-04:00
log9c8dfadbb1b95703a1503ae3a508f5acc29e7695
treee5884cb00c039385d68b1153a130cd6df0f80b77
parentf8fe517d126d582e37ab4537fe9fd42f0531f44b
signaturelock-open Commit is signed but in an unrecognized format.

add compile error for casting const array to mutable slice

See #1565

2 files changed, 15 insertions(+), 2 deletions(-)

src/ir.cpp+5-2
......@@ -10838,8 +10838,11 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
1083810838 {
1083910839 ZigType *slice_ptr_type = wanted_type->data.structure.fields[slice_ptr_index].type_entry;
1084010840 assert(slice_ptr_type->id == ZigTypeIdPointer);
10841 if (types_match_const_cast_only(ira, slice_ptr_type->data.pointer.child_type,
10842 actual_type->data.pointer.child_type->data.array.child_type, source_node,
10841 ZigType *array_type = actual_type->data.pointer.child_type;
10842 bool const_ok = (slice_ptr_type->data.pointer.is_const || array_type->data.array.len == 0
10843 || !actual_type->data.pointer.is_const);
10844 if (const_ok && types_match_const_cast_only(ira, slice_ptr_type->data.pointer.child_type,
10845 array_type->data.array.child_type, source_node,
1084310846 !slice_ptr_type->data.pointer.is_const).id == ConstCastResultIdOk)
1084410847 {
1084510848 return ir_resolve_ptr_of_array_to_slice(ira, source_instr, value, wanted_type);
test/compile_errors.zig+10
......@@ -1,6 +1,16 @@
11const tests = @import("tests.zig");
22
33pub fn addCases(cases: *tests.CompileErrorContext) void {
4 cases.add(
5 "implicit cast const array to mutable slice",
6 \\export fn entry() void {
7 \\ const buffer: [1]u8 = []u8{8};
8 \\ const sliceA: []u8 = &buffer;
9 \\}
10 ,
11 ".tmp_source.zig:3:27: error: expected type '[]u8', found '*const [1]u8'",
12 );
13
414 cases.add(
515 "deref slice and get len field",
616 \\export fn entry() void {