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...@@ -10838,8 +10838,11 @@ static IrInstruction *ir_analyze_cast(IrAnalyze *ira, IrInstruction *source_inst
10838 {10838 {
10839 ZigType *slice_ptr_type = wanted_type->data.structure.fields[slice_ptr_index].type_entry;10839 ZigType *slice_ptr_type = wanted_type->data.structure.fields[slice_ptr_index].type_entry;
10840 assert(slice_ptr_type->id == ZigTypeIdPointer);10840 assert(slice_ptr_type->id == ZigTypeIdPointer);
10841 if (types_match_const_cast_only(ira, slice_ptr_type->data.pointer.child_type,10841 ZigType *array_type = actual_type->data.pointer.child_type;
10842 actual_type->data.pointer.child_type->data.array.child_type, source_node,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,
10843 !slice_ptr_type->data.pointer.is_const).id == ConstCastResultIdOk)10846 !slice_ptr_type->data.pointer.is_const).id == ConstCastResultIdOk)
10844 {10847 {
10845 return ir_resolve_ptr_of_array_to_slice(ira, source_instr, value, wanted_type);10848 return ir_resolve_ptr_of_array_to_slice(ira, source_instr, value, wanted_type);
test/compile_errors.zig+10
...@@ -1,6 +1,16 @@...@@ -1,6 +1,16 @@
1const tests = @import("tests.zig");1const tests = @import("tests.zig");
22
3pub fn addCases(cases: *tests.CompileErrorContext) void {3pub 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
4 cases.add(14 cases.add(
5 "deref slice and get len field",15 "deref slice and get len field",
6 \\export fn entry() void {16 \\export fn entry() void {