Skip to content

Commit 5d51d44

Browse files
committed
fix slice of slice with sentinel but no end index
example: ```zig test { var foo = ""; _ = foo[0..][0.. :0]; } ``` A `.slice_sentinel` ast node may not have an end index.
1 parent 2e40a1d commit 5d51d44

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

lib/std/zig/AstGen.zig

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -885,7 +885,7 @@ fn expr(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) InnerE
885885
const lhs_is_slice_sentinel = lhs_tag == .slice_sentinel;
886886
const lhs_is_open_slice = lhs_tag == .slice_open or
887887
(lhs_is_slice_sentinel and tree.fullSlice(full.ast.sliced).?.ast.end == 0);
888-
if (node_tags[node] != .slice_open and
888+
if (full.ast.end != 0 and
889889
lhs_is_open_slice and
890890
nodeIsTriviallyZero(tree, full.ast.start))
891891
{
@@ -897,7 +897,7 @@ fn expr(gz: *GenZir, scope: *Scope, ri: ResultInfo, node: Ast.Node.Index) InnerE
897897
} else try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, node_datas[full.ast.sliced].rhs);
898898

899899
const cursor = maybeAdvanceSourceCursorToMainToken(gz, node);
900-
const len = if (full.ast.end != 0) try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, full.ast.end) else .none;
900+
const len = try expr(gz, scope, .{ .rl = .{ .coerced_ty = .usize_type } }, full.ast.end);
901901
const sentinel = if (full.ast.sentinel != 0) try expr(gz, scope, .{ .rl = .none }, full.ast.sentinel) else .none;
902902
try emitDbgStmt(gz, cursor);
903903
const result = try gz.addPlNode(.slice_length, node, Zir.Inst.SliceLength{

test/behavior/slice.zig

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,23 @@ test "comptime slice of slice preserves comptime var" {
9898
}
9999
}
100100

101+
test "open slice of open slice with sentinel" {
102+
if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
103+
104+
var slice: [:0]const u8 = "hello";
105+
_ = &slice;
106+
107+
comptime assert(@TypeOf(slice[0..][0.. :0]) == [:0]const u8);
108+
try expect(slice[0..][0.. :0].len == 5);
109+
try expect(slice[0..][0.. :0][0] == 'h');
110+
try expect(slice[0..][0.. :0][5] == 0);
111+
112+
comptime assert(@TypeOf(slice[1..][0.. :0]) == [:0]const u8);
113+
try expect(slice[1..][0.. :0].len == 4);
114+
try expect(slice[1..][0.. :0][0] == 'e');
115+
try expect(slice[1..][0.. :0][4] == 0);
116+
}
117+
101118
test "slice of type" {
102119
comptime {
103120
var types_array = [_]type{ i32, f64, type };

0 commit comments

Comments
 (0)