diff --git a/std/segmented_list.zig b/std/segmented_list.zig index a89d332556..977a725033 100644 --- a/std/segmented_list.zig +++ b/std/segmented_list.zig @@ -298,21 +298,27 @@ pub fn SegmentedList(comptime T: type, comptime prealloc_item_count: usize) type return &it.list.dynamic_segments[it.shelf_index][it.box_index]; } + + pub fn set(it: &Iterator, index: usize) void { + if (index < prealloc_item_count) { + it.index = index; + return; + } + it.shelf_index = shelfIndex(index); + it.box_index = boxIndex(index, it.shelf_index); + it.shelf_size = shelfSize(it.shelf_index); + } }; pub fn iterator(self: &Self, start_index: usize) Iterator { var it = Iterator { .list = self, - .index = start_index, + .index = undefined, .shelf_index = undefined, .box_index = undefined, .shelf_size = undefined, }; - if (start_index >= prealloc_item_count) { - it.shelf_index = shelfIndex(start_index); - it.box_index = boxIndex(start_index, it.shelf_index); - it.shelf_size = shelfSize(it.shelf_index); - } + it.set(start_index); return it; } }; diff --git a/std/zig/parse.zig b/std/zig/parse.zig index 094d368c23..970c49c4b2 100644 --- a/std/zig/parse.zig +++ b/std/zig/parse.zig @@ -1017,7 +1017,11 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { continue; }, State.Else => |dest| { - while (try eatLineComment(arena, &tok_it, &tree)) |_| { } + const old_index = tok_it.index; + var need_index_restore = false; + while (try eatLineComment(arena, &tok_it, &tree)) |_| { + need_index_restore = true; + } if (eatToken(&tok_it, &tree, Token.Id.Keyword_else)) |else_token| { const node = try arena.construct(ast.Node.Else { .base = ast.Node {.id = ast.Node.Id.Else }, @@ -1031,6 +1035,9 @@ pub fn parse(allocator: &mem.Allocator, source: []const u8) !ast.Tree { try stack.append(State { .Payload = OptionalCtx { .Optional = &node.payload } }); continue; } else { + if (need_index_restore) { + tok_it.set(old_index); + } continue; } }, diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 38e61fe8fe..094c4d51f7 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,3 +1,18 @@ +test "zig fmt: comment after if before another if" { + try testCanonical( + \\test "aoeu" { + \\ if (x) { + \\ foo(); + \\ } + \\ // comment + \\ if (x) { + \\ bar(); + \\ } + \\} + \\ + ); +} + test "zig fmt: line comment between if block and else keyword" { try testTransform( \\test "aoeu" {