authorgravatar for michael.dusan@gmail.comMichael Dusan <michael.dusan@gmail.com> 2021-01-18 00:36:37-05:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2021-01-30 11:19:25+02:00
logf9b85c6e50e22153aff4c87e2ba943d68f24ee8c
tree0a5825a3c0f930f80f08f596c6f1750d57366252
parent3d4eeafb47f97e5057d36fe2c3ed061cf0c70a63

stage1: add error for slice.len incr beyond bounds

comptime direct slice.len increment dodges bounds checking but we can emit an error for it, at least in the simple case. - promote original assert to compile-error - add test case closes #7810

2 files changed, 18 insertions(+), 3 deletions(-)

src/stage1/ir.cpp+4-3
......@@ -22655,9 +22655,10 @@ static IrInstGen *ir_analyze_instruction_elem_ptr(IrAnalyze *ira, IrInstSrcElemP
2265522655 if (ptr_field->data.x_ptr.data.base_array.array_val->data.x_array.special !=
2265622656 ConstArraySpecialBuf)
2265722657 {
22658 ir_assert(new_index <
22659 ptr_field->data.x_ptr.data.base_array.array_val->type->data.array.len,
22660 &elem_ptr_instruction->base.base);
22658 if (new_index >= ptr_field->data.x_ptr.data.base_array.array_val->type->data.array.len) {
22659 ir_add_error(ira, &elem_ptr_instruction->base.base, buf_sprintf("out of bounds slice"));
22660 return ira->codegen->invalid_inst_gen;
22661 }
2266122662 }
2266222663 out_val->data.x_ptr.special = ConstPtrSpecialBaseArray;
2266322664 out_val->data.x_ptr.data.base_array.array_val =
test/compile_errors.zig+14
......@@ -7981,6 +7981,20 @@ pub fn addCases(cases: *tests.CompileErrorContext) void {
79817981 "tmp.zig:7:37: note: referenced here",
79827982 });
79837983
7984 // issue #7810
7985 cases.add("comptime slice-len increment beyond bounds",
7986 \\export fn foo_slice_len_increment_beyond_bounds() void {
7987 \\ comptime {
7988 \\ var buf_storage: [8]u8 = undefined;
7989 \\ var buf: []const u8 = buf_storage[0..];
7990 \\ buf.len += 1;
7991 \\ buf[8] = 42;
7992 \\ }
7993 \\}
7994 , &[_][]const u8{
7995 ":6:12: error: out of bounds slice",
7996 });
7997
79847998 cases.add("comptime slice-sentinel is out of bounds (unterminated)",
79857999 \\export fn foo_array() void {
79868000 \\ comptime {